privatebin.js 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @see {@link https://github.com/PrivateBin/PrivateBin}
  7. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  8. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  9. * @version 1.1.1
  10. * @name PrivateBin
  11. * @namespace
  12. */
  13. /** global: Base64 */
  14. /** global: DOMPurify */
  15. /** global: FileReader */
  16. /** global: RawDeflate */
  17. /** global: history */
  18. /** global: navigator */
  19. /** global: prettyPrint */
  20. /** global: prettyPrintOne */
  21. /** global: showdown */
  22. /** global: sjcl */
  23. // Immediately start random number generator collector.
  24. sjcl.random.startCollectors();
  25. // main application start, called when DOM is fully loaded
  26. jQuery(document).ready(function() {
  27. // run main controller
  28. $.PrivateBin.Controller.init();
  29. });
  30. jQuery.PrivateBin = function($, sjcl, Base64, RawDeflate) {
  31. 'use strict';
  32. /**
  33. * static Helper methods
  34. *
  35. * @name Helper
  36. * @class
  37. */
  38. var Helper = (function () {
  39. var me = {};
  40. /**
  41. * character to HTML entity lookup table
  42. *
  43. * @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
  44. * @name Helper.entityMap
  45. * @private
  46. * @enum {Object}
  47. * @readonly
  48. */
  49. var entityMap = {
  50. '&': '&',
  51. '<': '&lt;',
  52. '>': '&gt;',
  53. '"': '&quot;',
  54. "'": '&#39;',
  55. '/': '&#x2F;',
  56. '`': '&#x60;',
  57. '=': '&#x3D;'
  58. };
  59. /**
  60. * cache for script location
  61. *
  62. * @name Helper.baseUri
  63. * @private
  64. * @enum {string|null}
  65. */
  66. var baseUri = null;
  67. /**
  68. * converts a duration (in seconds) into human friendly approximation
  69. *
  70. * @name Helper.secondsToHuman
  71. * @function
  72. * @param {number} seconds
  73. * @return {Array}
  74. */
  75. me.secondsToHuman = function(seconds)
  76. {
  77. var v;
  78. if (seconds < 60)
  79. {
  80. v = Math.floor(seconds);
  81. return [v, 'second'];
  82. }
  83. if (seconds < 60 * 60)
  84. {
  85. v = Math.floor(seconds / 60);
  86. return [v, 'minute'];
  87. }
  88. if (seconds < 60 * 60 * 24)
  89. {
  90. v = Math.floor(seconds / (60 * 60));
  91. return [v, 'hour'];
  92. }
  93. // If less than 2 months, display in days:
  94. if (seconds < 60 * 60 * 24 * 60)
  95. {
  96. v = Math.floor(seconds / (60 * 60 * 24));
  97. return [v, 'day'];
  98. }
  99. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  100. return [v, 'month'];
  101. }
  102. /**
  103. * text range selection
  104. *
  105. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  106. * @name Helper.selectText
  107. * @function
  108. * @param {HTMLElement} element
  109. */
  110. me.selectText = function(element)
  111. {
  112. var range, selection;
  113. // MS
  114. if (document.body.createTextRange) {
  115. range = document.body.createTextRange();
  116. range.moveToElementText(element);
  117. range.select();
  118. } else if (window.getSelection) {
  119. selection = window.getSelection();
  120. range = document.createRange();
  121. range.selectNodeContents(element);
  122. selection.removeAllRanges();
  123. selection.addRange(range);
  124. }
  125. }
  126. /**
  127. * set text of a jQuery element (required for IE),
  128. *
  129. * @name Helper.setElementText
  130. * @function
  131. * @param {jQuery} $element - a jQuery element
  132. * @param {string} text - the text to enter
  133. */
  134. me.setElementText = function($element, text)
  135. {
  136. // For IE<10: Doesn't support white-space:pre-wrap; so we have to do this...
  137. if ($('#oldienotice').is(':visible')) {
  138. var html = me.htmlEntities(text).replace(/\n/ig, '\r\n<br>');
  139. $element.html('<pre>' + html + '</pre>');
  140. }
  141. // for other (sane) browsers:
  142. else
  143. {
  144. $element.text(text);
  145. }
  146. }
  147. /**
  148. * convert URLs to clickable links.
  149. * URLs to handle:
  150. * <pre>
  151. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  152. * http://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  153. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  154. * </pre>
  155. *
  156. * @name Helper.urls2links
  157. * @function
  158. * @param {Object} $element - a jQuery DOM element
  159. */
  160. me.urls2links = function($element)
  161. {
  162. var markup = '<a href="$1" rel="nofollow">$1</a>';
  163. $element.html(
  164. $element.html().replace(
  165. /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+*-]+(?![\w\s?&.\/;#~%"=-]*>))/ig,
  166. markup
  167. )
  168. );
  169. $element.html(
  170. $element.html().replace(
  171. /((magnet):[\w?=&.\/-;#@~%+*-]+)/ig,
  172. markup
  173. )
  174. );
  175. }
  176. /**
  177. * minimal sprintf emulation for %s and %d formats
  178. *
  179. * Note that this function needs the parameters in the same order as the
  180. * format strings appear in the string, contrary to the original.
  181. *
  182. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  183. * @name Helper.sprintf
  184. * @function
  185. * @param {string} format
  186. * @param {...*} args - one or multiple parameters injected into format string
  187. * @return {string}
  188. */
  189. me.sprintf = function()
  190. {
  191. var args = Array.prototype.slice.call(arguments);
  192. var format = args[0],
  193. i = 1;
  194. return format.replace(/%(s|d)/g, function (m) {
  195. // m is the matched format, e.g. %s, %d
  196. var val = args[i];
  197. // A switch statement so that the formatter can be extended.
  198. switch (m)
  199. {
  200. case '%d':
  201. val = parseFloat(val);
  202. if (isNaN(val)) {
  203. val = 0;
  204. }
  205. break;
  206. default:
  207. // Default is %s
  208. }
  209. ++i;
  210. return val;
  211. });
  212. }
  213. /**
  214. * get value of cookie, if it was set, empty string otherwise
  215. *
  216. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  217. * @name Helper.getCookie
  218. * @function
  219. * @param {string} cname - may not be empty
  220. * @return {string}
  221. */
  222. me.getCookie = function(cname) {
  223. var name = cname + '=',
  224. ca = document.cookie.split(';');
  225. for (var i = 0; i < ca.length; ++i) {
  226. var c = ca[i];
  227. while (c.charAt(0) === ' ')
  228. {
  229. c = c.substring(1);
  230. }
  231. if (c.indexOf(name) === 0)
  232. {
  233. return c.substring(name.length, c.length);
  234. }
  235. }
  236. return '';
  237. }
  238. /**
  239. * get the current location (without search or hash part of the URL),
  240. * eg. http://example.com/path/?aaaa#bbbb --> http://example.com/path/
  241. *
  242. * @name Helper.baseUri
  243. * @function
  244. * @return {string}
  245. */
  246. me.baseUri = function()
  247. {
  248. // check for cached version
  249. if (baseUri !== null) {
  250. return baseUri;
  251. }
  252. baseUri = window.location.origin + window.location.pathname;
  253. return baseUri;
  254. }
  255. /**
  256. * convert all applicable characters to HTML entities
  257. *
  258. * @see {@link https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content}
  259. * @name Helper.htmlEntities
  260. * @function
  261. * @param {string} str
  262. * @return {string} escaped HTML
  263. */
  264. me.htmlEntities = function(str) {
  265. return String(str).replace(
  266. /[&<>"'`=\/]/g, function(s) {
  267. return entityMap[s];
  268. });
  269. }
  270. /**
  271. * resets state, used for unit testing
  272. *
  273. * @name Helper.reset
  274. * @function
  275. */
  276. me.reset = function()
  277. {
  278. baseUri = null;
  279. }
  280. return me;
  281. })();
  282. /**
  283. * internationalization module
  284. *
  285. * @name I18n
  286. * @class
  287. */
  288. var I18n = (function () {
  289. var me = {};
  290. /**
  291. * const for string of loaded language
  292. *
  293. * @name I18n.languageLoadedEvent
  294. * @private
  295. * @prop {string}
  296. * @readonly
  297. */
  298. var languageLoadedEvent = 'languageLoaded';
  299. /**
  300. * supported languages, minus the built in 'en'
  301. *
  302. * @name I18n.supportedLanguages
  303. * @private
  304. * @prop {string[]}
  305. * @readonly
  306. */
  307. var supportedLanguages = ['de', 'es', 'fr', 'it', 'no', 'pl', 'pt', 'oc', 'ru', 'sl', 'zh'];
  308. /**
  309. * built in language
  310. *
  311. * @name I18n.language
  312. * @private
  313. * @prop {string|null}
  314. */
  315. var language = null;
  316. /**
  317. * translation cache
  318. *
  319. * @name I18n.translations
  320. * @private
  321. * @enum {Object}
  322. */
  323. var translations = {};
  324. /**
  325. * translate a string, alias for I18n.translate
  326. *
  327. * @name I18n._
  328. * @function
  329. * @param {jQuery} $element - optional
  330. * @param {string} messageId
  331. * @param {...*} args - one or multiple parameters injected into placeholders
  332. * @return {string}
  333. */
  334. me._ = function()
  335. {
  336. return me.translate.apply(this, arguments);
  337. }
  338. /**
  339. * translate a string
  340. *
  341. * Optionally pass a jQuery element as the first parameter, to automatically
  342. * let the text of this element be replaced. In case the (asynchronously
  343. * loaded) language is not downloadet yet, this will make sure the string
  344. * is replaced when it is actually loaded.
  345. * So for easy translations passing the jQuery object to apply it to is
  346. * more save, especially when they are loaded in the beginning.
  347. *
  348. * @name I18n.translate
  349. * @function
  350. * @param {jQuery} $element - optional
  351. * @param {string} messageId
  352. * @param {...*} args - one or multiple parameters injected into placeholders
  353. * @return {string}
  354. */
  355. me.translate = function()
  356. {
  357. // convert parameters to array
  358. var args = Array.prototype.slice.call(arguments),
  359. messageId,
  360. $element = null;
  361. // parse arguments
  362. if (args[0] instanceof jQuery) {
  363. // optional jQuery element as first parameter
  364. $element = args[0];
  365. args.shift();
  366. }
  367. // extract messageId from arguments
  368. var usesPlurals = $.isArray(args[0]);
  369. if (usesPlurals) {
  370. // use the first plural form as messageId, otherwise the singular
  371. messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
  372. } else {
  373. messageId = args[0];
  374. }
  375. if (messageId.length === 0) {
  376. return messageId;
  377. }
  378. // if no translation string cannot be found (in translations object)
  379. if (!translations.hasOwnProperty(messageId) || language === null) {
  380. // if language is still loading and we have an elemt assigned
  381. if (language === null && $element !== null) {
  382. // handle the error by attaching the language loaded event
  383. var orgArguments = arguments;
  384. $(document).on(languageLoadedEvent, function () {
  385. // log to show that the previous error could be mitigated
  386. console.warn('Fix missing translation of \'' + messageId + '\' with now loaded language ' + language);
  387. // re-execute this function
  388. me.translate.apply(this, orgArguments);
  389. });
  390. // and fall back to English for now until the real language
  391. // file is loaded
  392. }
  393. // for all other langauges than English for which this behaviour
  394. // is expected as it is built-in, log error
  395. if (language !== null && language !== 'en') {
  396. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  397. // fallback to English
  398. }
  399. // save English translation (should be the same on both sides)
  400. translations[messageId] = args[0];
  401. }
  402. // lookup plural translation
  403. if (usesPlurals && $.isArray(translations[messageId])) {
  404. var n = parseInt(args[1] || 1, 10),
  405. key = me.getPluralForm(n),
  406. maxKey = translations[messageId].length - 1;
  407. if (key > maxKey) {
  408. key = maxKey;
  409. }
  410. args[0] = translations[messageId][key];
  411. args[1] = n;
  412. } else {
  413. // lookup singular translation
  414. args[0] = translations[messageId];
  415. }
  416. // format string
  417. var output = Helper.sprintf.apply(this, args);
  418. // if $element is given, apply text to element
  419. if ($element !== null) {
  420. // get last text node of element
  421. var content = $element.contents();
  422. if (content.length > 1) {
  423. content[content.length - 1].nodeValue = ' ' + output;
  424. } else {
  425. $element.text(output);
  426. }
  427. }
  428. return output;
  429. }
  430. /**
  431. * per language functions to use to determine the plural form
  432. *
  433. * @see {@link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
  434. * @name I18n.getPluralForm
  435. * @function
  436. * @param {int} n
  437. * @return {int} array key
  438. */
  439. me.getPluralForm = function(n) {
  440. switch (language)
  441. {
  442. case 'fr':
  443. case 'oc':
  444. case 'zh':
  445. return (n > 1 ? 1 : 0);
  446. case 'pl':
  447. return (n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  448. case 'ru':
  449. return (n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
  450. case 'sl':
  451. return (n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0)));
  452. // de, en, es, it, no, pt
  453. default:
  454. return (n !== 1 ? 1 : 0);
  455. }
  456. }
  457. /**
  458. * load translations into cache
  459. *
  460. * @name I18n.loadTranslations
  461. * @function
  462. */
  463. me.loadTranslations = function()
  464. {
  465. var newLanguage = Helper.getCookie('lang');
  466. // auto-select language based on browser settings
  467. if (newLanguage.length === 0) {
  468. newLanguage = (navigator.language || navigator.userLanguage).substring(0, 2);
  469. }
  470. // if language is already used skip update
  471. if (newLanguage === language) {
  472. return;
  473. }
  474. // if language is built-in (English) skip update
  475. if (newLanguage === 'en') {
  476. language = 'en';
  477. return;
  478. }
  479. // if language is not supported, show error
  480. if (supportedLanguages.indexOf(newLanguage) === -1) {
  481. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  482. language = 'en';
  483. return;
  484. }
  485. // load strings from JSON
  486. $.getJSON('i18n/' + newLanguage + '.json', function(data) {
  487. language = newLanguage;
  488. translations = data;
  489. $(document).triggerHandler(languageLoadedEvent);
  490. }).fail(function (data, textStatus, errorMsg) {
  491. console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
  492. language = 'en';
  493. });
  494. }
  495. /**
  496. * resets state, used for unit testing
  497. *
  498. * @name I18n.reset
  499. * @function
  500. */
  501. me.reset = function(mockLanguage, mockTranslations)
  502. {
  503. language = mockLanguage || null;
  504. translations = mockTranslations || {};
  505. }
  506. return me;
  507. })();
  508. /**
  509. * handles everything related to en/decryption
  510. *
  511. * @name CryptTool
  512. * @class
  513. */
  514. var CryptTool = (function () {
  515. var me = {};
  516. /**
  517. * compress a message (deflate compression), returns base64 encoded data
  518. *
  519. * @name CryptTool.compress
  520. * @function
  521. * @private
  522. * @param {string} message
  523. * @return {string} base64 data
  524. */
  525. function compress(message)
  526. {
  527. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  528. }
  529. /**
  530. * decompress a message compressed with cryptToolcompress()
  531. *
  532. * @name CryptTool.decompress
  533. * @function
  534. * @private
  535. * @param {string} data - base64 data
  536. * @return {string} message
  537. */
  538. function decompress(data)
  539. {
  540. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  541. }
  542. /**
  543. * compress, then encrypt message with given key and password
  544. *
  545. * @name CryptTool.cipher
  546. * @function
  547. * @param {string} key
  548. * @param {string} password
  549. * @param {string} message
  550. * @return {string} data - JSON with encrypted data
  551. */
  552. me.cipher = function(key, password, message)
  553. {
  554. // Galois Counter Mode, keysize 256 bit, authentication tag 128 bit
  555. var options = {
  556. mode: 'gcm',
  557. ks: 256,
  558. ts: 128
  559. };
  560. if ((password || '').trim().length === 0) {
  561. return sjcl.encrypt(key, compress(message), options);
  562. }
  563. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), compress(message), options);
  564. }
  565. /**
  566. * decrypt message with key, then decompress
  567. *
  568. * @name CryptTool.decipher
  569. * @function
  570. * @param {string} key
  571. * @param {string} password
  572. * @param {string} data - JSON with encrypted data
  573. * @return {string} decrypted message
  574. */
  575. me.decipher = function(key, password, data)
  576. {
  577. if (data !== undefined) {
  578. try {
  579. return decompress(sjcl.decrypt(key, data));
  580. } catch(err) {
  581. try {
  582. return decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  583. } catch(e) {
  584. // ignore error, because ????? @TODO
  585. }
  586. }
  587. }
  588. return '';
  589. }
  590. /**
  591. * checks whether the crypt tool has collected enough entropy
  592. *
  593. * @name CryptTool.isEntropyReady
  594. * @function
  595. * @return {bool}
  596. */
  597. me.isEntropyReady = function()
  598. {
  599. return sjcl.random.isReady();
  600. }
  601. /**
  602. * add a listener function, triggered when enough entropy is available
  603. *
  604. * @name CryptTool.addEntropySeedListener
  605. * @function
  606. * @param {function} func
  607. */
  608. me.addEntropySeedListener = function(func)
  609. {
  610. sjcl.random.addEventListener('seeded', func);
  611. }
  612. /**
  613. * returns a random symmetric key
  614. *
  615. * @name CryptTool.getSymmetricKey
  616. * @function
  617. * @return {string} func
  618. */
  619. me.getSymmetricKey = function()
  620. {
  621. return sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  622. }
  623. return me;
  624. })();
  625. /**
  626. * (Model) Data source (aka MVC)
  627. *
  628. * @name Model
  629. * @class
  630. */
  631. var Model = (function () {
  632. var me = {};
  633. var $cipherData,
  634. $templates;
  635. var id = null, symmetricKey = null;
  636. /**
  637. * returns the expiration set in the HTML
  638. *
  639. * @name Model.getExpirationDefault
  640. * @function
  641. * @return string
  642. * @TODO the template can be simplified as #pasteExpiration is no longer modified (only default value)
  643. */
  644. me.getExpirationDefault = function()
  645. {
  646. return $('#pasteExpiration').val();
  647. }
  648. /**
  649. * returns the format set in the HTML
  650. *
  651. * @name Model.getFormatDefault
  652. * @function
  653. * @return string
  654. * @TODO the template can be simplified as #pasteFormatter is no longer modified (only default value)
  655. */
  656. me.getFormatDefault = function()
  657. {
  658. return $('#pasteFormatter').val();
  659. }
  660. /**
  661. * check if cipher data was supplied
  662. *
  663. * @name Model.getCipherData
  664. * @function
  665. * @return boolean
  666. */
  667. me.hasCipherData = function()
  668. {
  669. return (me.getCipherData().length > 0);
  670. }
  671. /**
  672. * returns the cipher data
  673. *
  674. * @name Model.getCipherData
  675. * @function
  676. * @return string
  677. */
  678. me.getCipherData = function()
  679. {
  680. return $cipherData.text();
  681. }
  682. /**
  683. * get the pastes unique identifier from the URL,
  684. * eg. http://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  685. *
  686. * @name Model.getPasteId
  687. * @function
  688. * @return {string} unique identifier
  689. * @throws {string}
  690. */
  691. me.getPasteId = function()
  692. {
  693. if (id === null) {
  694. id = window.location.search.substring(1);
  695. if (id === '') {
  696. throw 'no paste id given';
  697. }
  698. }
  699. return id;
  700. }
  701. /**
  702. * return the deciphering key stored in anchor part of the URL
  703. *
  704. * @name Model.getPasteKey
  705. * @function
  706. * @return {string|null} key
  707. * @throws {string}
  708. */
  709. me.getPasteKey = function()
  710. {
  711. if (symmetricKey === null) {
  712. symmetricKey = window.location.hash.substring(1);
  713. if (symmetricKey === '') {
  714. throw 'no encryption key given';
  715. }
  716. // Some web 2.0 services and redirectors add data AFTER the anchor
  717. // (such as &utm_source=...). We will strip any additional data.
  718. var ampersandPos = symmetricKey.indexOf('&');
  719. if (ampersandPos > -1)
  720. {
  721. symmetricKey = symmetricKey.substring(0, ampersandPos);
  722. }
  723. }
  724. return symmetricKey;
  725. }
  726. /**
  727. * returns a jQuery copy of the HTML template
  728. *
  729. * @name Model.getTemplate
  730. * @function
  731. * @param {string} name - the name of the template
  732. * @return {jQuery}
  733. */
  734. me.getTemplate = function(name)
  735. {
  736. // find template
  737. var $element = $templates.find('#' + name + 'template').clone(true);
  738. // change ID to avoid collisions (one ID should really be unique)
  739. return $element.prop('id', name);
  740. }
  741. /**
  742. * resets state, used for unit testing
  743. *
  744. * @name Model.reset
  745. * @function
  746. */
  747. me.reset = function()
  748. {
  749. $cipherData = $templates = id = symmetricKey = null;
  750. }
  751. /**
  752. * init navigation manager
  753. *
  754. * preloads jQuery elements
  755. *
  756. * @name Model.init
  757. * @function
  758. */
  759. me.init = function()
  760. {
  761. $cipherData = $('#cipherdata');
  762. $templates = $('#templates');
  763. }
  764. return me;
  765. })();
  766. /**
  767. * Helper functions for user interface
  768. *
  769. * everything directly UI-related, which fits nowhere else
  770. *
  771. * @name UiHelper
  772. * @class
  773. */
  774. var UiHelper = (function () {
  775. var me = {};
  776. /**
  777. * handle history (pop) state changes
  778. *
  779. * currently this does only handle redirects to the home page.
  780. *
  781. * @name UiHelper.historyChange
  782. * @private
  783. * @function
  784. * @param {Event} event
  785. */
  786. function historyChange(event)
  787. {
  788. var currentLocation = Helper.baseUri();
  789. if (event.originalEvent.state === null && // no state object passed
  790. event.target.location.href === currentLocation && // target location is home page
  791. window.location.href === currentLocation // and we are not already on the home page
  792. ) {
  793. // redirect to home page
  794. window.location.href = currentLocation;
  795. }
  796. }
  797. /**
  798. * reload the page
  799. *
  800. * This takes the user to the PrivateBin homepage.
  801. *
  802. * @name UiHelper.reloadHome
  803. * @function
  804. */
  805. me.reloadHome = function()
  806. {
  807. window.location.href = Helper.baseUri();
  808. }
  809. /**
  810. * checks whether the element is currently visible in the viewport (so
  811. * the user can actually see it)
  812. *
  813. * @see {@link https://stackoverflow.com/a/40658647}
  814. * @name UiHelper.isVisible
  815. * @function
  816. * @param {jQuery} $element The link hash to move to.
  817. */
  818. me.isVisible = function($element)
  819. {
  820. var elementTop = $element.offset().top;
  821. var viewportTop = $(window).scrollTop();
  822. var viewportBottom = viewportTop + $(window).height();
  823. return (elementTop > viewportTop && elementTop < viewportBottom);
  824. }
  825. /**
  826. * scrolls to a specific element
  827. *
  828. * @see {@link https://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to-an-anchor#answer-12714767}
  829. * @name UiHelper.scrollTo
  830. * @function
  831. * @param {jQuery} $element The link hash to move to.
  832. * @param {(number|string)} animationDuration passed to jQuery .animate, when set to 0 the animation is skipped
  833. * @param {string} animationEffect passed to jQuery .animate
  834. * @param {function} finishedCallback function to call after animation finished
  835. */
  836. me.scrollTo = function($element, animationDuration, animationEffect, finishedCallback)
  837. {
  838. var $body = $('html, body'),
  839. margin = 50,
  840. callbackCalled = false;
  841. //calculate destination place
  842. var dest = 0;
  843. // if it would scroll out of the screen at the bottom only scroll it as
  844. // far as the screen can go
  845. if ($element.offset().top > $(document).height() - $(window).height()) {
  846. dest = $(document).height() - $(window).height();
  847. } else {
  848. dest = $element.offset().top - margin;
  849. }
  850. // skip animation if duration is set to 0
  851. if (animationDuration === 0) {
  852. window.scrollTo(0, dest);
  853. } else {
  854. // stop previous animation
  855. $body.stop();
  856. // scroll to destination
  857. $body.animate({
  858. scrollTop: dest
  859. }, animationDuration, animationEffect);
  860. }
  861. // as we have finished we can enable scrolling again
  862. $body.queue(function (next) {
  863. if (!callbackCalled) {
  864. // call user function if needed
  865. if (typeof finishedCallback !== 'undefined') {
  866. finishedCallback();
  867. }
  868. // prevent calling this function twice
  869. callbackCalled = true;
  870. }
  871. next();
  872. });
  873. }
  874. /**
  875. * trigger a history (pop) state change
  876. *
  877. * used to test the UiHelper.historyChange private function
  878. *
  879. * @name UiHelper.mockHistoryChange
  880. * @function
  881. * @param {string} state (optional) state to mock
  882. */
  883. me.mockHistoryChange = function(state)
  884. {
  885. if (typeof state === 'undefined') {
  886. state = null;
  887. }
  888. historyChange($.Event('popstate', {originalEvent: new PopStateEvent('popstate', {state: state}), target: window}));
  889. }
  890. /**
  891. * initialize
  892. *
  893. * @name UiHelper.init
  894. * @function
  895. */
  896. me.init = function()
  897. {
  898. // update link to home page
  899. $('.reloadlink').prop('href', Helper.baseUri());
  900. $(window).on('popstate', historyChange);
  901. }
  902. return me;
  903. })();
  904. /**
  905. * Alert/error manager
  906. *
  907. * @name Alert
  908. * @class
  909. */
  910. var Alert = (function () {
  911. var me = {};
  912. var $errorMessage,
  913. $loadingIndicator,
  914. $statusMessage,
  915. $remainingTime;
  916. var currentIcon;
  917. var alertType = [
  918. 'loading', // not in bootstrap, but using a good value here
  919. 'info', // status icon
  920. 'warning', // not used yet
  921. 'danger' // error icon
  922. ];
  923. var customHandler;
  924. /**
  925. * forwards a request to the i18n module and shows the element
  926. *
  927. * @name Alert.handleNotification
  928. * @private
  929. * @function
  930. * @param {int} id - id of notification
  931. * @param {jQuery} $element - jQuery object
  932. * @param {string|array} args
  933. * @param {string|null} icon - optional, icon
  934. */
  935. function handleNotification(id, $element, args, icon)
  936. {
  937. // basic parsing/conversion of parameters
  938. if (typeof icon === 'undefined') {
  939. icon = null;
  940. }
  941. if (typeof args === 'undefined') {
  942. args = null;
  943. } else if (typeof args === 'string') {
  944. // convert string to array if needed
  945. args = [args];
  946. }
  947. // pass to custom handler if defined
  948. if (typeof customHandler === 'function') {
  949. var handlerResult = customHandler(alertType[id], $element, args, icon);
  950. if (handlerResult === true) {
  951. // if it returs true, skip own handler
  952. return;
  953. }
  954. if (handlerResult instanceof jQuery) {
  955. // continue processing with new element
  956. $element = handlerResult;
  957. icon = null; // icons not supported in this case
  958. }
  959. }
  960. // handle icon
  961. if (icon !== null && // icon was passed
  962. icon !== currentIcon[id] // and it differs from current icon
  963. ) {
  964. var $glyphIcon = $element.find(':first');
  965. // remove (previous) icon
  966. $glyphIcon.removeClass(currentIcon[id]);
  967. // any other thing as a string (e.g. 'null') (only) removes the icon
  968. if (typeof icon === 'string') {
  969. // set new icon
  970. currentIcon[id] = 'glyphicon-' + icon;
  971. $glyphIcon.addClass(currentIcon[id]);
  972. }
  973. }
  974. // show text
  975. if (args !== null) {
  976. // add jQuery object to it as first parameter
  977. args.unshift($element);
  978. // pass it to I18n
  979. I18n._.apply(this, args);
  980. }
  981. // show notification
  982. $element.removeClass('hidden');
  983. }
  984. /**
  985. * display a status message
  986. *
  987. * This automatically passes the text to I18n for translation.
  988. *
  989. * @name Alert.showStatus
  990. * @function
  991. * @param {string|array} message string, use an array for %s/%d options
  992. * @param {string|null} icon optional, the icon to show,
  993. * default: leave previous icon
  994. * @param {bool} dismissable optional, whether the notification
  995. * can be dismissed (closed), default: false
  996. * @param {bool|int} autoclose optional, after how many seconds the
  997. * notification should be hidden automatically;
  998. * default: disabled (0); use true for default value
  999. */
  1000. me.showStatus = function(message, icon, dismissable, autoclose)
  1001. {
  1002. console.info('status shown: ', message);
  1003. // @TODO: implement dismissable
  1004. // @TODO: implement autoclose
  1005. handleNotification(1, $statusMessage, message, icon);
  1006. }
  1007. /**
  1008. * display an error message
  1009. *
  1010. * This automatically passes the text to I18n for translation.
  1011. *
  1012. * @name Alert.showError
  1013. * @function
  1014. * @param {string|array} message string, use an array for %s/%d options
  1015. * @param {string|null} icon optional, the icon to show, default:
  1016. * leave previous icon
  1017. * @param {bool} dismissable optional, whether the notification
  1018. * can be dismissed (closed), default: false
  1019. * @param {bool|int} autoclose optional, after how many seconds the
  1020. * notification should be hidden automatically;
  1021. * default: disabled (0); use true for default value
  1022. */
  1023. me.showError = function(message, icon, dismissable, autoclose)
  1024. {
  1025. console.error('error message shown: ', message);
  1026. // @TODO: implement dismissable (bootstrap add-on has it)
  1027. // @TODO: implement autoclose
  1028. handleNotification(3, $errorMessage, message, icon);
  1029. }
  1030. /**
  1031. * display remaining message
  1032. *
  1033. * This automatically passes the text to I18n for translation.
  1034. *
  1035. * @name Alert.showRemaining
  1036. * @function
  1037. * @param {string|array} message string, use an array for %s/%d options
  1038. */
  1039. me.showRemaining = function(message)
  1040. {
  1041. console.info('remaining message shown: ', message);
  1042. handleNotification(1, $remainingTime, message);
  1043. }
  1044. /**
  1045. * shows a loading message, optionally with a percentage
  1046. *
  1047. * This automatically passes all texts to the i10s module.
  1048. *
  1049. * @name Alert.showLoading
  1050. * @function
  1051. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1052. * @param {int} percentage optional, default: null
  1053. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1054. */
  1055. me.showLoading = function(message, percentage, icon)
  1056. {
  1057. if (typeof message !== 'undefined' && message !== null) {
  1058. console.info('status changed: ', message);
  1059. }
  1060. // default message text
  1061. if (typeof message === 'undefined') {
  1062. message = 'Loading…';
  1063. }
  1064. // currently percentage parameter is ignored
  1065. // // @TODO handle it here…
  1066. handleNotification(0, $loadingIndicator, message, icon);
  1067. // show loading status (cursor)
  1068. $('body').addClass('loading');
  1069. }
  1070. /**
  1071. * hides the loading message
  1072. *
  1073. * @name Alert.hideLoading
  1074. * @function
  1075. */
  1076. me.hideLoading = function()
  1077. {
  1078. $loadingIndicator.addClass('hidden');
  1079. // hide loading cursor
  1080. $('body').removeClass('loading');
  1081. }
  1082. /**
  1083. * hides any status/error messages
  1084. *
  1085. * This does not include the loading message.
  1086. *
  1087. * @name Alert.hideMessages
  1088. * @function
  1089. */
  1090. me.hideMessages = function()
  1091. {
  1092. // also possible: $('.statusmessage').addClass('hidden');
  1093. $statusMessage.addClass('hidden');
  1094. $errorMessage.addClass('hidden');
  1095. }
  1096. /**
  1097. * set a custom handler, which gets all notifications.
  1098. *
  1099. * This handler gets the following arguments:
  1100. * alertType (see array), $element, args, icon
  1101. * If it returns true, the own processing will be stopped so the message
  1102. * will not be displayed. Otherwise it will continue.
  1103. * As an aditional feature it can return q jQuery element, which will
  1104. * then be used to add the message there. Icons are not supported in
  1105. * that case and will be ignored.
  1106. * Pass 'null' to reset/delete the custom handler.
  1107. * Note that there is no notification when a message is supposed to get
  1108. * hidden.
  1109. *
  1110. * @name Alert.setCustomHandler
  1111. * @function
  1112. * @param {function|null} newHandler
  1113. */
  1114. me.setCustomHandler = function(newHandler)
  1115. {
  1116. customHandler = newHandler;
  1117. }
  1118. /**
  1119. * init status manager
  1120. *
  1121. * preloads jQuery elements
  1122. *
  1123. * @name Alert.init
  1124. * @function
  1125. */
  1126. me.init = function()
  1127. {
  1128. // hide "no javascript" error message
  1129. $('#noscript').hide();
  1130. // not a reset, but first set of the elements
  1131. $errorMessage = $('#errormessage');
  1132. $loadingIndicator = $('#loadingindicator');
  1133. $statusMessage = $('#status');
  1134. $remainingTime = $('#remainingtime');
  1135. currentIcon = [
  1136. 'glyphicon-time', // loading icon
  1137. 'glyphicon-info-sign', // status icon
  1138. '', // reserved for warning, not used yet
  1139. 'glyphicon-alert' // error icon
  1140. ];
  1141. }
  1142. return me;
  1143. })();
  1144. /**
  1145. * handles paste status/result
  1146. *
  1147. * @name PasteStatus
  1148. * @class
  1149. */
  1150. var PasteStatus = (function () {
  1151. var me = {};
  1152. var $pasteSuccess,
  1153. $pasteUrl,
  1154. $remainingTime,
  1155. $shortenButton;
  1156. /**
  1157. * forward to URL shortener
  1158. *
  1159. * @name PasteStatus.sendToShortener
  1160. * @private
  1161. * @function
  1162. * @param {Event} event
  1163. */
  1164. function sendToShortener(event)
  1165. {
  1166. window.location.href = $shortenButton.data('shortener')
  1167. + encodeURIComponent($pasteUrl.attr('href'));
  1168. }
  1169. /**
  1170. * Forces opening the paste if the link does not do this automatically.
  1171. *
  1172. * This is necessary as browsers will not reload the page when it is
  1173. * already loaded (which is fake as it is set via history.pushState()).
  1174. *
  1175. * @name PasteStatus.pasteLinkClick
  1176. * @function
  1177. * @param {Event} event
  1178. */
  1179. function pasteLinkClick(event)
  1180. {
  1181. // check if location is (already) shown in URL bar
  1182. if (window.location.href === $pasteUrl.attr('href')) {
  1183. // if so we need to load link by reloading the current site
  1184. window.location.reload(true);
  1185. }
  1186. }
  1187. /**
  1188. * creates a notification after a successfull paste upload
  1189. *
  1190. * @name PasteStatus.createPasteNotification
  1191. * @function
  1192. * @param {string} url
  1193. * @param {string} deleteUrl
  1194. */
  1195. me.createPasteNotification = function(url, deleteUrl)
  1196. {
  1197. $('#pastelink').html(
  1198. I18n._(
  1199. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1200. url, url
  1201. )
  1202. );
  1203. // save newly created element
  1204. $pasteUrl = $('#pasteurl');
  1205. // and add click event
  1206. $pasteUrl.click(pasteLinkClick);
  1207. // shorten button
  1208. $('#deletelink').html('<a href="' + deleteUrl + '">' + I18n._('Delete data') + '</a>');
  1209. // show result
  1210. $pasteSuccess.removeClass('hidden');
  1211. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1212. Helper.selectText($pasteUrl[0]);
  1213. }
  1214. /**
  1215. * shows the remaining time
  1216. *
  1217. * @name PasteStatus.showRemainingTime
  1218. * @function
  1219. * @param {object} pasteMetaData
  1220. */
  1221. me.showRemainingTime = function(pasteMetaData)
  1222. {
  1223. if (pasteMetaData.burnafterreading) {
  1224. // display paste "for your eyes only" if it is deleted
  1225. // actually remove paste, before we claim it is deleted
  1226. Controller.removePaste(Model.getPasteId(), 'burnafterreading');
  1227. Alert.showRemaining("FOR YOUR EYES ONLY. Don't close this window, this message can't be displayed again.");
  1228. $remainingTime.addClass('foryoureyesonly');
  1229. // discourage cloning (it cannot really be prevented)
  1230. TopNav.hideCloneButton();
  1231. } else if (pasteMetaData.expire_date) {
  1232. // display paste expiration
  1233. var expiration = Helper.secondsToHuman(pasteMetaData.remaining_time),
  1234. expirationLabel = [
  1235. 'This document will expire in %d ' + expiration[1] + '.',
  1236. 'This document will expire in %d ' + expiration[1] + 's.'
  1237. ];
  1238. Alert.showRemaining([expirationLabel, expiration[0]]);
  1239. $remainingTime.removeClass('foryoureyesonly');
  1240. } else {
  1241. // never expires
  1242. return;
  1243. }
  1244. // in the end, display notification
  1245. $remainingTime.removeClass('hidden');
  1246. }
  1247. /**
  1248. * hides the remaining time and successful upload notification
  1249. *
  1250. * @name PasteStatus.hideRemainingTime
  1251. * @function
  1252. */
  1253. me.hideMessages = function()
  1254. {
  1255. $remainingTime.addClass('hidden');
  1256. $pasteSuccess.addClass('hidden');
  1257. }
  1258. /**
  1259. * init status manager
  1260. *
  1261. * preloads jQuery elements
  1262. *
  1263. * @name PasteStatus.init
  1264. * @function
  1265. */
  1266. me.init = function()
  1267. {
  1268. $pasteSuccess = $('#pastesuccess');
  1269. // $pasteUrl is saved in me.createPasteNotification() after creation
  1270. $remainingTime = $('#remainingtime');
  1271. $shortenButton = $('#shortenbutton');
  1272. // bind elements
  1273. $shortenButton.click(sendToShortener);
  1274. }
  1275. return me;
  1276. })();
  1277. /**
  1278. * password prompt
  1279. *
  1280. * @name Prompt
  1281. * @class
  1282. */
  1283. var Prompt = (function () {
  1284. var me = {};
  1285. var $passwordDecrypt,
  1286. $passwordForm,
  1287. $passwordModal;
  1288. var password = '';
  1289. /**
  1290. * submit a password in the modal dialog
  1291. *
  1292. * @name Prompt.submitPasswordModal
  1293. * @private
  1294. * @function
  1295. * @param {Event} event
  1296. */
  1297. function submitPasswordModal(event)
  1298. {
  1299. event.preventDefault();
  1300. // get input
  1301. password = $passwordDecrypt.val();
  1302. // hide modal
  1303. $passwordModal.modal('hide');
  1304. PasteDecrypter.run();
  1305. }
  1306. /**
  1307. * ask the user for the password and set it
  1308. *
  1309. * @name Prompt.requestPassword
  1310. * @function
  1311. */
  1312. me.requestPassword = function()
  1313. {
  1314. // show new bootstrap method (if available)
  1315. if ($passwordModal.length !== 0) {
  1316. $passwordModal.modal({
  1317. backdrop: 'static',
  1318. keyboard: false
  1319. });
  1320. return;
  1321. }
  1322. // fallback to old method for page template
  1323. var newPassword = prompt(I18n._('Please enter the password for this paste:'), '');
  1324. if (newPassword === null) {
  1325. throw 'password prompt canceled';
  1326. }
  1327. if (password.length === 0) {
  1328. // recurse…
  1329. return me.requestPassword();
  1330. }
  1331. password = newPassword;
  1332. }
  1333. /**
  1334. * get the cached password
  1335. *
  1336. * If you do not get a password with this function
  1337. * (returns an empty string), use requestPassword.
  1338. *
  1339. * @name Prompt.getPassword
  1340. * @function
  1341. * @return {string}
  1342. */
  1343. me.getPassword = function()
  1344. {
  1345. return password;
  1346. }
  1347. /**
  1348. * init status manager
  1349. *
  1350. * preloads jQuery elements
  1351. *
  1352. * @name Prompt.init
  1353. * @function
  1354. */
  1355. me.init = function()
  1356. {
  1357. $passwordDecrypt = $('#passworddecrypt');
  1358. $passwordForm = $('#passwordform');
  1359. $passwordModal = $('#passwordmodal');
  1360. // bind events
  1361. // focus password input when it is shown
  1362. $passwordModal.on('shown.bs.Model', function () {
  1363. $passwordDecrypt.focus();
  1364. });
  1365. // handle Model password submission
  1366. $passwordForm.submit(submitPasswordModal);
  1367. }
  1368. return me;
  1369. })();
  1370. /**
  1371. * Manage paste/message input, and preview tab
  1372. *
  1373. * Note that the actual preview is handled by PasteViewer.
  1374. *
  1375. * @name Editor
  1376. * @class
  1377. */
  1378. var Editor = (function () {
  1379. var me = {};
  1380. var $editorTabs,
  1381. $messageEdit,
  1382. $messagePreview,
  1383. $message;
  1384. var isPreview = false;
  1385. /**
  1386. * support input of tab character
  1387. *
  1388. * @name Editor.supportTabs
  1389. * @function
  1390. * @param {Event} event
  1391. * @this $message (but not used, so it is jQuery-free, possibly faster)
  1392. */
  1393. function supportTabs(event)
  1394. {
  1395. var keyCode = event.keyCode || event.which;
  1396. // tab was pressed
  1397. if (keyCode === 9) {
  1398. // get caret position & selection
  1399. var val = this.value,
  1400. start = this.selectionStart,
  1401. end = this.selectionEnd;
  1402. // set textarea value to: text before caret + tab + text after caret
  1403. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1404. // put caret at right position again
  1405. this.selectionStart = this.selectionEnd = start + 1;
  1406. // prevent the textarea to lose focus
  1407. event.preventDefault();
  1408. }
  1409. }
  1410. /**
  1411. * view the Editor tab
  1412. *
  1413. * @name Editor.viewEditor
  1414. * @function
  1415. * @param {Event} event - optional
  1416. */
  1417. function viewEditor(event)
  1418. {
  1419. // toggle buttons
  1420. $messageEdit.addClass('active');
  1421. $messagePreview.removeClass('active');
  1422. PasteViewer.hide();
  1423. // reshow input
  1424. $message.removeClass('hidden');
  1425. me.focusInput();
  1426. // finish
  1427. isPreview = false;
  1428. // prevent jumping of page to top
  1429. if (typeof event !== 'undefined') {
  1430. event.preventDefault();
  1431. }
  1432. }
  1433. /**
  1434. * view the preview tab
  1435. *
  1436. * @name Editor.viewPreview
  1437. * @function
  1438. * @param {Event} event
  1439. */
  1440. function viewPreview(event)
  1441. {
  1442. // toggle buttons
  1443. $messageEdit.removeClass('active');
  1444. $messagePreview.addClass('active');
  1445. // hide input as now preview is shown
  1446. $message.addClass('hidden');
  1447. // show preview
  1448. PasteViewer.setText($message.val());
  1449. PasteViewer.run();
  1450. // finish
  1451. isPreview = true;
  1452. // prevent jumping of page to top
  1453. if (typeof event !== 'undefined') {
  1454. event.preventDefault();
  1455. }
  1456. }
  1457. /**
  1458. * get the state of the preview
  1459. *
  1460. * @name Editor.isPreview
  1461. * @function
  1462. */
  1463. me.isPreview = function()
  1464. {
  1465. return isPreview;
  1466. }
  1467. /**
  1468. * reset the Editor view
  1469. *
  1470. * @name Editor.resetInput
  1471. * @function
  1472. */
  1473. me.resetInput = function()
  1474. {
  1475. // go back to input
  1476. if (isPreview) {
  1477. viewEditor();
  1478. }
  1479. // clear content
  1480. $message.val('');
  1481. }
  1482. /**
  1483. * shows the Editor
  1484. *
  1485. * @name Editor.show
  1486. * @function
  1487. */
  1488. me.show = function()
  1489. {
  1490. $message.removeClass('hidden');
  1491. $editorTabs.removeClass('hidden');
  1492. }
  1493. /**
  1494. * hides the Editor
  1495. *
  1496. * @name Editor.reset
  1497. * @function
  1498. */
  1499. me.hide = function()
  1500. {
  1501. $message.addClass('hidden');
  1502. $editorTabs.addClass('hidden');
  1503. }
  1504. /**
  1505. * focuses the message input
  1506. *
  1507. * @name Editor.focusInput
  1508. * @function
  1509. */
  1510. me.focusInput = function()
  1511. {
  1512. $message.focus();
  1513. }
  1514. /**
  1515. * sets a new text
  1516. *
  1517. * @name Editor.setText
  1518. * @function
  1519. * @param {string} newText
  1520. */
  1521. me.setText = function(newText)
  1522. {
  1523. $message.val(newText);
  1524. }
  1525. /**
  1526. * returns the current text
  1527. *
  1528. * @name Editor.getText
  1529. * @function
  1530. * @return {string}
  1531. */
  1532. me.getText = function()
  1533. {
  1534. return $message.val()
  1535. }
  1536. /**
  1537. * init status manager
  1538. *
  1539. * preloads jQuery elements
  1540. *
  1541. * @name Editor.init
  1542. * @function
  1543. */
  1544. me.init = function()
  1545. {
  1546. $editorTabs = $('#editorTabs');
  1547. $message = $('#message');
  1548. // bind events
  1549. $message.keydown(supportTabs);
  1550. // bind click events to tab switchers (a), but save parent of them
  1551. // (li)
  1552. $messageEdit = $('#messageedit').click(viewEditor).parent();
  1553. $messagePreview = $('#messagepreview').click(viewPreview).parent();
  1554. }
  1555. return me;
  1556. })();
  1557. /**
  1558. * (view) Parse and show paste.
  1559. *
  1560. * @name PasteViewer
  1561. * @class
  1562. */
  1563. var PasteViewer = (function () {
  1564. var me = {};
  1565. var $placeholder,
  1566. $prettyMessage,
  1567. $prettyPrint,
  1568. $plainText;
  1569. var text,
  1570. format = 'plaintext',
  1571. isDisplayed = false,
  1572. isChanged = true; // by default true as nothing was parsed yet
  1573. /**
  1574. * apply the set format on paste and displays it
  1575. *
  1576. * @name PasteViewer.parsePaste
  1577. * @private
  1578. * @function
  1579. */
  1580. function parsePaste()
  1581. {
  1582. // skip parsing if no text is given
  1583. if (text === '') {
  1584. return;
  1585. }
  1586. // set text
  1587. var sanitizedText = DOMPurify.sanitize(text, {SAFE_FOR_JQUERY: true})
  1588. Helper.setElementText($plainText, sanitizedText);
  1589. Helper.setElementText($prettyPrint, sanitizedText);
  1590. switch (format) {
  1591. case 'markdown':
  1592. var converter = new showdown.Converter({
  1593. strikethrough: true,
  1594. tables: true,
  1595. tablesHeaderId: true
  1596. });
  1597. // let showdown convert the HTML and sanitize HTML *afterwards*!
  1598. $plainText.html(
  1599. DOMPurify.sanitize(converter.makeHtml(text), {SAFE_FOR_JQUERY: true})
  1600. );
  1601. // add table classes from bootstrap css
  1602. $plainText.find('table').addClass('table-condensed table-bordered');
  1603. break;
  1604. case 'syntaxhighlighting':
  1605. // @TODO is this really needed or is "one" enough?
  1606. if (typeof prettyPrint === 'function')
  1607. {
  1608. prettyPrint();
  1609. }
  1610. $prettyPrint.html(
  1611. prettyPrintOne(
  1612. Helper.htmlEntities(sanitizedText), null, true
  1613. )
  1614. );
  1615. // fall through, as the rest is the same
  1616. default: // = 'plaintext'
  1617. // convert URLs to clickable links
  1618. Helper.urls2links($plainText);
  1619. Helper.urls2links($prettyPrint);
  1620. $prettyPrint.css('white-space', 'pre-wrap');
  1621. $prettyPrint.css('word-break', 'normal');
  1622. $prettyPrint.removeClass('prettyprint');
  1623. }
  1624. }
  1625. /**
  1626. * displays the paste
  1627. *
  1628. * @name PasteViewer.showPaste
  1629. * @private
  1630. * @function
  1631. */
  1632. function showPaste()
  1633. {
  1634. // instead of "nothing" better display a placeholder
  1635. if (text === '') {
  1636. $placeholder.removeClass('hidden')
  1637. return;
  1638. }
  1639. // otherwise hide the placeholder
  1640. $placeholder.addClass('hidden')
  1641. switch (format) {
  1642. case 'markdown':
  1643. $plainText.removeClass('hidden');
  1644. $prettyMessage.addClass('hidden');
  1645. break;
  1646. default:
  1647. $plainText.addClass('hidden');
  1648. $prettyMessage.removeClass('hidden');
  1649. break;
  1650. }
  1651. }
  1652. /**
  1653. * sets the format in which the text is shown
  1654. *
  1655. * @name PasteViewer.setFormat
  1656. * @function
  1657. * @param {string} newFormat the new format
  1658. */
  1659. me.setFormat = function(newFormat)
  1660. {
  1661. // skip if there is no update
  1662. if (format === newFormat) {
  1663. return;
  1664. }
  1665. // needs to update display too, if we switch from or to Markdown
  1666. if (format === 'markdown' || newFormat === 'markdown') {
  1667. isDisplayed = false;
  1668. }
  1669. format = newFormat;
  1670. isChanged = true;
  1671. }
  1672. /**
  1673. * returns the current format
  1674. *
  1675. * @name PasteViewer.getFormat
  1676. * @function
  1677. * @return {string}
  1678. */
  1679. me.getFormat = function()
  1680. {
  1681. return format;
  1682. }
  1683. /**
  1684. * returns whether the current view is pretty printed
  1685. *
  1686. * @name PasteViewer.isPrettyPrinted
  1687. * @function
  1688. * @return {bool}
  1689. */
  1690. me.isPrettyPrinted = function()
  1691. {
  1692. return $prettyPrint.hasClass('prettyprinted');
  1693. }
  1694. /**
  1695. * sets the text to show
  1696. *
  1697. * @name PasteViewer.setText
  1698. * @function
  1699. * @param {string} newText the text to show
  1700. */
  1701. me.setText = function(newText)
  1702. {
  1703. if (text !== newText) {
  1704. text = newText;
  1705. isChanged = true;
  1706. }
  1707. }
  1708. /**
  1709. * gets the current cached text
  1710. *
  1711. * @name PasteViewer.getText
  1712. * @function
  1713. * @return {string}
  1714. */
  1715. me.getText = function()
  1716. {
  1717. return text;
  1718. }
  1719. /**
  1720. * show/update the parsed text (preview)
  1721. *
  1722. * @name PasteViewer.run
  1723. * @function
  1724. */
  1725. me.run = function()
  1726. {
  1727. if (isChanged) {
  1728. parsePaste();
  1729. isChanged = false;
  1730. }
  1731. if (!isDisplayed) {
  1732. showPaste();
  1733. isDisplayed = true;
  1734. }
  1735. }
  1736. /**
  1737. * hide parsed text (preview)
  1738. *
  1739. * @name PasteViewer.hide
  1740. * @function
  1741. */
  1742. me.hide = function()
  1743. {
  1744. if (!isDisplayed) {
  1745. console.warn('PasteViewer was called to hide the parsed view, but it is already hidden.');
  1746. }
  1747. $plainText.addClass('hidden');
  1748. $prettyMessage.addClass('hidden');
  1749. $placeholder.addClass('hidden');
  1750. isDisplayed = false;
  1751. }
  1752. /**
  1753. * init status manager
  1754. *
  1755. * preloads jQuery elements
  1756. *
  1757. * @name PasteViewer.init
  1758. * @function
  1759. */
  1760. me.init = function()
  1761. {
  1762. $placeholder = $('#placeholder');
  1763. $plainText = $('#plaintext');
  1764. $prettyMessage = $('#prettymessage');
  1765. $prettyPrint = $('#prettyprint');
  1766. // check requirements
  1767. if (typeof prettyPrintOne !== 'function') {
  1768. Alert.showError([
  1769. 'The library %s is not available. This may cause display errors.',
  1770. 'pretty print'
  1771. ]);
  1772. }
  1773. if (typeof showdown !== 'object') {
  1774. Alert.showError([
  1775. 'The library %s is not available. This may cause display errors.',
  1776. 'showdown'
  1777. ]);
  1778. }
  1779. // get default option from template/HTML or fall back to set value
  1780. format = Model.getFormatDefault() || format;
  1781. text = '';
  1782. isDisplayed = false;
  1783. isChanged = true;
  1784. }
  1785. return me;
  1786. })();
  1787. /**
  1788. * (view) Show attachment and preview if possible
  1789. *
  1790. * @name AttachmentViewer
  1791. * @param {object} window
  1792. * @param {object} document
  1793. * @class
  1794. */
  1795. var AttachmentViewer = (function (window, document) {
  1796. var me = {};
  1797. var $attachmentLink,
  1798. $attachmentPreview,
  1799. $attachment;
  1800. var attachmentHasPreview = false;
  1801. /**
  1802. * sets the attachment but does not yet show it
  1803. *
  1804. * @name AttachmentViewer.setAttachment
  1805. * @function
  1806. * @param {string} attachmentData - base64-encoded data of file
  1807. * @param {string} fileName - optional, file name
  1808. */
  1809. me.setAttachment = function(attachmentData, fileName)
  1810. {
  1811. var imagePrefix = 'data:image/';
  1812. $attachmentLink.attr('href', attachmentData);
  1813. if (typeof fileName !== 'undefined') {
  1814. $attachmentLink.attr('download', fileName);
  1815. }
  1816. // if the attachment is an image, display it
  1817. if (attachmentData.substring(0, imagePrefix.length) === imagePrefix) {
  1818. $attachmentPreview.html(
  1819. $(document.createElement('img'))
  1820. .attr('src', attachmentData)
  1821. .attr('class', 'img-thumbnail')
  1822. );
  1823. attachmentHasPreview = true;
  1824. }
  1825. }
  1826. /**
  1827. * displays the attachment
  1828. *
  1829. * @name AttachmentViewer.showAttachment
  1830. * @function
  1831. */
  1832. me.showAttachment = function()
  1833. {
  1834. $attachment.removeClass('hidden');
  1835. if (attachmentHasPreview) {
  1836. $attachmentPreview.removeClass('hidden');
  1837. }
  1838. }
  1839. /**
  1840. * removes the attachment
  1841. *
  1842. * This automatically hides the attachment containers to, to
  1843. * prevent an inconsistent display.
  1844. *
  1845. * @name AttachmentViewer.removeAttachment
  1846. * @function
  1847. */
  1848. me.removeAttachment = function()
  1849. {
  1850. me.hideAttachment();
  1851. me.hideAttachmentPreview();
  1852. $attachmentLink.prop('href', '');
  1853. $attachmentLink.prop('download', '');
  1854. $attachmentPreview.html('');
  1855. }
  1856. /**
  1857. * hides the attachment
  1858. *
  1859. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  1860. * for that) nor will it hide the attachment link if it was moved somewhere
  1861. * else (see AttachmentViewer.moveAttachmentTo).
  1862. *
  1863. * @name AttachmentViewer.hideAttachment
  1864. * @function
  1865. */
  1866. me.hideAttachment = function()
  1867. {
  1868. $attachment.addClass('hidden');
  1869. }
  1870. /**
  1871. * hides the attachment preview
  1872. *
  1873. * @name AttachmentViewer.hideAttachmentPreview
  1874. * @function
  1875. */
  1876. me.hideAttachmentPreview = function()
  1877. {
  1878. $attachmentPreview.addClass('hidden');
  1879. }
  1880. /**
  1881. * checks if there is an attachment
  1882. *
  1883. * @name AttachmentViewer.hasAttachment
  1884. * @function
  1885. */
  1886. me.hasAttachment = function()
  1887. {
  1888. var link = $attachmentLink.prop('href');
  1889. return (typeof link !== 'undefined' && link !== '')
  1890. }
  1891. /**
  1892. * return the attachment
  1893. *
  1894. * @name AttachmentViewer.getAttachment
  1895. * @function
  1896. * @returns {array}
  1897. */
  1898. me.getAttachment = function()
  1899. {
  1900. return [
  1901. $attachmentLink.prop('href'),
  1902. $attachmentLink.prop('download')
  1903. ];
  1904. }
  1905. /**
  1906. * moves the attachment link to another element
  1907. *
  1908. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  1909. *
  1910. * @name AttachmentViewer.moveAttachmentTo
  1911. * @function
  1912. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  1913. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  1914. */
  1915. me.moveAttachmentTo = function($element, label)
  1916. {
  1917. // move elemement to new place
  1918. $attachmentLink.appendTo($element);
  1919. // update text
  1920. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  1921. }
  1922. /**
  1923. * initiate
  1924. *
  1925. * preloads jQuery elements
  1926. *
  1927. * @name AttachmentViewer.init
  1928. * @function
  1929. */
  1930. me.init = function()
  1931. {
  1932. $attachment = $('#attachment');
  1933. $attachmentLink = $('#attachment a');
  1934. $attachmentPreview = $('#attachmentPreview');
  1935. }
  1936. return me;
  1937. })(window, document);
  1938. /**
  1939. * (view) Shows discussion thread and handles replies
  1940. *
  1941. * @name DiscussionViewer
  1942. * @param {object} window
  1943. * @param {object} document
  1944. * @class
  1945. */
  1946. var DiscussionViewer = (function (window, document) {
  1947. var me = {};
  1948. var $commentTail,
  1949. $discussion,
  1950. $reply,
  1951. $replyMessage,
  1952. $replyNickname,
  1953. $replyStatus,
  1954. $commentContainer;
  1955. var replyCommentId;
  1956. /**
  1957. * initializes the templates
  1958. *
  1959. * @name DiscussionViewer.initTemplates
  1960. * @private
  1961. * @function
  1962. */
  1963. function initTemplates()
  1964. {
  1965. $reply = Model.getTemplate('reply');
  1966. $replyMessage = $reply.find('#replymessage');
  1967. $replyNickname = $reply.find('#nickname');
  1968. $replyStatus = $reply.find('#replystatus');
  1969. // cache jQuery elements
  1970. $commentTail = Model.getTemplate('commenttail');
  1971. }
  1972. /**
  1973. * open the comment entry when clicking the "Reply" button of a comment
  1974. *
  1975. * @name DiscussionViewer.openReply
  1976. * @private
  1977. * @function
  1978. * @param {Event} event
  1979. */
  1980. function openReply(event)
  1981. {
  1982. var $source = $(event.target);
  1983. // clear input
  1984. $replyMessage.val('');
  1985. $replyNickname.val('');
  1986. // get comment id from source element
  1987. replyCommentId = $source.parent().prop('id').split('_')[1];
  1988. // move to correct position
  1989. $source.after($reply);
  1990. // show
  1991. $reply.removeClass('hidden');
  1992. $replyMessage.focus();
  1993. event.preventDefault();
  1994. }
  1995. /**
  1996. * custom handler for displaying notifications in own status message area
  1997. *
  1998. * @name DiscussionViewer.handleNotification
  1999. * @function
  2000. * @param {string} alertType
  2001. * @param {jQuery} $element
  2002. * @param {string|array} args
  2003. * @param {string|null} icon
  2004. * @return {bool|jQuery}
  2005. */
  2006. me.handleNotification = function(alertType, $element, args, icon)
  2007. {
  2008. // ignore loading messages
  2009. if (alertType === 'loading') {
  2010. return false;
  2011. }
  2012. if (alertType === 'danger') {
  2013. $replyStatus.removeClass('alert-info');
  2014. $replyStatus.addClass('alert-danger');
  2015. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2016. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2017. } else {
  2018. $replyStatus.removeClass('alert-danger');
  2019. $replyStatus.addClass('alert-info');
  2020. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2021. $replyStatus.find(':first').addClass('glyphicon-alert');
  2022. }
  2023. return $replyStatus;
  2024. }
  2025. /**
  2026. * adds another comment
  2027. *
  2028. * @name DiscussionViewer.addComment
  2029. * @function
  2030. * @param {object} comment
  2031. * @param {string} commentText
  2032. * @param {jQuery} $place - optional, tries to find the best position otherwise
  2033. */
  2034. me.addComment = function(comment, commentText, nickname, $place)
  2035. {
  2036. if (typeof $place === 'undefined') {
  2037. // starting point (default value/fallback)
  2038. $place = $commentContainer;
  2039. // if parent comment exists
  2040. var $parentComment = $('#comment_' + comment.parentid);
  2041. if ($parentComment.length) {
  2042. // use parent as position for noew comment, so it shifted
  2043. // to the right
  2044. $place = $parentComment;
  2045. }
  2046. }
  2047. if (commentText === '') {
  2048. commentText = 'comment decryption failed';
  2049. }
  2050. // create new comment based on template
  2051. var $commentEntry = Model.getTemplate('comment');
  2052. $commentEntry.prop('id', 'comment_' + comment.id);
  2053. var $commentEntryData = $commentEntry.find('div.commentdata');
  2054. // set & parse text
  2055. Helper.setElementText($commentEntryData, commentText);
  2056. Helper.urls2links($commentEntryData);
  2057. // set nickname
  2058. if (nickname.length > 0) {
  2059. $commentEntry.find('span.nickname').text(nickname);
  2060. } else {
  2061. $commentEntry.find('span.nickname').html('<i></i>');
  2062. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2063. }
  2064. // set date
  2065. $commentEntry.find('span.commentdate')
  2066. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2067. .attr('title', 'CommentID: ' + comment.id);
  2068. // if an avatar is available, display it
  2069. if (comment.meta.vizhash) {
  2070. $commentEntry.find('span.nickname')
  2071. .before(
  2072. '<img src="' + comment.meta.vizhash + '" class="vizhash" /> '
  2073. );
  2074. $(document).on('languageLoaded', function () {
  2075. $commentEntry.find('img.vizhash')
  2076. .prop('title', I18n._('Avatar generated from IP address'));
  2077. });
  2078. }
  2079. // finally append comment
  2080. $place.append($commentEntry);
  2081. }
  2082. /**
  2083. * finishes the discussion area after last comment
  2084. *
  2085. * @name DiscussionViewer.finishDiscussion
  2086. * @function
  2087. */
  2088. me.finishDiscussion = function()
  2089. {
  2090. // add 'add new comment' area
  2091. $commentContainer.append($commentTail);
  2092. // show discussions
  2093. $discussion.removeClass('hidden');
  2094. }
  2095. /**
  2096. * shows the discussion area
  2097. *
  2098. * @name DiscussionViewer.showDiscussion
  2099. * @function
  2100. */
  2101. me.showDiscussion = function()
  2102. {
  2103. $discussion.removeClass('hidden');
  2104. }
  2105. /**
  2106. * removes the old discussion and prepares everything for creating a new
  2107. * one.
  2108. *
  2109. * @name DiscussionViewer.prepareNewDisucssion
  2110. * @function
  2111. */
  2112. me.prepareNewDisucssion = function()
  2113. {
  2114. $commentContainer.html('');
  2115. $discussion.addClass('hidden');
  2116. // (re-)init templates
  2117. initTemplates();
  2118. }
  2119. /**
  2120. * returns the user put into the reply form
  2121. *
  2122. * @name DiscussionViewer.getReplyData
  2123. * @function
  2124. * @return {array}
  2125. */
  2126. me.getReplyData = function()
  2127. {
  2128. return [
  2129. $replyMessage.val(),
  2130. $replyNickname.val()
  2131. ];
  2132. }
  2133. /**
  2134. * highlights a specific comment and scrolls to it if necessary
  2135. *
  2136. * @name DiscussionViewer.highlightComment
  2137. * @function
  2138. * @param {string} commentId
  2139. * @param {bool} fadeOut - whether to fade out the comment
  2140. */
  2141. me.highlightComment = function(commentId, fadeOut)
  2142. {
  2143. var $comment = $('#comment_' + commentId);
  2144. // in case comment does not exist, cancel
  2145. if ($comment.length === 0) {
  2146. return;
  2147. }
  2148. var highlightComment = function () {
  2149. $comment.addClass('highlight');
  2150. if (fadeOut === true) {
  2151. setTimeout(function () {
  2152. $comment.removeClass('highlight');
  2153. }, 300);
  2154. }
  2155. }
  2156. if (UiHelper.isVisible($comment)) {
  2157. return highlightComment();
  2158. }
  2159. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2160. }
  2161. /**
  2162. * returns the id of the parent comment the user is replying to
  2163. *
  2164. * @name DiscussionViewer.getReplyCommentId
  2165. * @function
  2166. * @return {int|undefined}
  2167. */
  2168. me.getReplyCommentId = function()
  2169. {
  2170. return replyCommentId;
  2171. }
  2172. /**
  2173. * initiate
  2174. *
  2175. * preloads jQuery elements
  2176. *
  2177. * @name DiscussionViewer.init
  2178. * @function
  2179. */
  2180. me.init = function()
  2181. {
  2182. // bind events to templates (so they are later cloned)
  2183. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2184. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2185. $commentContainer = $('#commentcontainer');
  2186. $discussion = $('#discussion');
  2187. }
  2188. return me;
  2189. })(window, document);
  2190. /**
  2191. * Manage top (navigation) bar
  2192. *
  2193. * @name TopNav
  2194. * @param {object} window
  2195. * @param {object} document
  2196. * @class
  2197. */
  2198. var TopNav = (function (window, document) {
  2199. var me = {};
  2200. var createButtonsDisplayed = false;
  2201. var viewButtonsDisplayed = false;
  2202. var $attach,
  2203. $burnAfterReading,
  2204. $burnAfterReadingOption,
  2205. $cloneButton,
  2206. $customAttachment,
  2207. $expiration,
  2208. $fileRemoveButton,
  2209. $fileWrap,
  2210. $formatter,
  2211. $newButton,
  2212. $openDiscussion,
  2213. $openDiscussionOption,
  2214. $password,
  2215. $passwordInput,
  2216. $rawTextButton,
  2217. $sendButton;
  2218. var pasteExpiration = '1week';
  2219. /**
  2220. * set the expiration on bootstrap templates in dropdown
  2221. *
  2222. * @name TopNav.updateExpiration
  2223. * @private
  2224. * @function
  2225. * @param {Event} event
  2226. */
  2227. function updateExpiration(event)
  2228. {
  2229. // get selected option
  2230. var target = $(event.target);
  2231. // update dropdown display and save new expiration time
  2232. $('#pasteExpirationDisplay').text(target.text());
  2233. pasteExpiration = target.data('expiration');
  2234. event.preventDefault();
  2235. }
  2236. /**
  2237. * set the format on bootstrap templates in dropdown
  2238. *
  2239. * @name TopNav.updateFormat
  2240. * @private
  2241. * @function
  2242. * @param {Event} event
  2243. */
  2244. function updateFormat(event)
  2245. {
  2246. // get selected option
  2247. var $target = $(event.target);
  2248. // update dropdown display and save new format
  2249. var newFormat = $target.data('format');
  2250. $('#pasteFormatterDisplay').text($target.text());
  2251. PasteViewer.setFormat(newFormat);
  2252. // update preview
  2253. if (Editor.isPreview()) {
  2254. PasteViewer.run();
  2255. }
  2256. event.preventDefault();
  2257. }
  2258. /**
  2259. * when "burn after reading" is checked, disable discussion
  2260. *
  2261. * @name TopNav.changeBurnAfterReading
  2262. * @private
  2263. * @function
  2264. */
  2265. function changeBurnAfterReading()
  2266. {
  2267. if ($burnAfterReading.is(':checked')) {
  2268. $openDiscussionOption.addClass('buttondisabled');
  2269. $openDiscussion.prop('checked', false);
  2270. // if button is actually disabled, force-enable it and uncheck other button
  2271. $burnAfterReadingOption.removeClass('buttondisabled');
  2272. } else {
  2273. $openDiscussionOption.removeClass('buttondisabled');
  2274. }
  2275. }
  2276. /**
  2277. * when discussion is checked, disable "burn after reading"
  2278. *
  2279. * @name TopNav.changeOpenDiscussion
  2280. * @private
  2281. * @function
  2282. */
  2283. function changeOpenDiscussion()
  2284. {
  2285. if ($openDiscussion.is(':checked')) {
  2286. $burnAfterReadingOption.addClass('buttondisabled');
  2287. $burnAfterReading.prop('checked', false);
  2288. // if button is actually disabled, force-enable it and uncheck other button
  2289. $openDiscussionOption.removeClass('buttondisabled');
  2290. } else {
  2291. $burnAfterReadingOption.removeClass('buttondisabled');
  2292. }
  2293. }
  2294. /**
  2295. * return raw text
  2296. *
  2297. * @name TopNav.rawText
  2298. * @private
  2299. * @function
  2300. * @param {Event} event
  2301. */
  2302. function rawText(event)
  2303. {
  2304. TopNav.hideAllButtons();
  2305. Alert.showLoading('Showing raw text…', 0, 'time');
  2306. var paste = PasteViewer.getText();
  2307. // push a new state to allow back navigation with browser back button
  2308. history.pushState(
  2309. {type: 'raw'},
  2310. document.title,
  2311. // recreate paste URL
  2312. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  2313. Model.getPasteKey()
  2314. );
  2315. // we use text/html instead of text/plain to avoid a bug when
  2316. // reloading the raw text view (it reverts to type text/html)
  2317. var $head = $('head').children().not('noscript, script, link[type="text/css"]');
  2318. var newDoc = document.open('text/html', 'replace');
  2319. newDoc.write('<!DOCTYPE html><html><head>');
  2320. for (var i = 0; i < $head.length; i++) {
  2321. newDoc.write($head[i].outerHTML);
  2322. }
  2323. newDoc.write('</head><body><pre>' + Helper.htmlEntities(paste) + '</pre></body></html>');
  2324. newDoc.close();
  2325. }
  2326. /**
  2327. * saves the language in a cookie and reloads the page
  2328. *
  2329. * @name TopNav.setLanguage
  2330. * @private
  2331. * @function
  2332. * @param {Event} event
  2333. */
  2334. function setLanguage(event)
  2335. {
  2336. document.cookie = 'lang=' + $(event.target).data('lang');
  2337. UiHelper.reloadHome();
  2338. }
  2339. /**
  2340. * hides all messages and creates a new paste
  2341. *
  2342. * @name TopNav.clickNewPaste
  2343. * @private
  2344. * @function
  2345. * @param {Event} event
  2346. */
  2347. function clickNewPaste(event)
  2348. {
  2349. Controller.hideStatusMessages();
  2350. Controller.newPaste();
  2351. }
  2352. /**
  2353. * removes the existing attachment
  2354. *
  2355. * @name TopNav.removeAttachment
  2356. * @private
  2357. * @function
  2358. * @param {Event} event
  2359. */
  2360. function removeAttachment(event)
  2361. {
  2362. // if custom attachment is used, remove it first
  2363. if (!$customAttachment.hasClass('hidden')) {
  2364. AttachmentViewer.removeAttachment();
  2365. $customAttachment.addClass('hidden');
  2366. $fileWrap.removeClass('hidden');
  2367. }
  2368. // our up-to-date jQuery can handle it :)
  2369. $fileWrap.find('input').val('');
  2370. // pevent '#' from appearing in the URL
  2371. event.preventDefault();
  2372. }
  2373. /**
  2374. * Shows all elements belonging to viwing an existing pastes
  2375. *
  2376. * @name TopNav.showViewButtons
  2377. * @function
  2378. */
  2379. me.showViewButtons = function()
  2380. {
  2381. if (viewButtonsDisplayed) {
  2382. console.warn('showViewButtons: view buttons are already displayed');
  2383. return;
  2384. }
  2385. $newButton.removeClass('hidden');
  2386. $cloneButton.removeClass('hidden');
  2387. $rawTextButton.removeClass('hidden');
  2388. viewButtonsDisplayed = true;
  2389. }
  2390. /**
  2391. * Hides all elements belonging to existing pastes
  2392. *
  2393. * @name TopNav.hideViewButtons
  2394. * @function
  2395. */
  2396. me.hideViewButtons = function()
  2397. {
  2398. if (!viewButtonsDisplayed) {
  2399. console.warn('hideViewButtons: view buttons are already hidden');
  2400. return;
  2401. }
  2402. $newButton.addClass('hidden');
  2403. $cloneButton.addClass('hidden');
  2404. $rawTextButton.addClass('hidden');
  2405. viewButtonsDisplayed = false;
  2406. }
  2407. /**
  2408. * Hides all elements belonging to existing pastes
  2409. *
  2410. * @name TopNav.hideAllButtons
  2411. * @function
  2412. */
  2413. me.hideAllButtons = function()
  2414. {
  2415. me.hideViewButtons();
  2416. me.hideCreateButtons();
  2417. }
  2418. /**
  2419. * shows all elements needed when creating a new paste
  2420. *
  2421. * @name TopNav.showCreateButtons
  2422. * @function
  2423. */
  2424. me.showCreateButtons = function()
  2425. {
  2426. if (createButtonsDisplayed) {
  2427. console.warn('showCreateButtons: create buttons are already displayed');
  2428. return;
  2429. }
  2430. $sendButton.removeClass('hidden');
  2431. $expiration.removeClass('hidden');
  2432. $formatter.removeClass('hidden');
  2433. $burnAfterReadingOption.removeClass('hidden');
  2434. $openDiscussionOption.removeClass('hidden');
  2435. $newButton.removeClass('hidden');
  2436. $password.removeClass('hidden');
  2437. $attach.removeClass('hidden');
  2438. createButtonsDisplayed = true;
  2439. }
  2440. /**
  2441. * shows all elements needed when creating a new paste
  2442. *
  2443. * @name TopNav.hideCreateButtons
  2444. * @function
  2445. */
  2446. me.hideCreateButtons = function()
  2447. {
  2448. if (!createButtonsDisplayed) {
  2449. console.warn('hideCreateButtons: create buttons are already hidden');
  2450. return;
  2451. }
  2452. $newButton.addClass('hidden');
  2453. $sendButton.addClass('hidden');
  2454. $expiration.addClass('hidden');
  2455. $formatter.addClass('hidden');
  2456. $burnAfterReadingOption.addClass('hidden');
  2457. $openDiscussionOption.addClass('hidden');
  2458. $password.addClass('hidden');
  2459. $attach.addClass('hidden');
  2460. createButtonsDisplayed = false;
  2461. }
  2462. /**
  2463. * only shows the "new paste" button
  2464. *
  2465. * @name TopNav.showNewPasteButton
  2466. * @function
  2467. */
  2468. me.showNewPasteButton = function()
  2469. {
  2470. $newButton.removeClass('hidden');
  2471. }
  2472. /**
  2473. * only hides the clone button
  2474. *
  2475. * @name TopNav.hideCloneButton
  2476. * @function
  2477. */
  2478. me.hideCloneButton = function()
  2479. {
  2480. $cloneButton.addClass('hidden');
  2481. }
  2482. /**
  2483. * only hides the raw text button
  2484. *
  2485. * @name TopNav.hideRawButton
  2486. * @function
  2487. */
  2488. me.hideRawButton = function()
  2489. {
  2490. $rawTextButton.addClass('hidden');
  2491. }
  2492. /**
  2493. * hides the file selector in attachment
  2494. *
  2495. * @name TopNav.hideFileSelector
  2496. * @function
  2497. */
  2498. me.hideFileSelector = function()
  2499. {
  2500. $fileWrap.addClass('hidden');
  2501. }
  2502. /**
  2503. * shows the custom attachment
  2504. *
  2505. * @name TopNav.showCustomAttachment
  2506. * @function
  2507. */
  2508. me.showCustomAttachment = function()
  2509. {
  2510. $customAttachment.removeClass('hidden');
  2511. }
  2512. /**
  2513. * collapses the navigation bar if nedded
  2514. *
  2515. * @name TopNav.collapseBar
  2516. * @function
  2517. */
  2518. me.collapseBar = function()
  2519. {
  2520. var $bar = $('.navbar-toggle');
  2521. // check if bar is expanded
  2522. if ($bar.hasClass('collapse in')) {
  2523. // if so, toggle it
  2524. $bar.click();
  2525. }
  2526. }
  2527. /**
  2528. * returns the currently set expiration time
  2529. *
  2530. * @name TopNav.getExpiration
  2531. * @function
  2532. * @return {int}
  2533. */
  2534. me.getExpiration = function()
  2535. {
  2536. return pasteExpiration;
  2537. }
  2538. /**
  2539. * returns the currently selected file(s)
  2540. *
  2541. * @name TopNav.getFileList
  2542. * @function
  2543. * @return {FileList|null}
  2544. */
  2545. me.getFileList = function()
  2546. {
  2547. var $file = $('#file');
  2548. // if no file given, return null
  2549. if (!$file.length || !$file[0].files.length) {
  2550. return null;
  2551. }
  2552. // @TODO is this really necessary
  2553. if (!($file[0].files && $file[0].files[0])) {
  2554. return null;
  2555. }
  2556. return $file[0].files;
  2557. }
  2558. /**
  2559. * returns the state of the burn after reading checkbox
  2560. *
  2561. * @name TopNav.getExpiration
  2562. * @function
  2563. * @return {bool}
  2564. */
  2565. me.getBurnAfterReading = function()
  2566. {
  2567. return $burnAfterReading.is(':checked');
  2568. }
  2569. /**
  2570. * returns the state of the discussion checkbox
  2571. *
  2572. * @name TopNav.getOpenDiscussion
  2573. * @function
  2574. * @return {bool}
  2575. */
  2576. me.getOpenDiscussion = function()
  2577. {
  2578. return $openDiscussion.is(':checked');
  2579. }
  2580. /**
  2581. * returns the entered password
  2582. *
  2583. * @name TopNav.getPassword
  2584. * @function
  2585. * @return {string}
  2586. */
  2587. me.getPassword = function()
  2588. {
  2589. return $passwordInput.val();
  2590. }
  2591. /**
  2592. * returns the element where custom attachments can be placed
  2593. *
  2594. * Used by AttachmentViewer when an attachment is cloned here.
  2595. *
  2596. * @name TopNav.getCustomAttachment
  2597. * @function
  2598. * @return {jQuery}
  2599. */
  2600. me.getCustomAttachment = function()
  2601. {
  2602. return $customAttachment;
  2603. }
  2604. /**
  2605. * init navigation manager
  2606. *
  2607. * preloads jQuery elements
  2608. *
  2609. * @name TopNav.init
  2610. * @function
  2611. */
  2612. me.init = function()
  2613. {
  2614. $attach = $('#attach');
  2615. $burnAfterReading = $('#burnafterreading');
  2616. $burnAfterReadingOption = $('#burnafterreadingoption');
  2617. $cloneButton = $('#clonebutton');
  2618. $customAttachment = $('#customattachment');
  2619. $expiration = $('#expiration');
  2620. $fileRemoveButton = $('#fileremovebutton');
  2621. $fileWrap = $('#filewrap');
  2622. $formatter = $('#formatter');
  2623. $newButton = $('#newbutton');
  2624. $openDiscussion = $('#opendiscussion');
  2625. $openDiscussionOption = $('#opendiscussionoption');
  2626. $password = $('#password');
  2627. $passwordInput = $('#passwordinput');
  2628. $rawTextButton = $('#rawtextbutton');
  2629. $sendButton = $('#sendbutton');
  2630. // bootstrap template drop down
  2631. $('#language ul.dropdown-menu li a').click(setLanguage);
  2632. // page template drop down
  2633. $('#language select option').click(setLanguage);
  2634. // bind events
  2635. $burnAfterReading.change(changeBurnAfterReading);
  2636. $openDiscussionOption.change(changeOpenDiscussion);
  2637. $newButton.click(clickNewPaste);
  2638. $sendButton.click(PasteEncrypter.sendPaste);
  2639. $cloneButton.click(Controller.clonePaste);
  2640. $rawTextButton.click(rawText);
  2641. $fileRemoveButton.click(removeAttachment);
  2642. // bootstrap template drop downs
  2643. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2644. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2645. // initiate default state of checkboxes
  2646. changeBurnAfterReading();
  2647. changeOpenDiscussion();
  2648. // get default value from template or fall back to set value
  2649. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2650. }
  2651. return me;
  2652. })(window, document);
  2653. /**
  2654. * Responsible for AJAX requests, transparently handles encryption…
  2655. *
  2656. * @name Uploader
  2657. * @class
  2658. */
  2659. var Uploader = (function () {
  2660. var me = {};
  2661. var successFunc = null,
  2662. failureFunc = null,
  2663. url,
  2664. data,
  2665. symmetricKey,
  2666. password;
  2667. /**
  2668. * public variable ('constant') for errors to prevent magic numbers
  2669. *
  2670. * @name Uploader.error
  2671. * @readonly
  2672. * @enum {Object}
  2673. */
  2674. me.error = {
  2675. okay: 0,
  2676. custom: 1,
  2677. unknown: 2,
  2678. serverError: 3
  2679. };
  2680. /**
  2681. * ajaxHeaders to send in AJAX requests
  2682. *
  2683. * @name Uploader.ajaxHeaders
  2684. * @private
  2685. * @readonly
  2686. * @enum {Object}
  2687. */
  2688. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  2689. /**
  2690. * called after successful upload
  2691. *
  2692. * @name Uploader.checkCryptParameters
  2693. * @private
  2694. * @function
  2695. * @throws {string}
  2696. */
  2697. function checkCryptParameters()
  2698. {
  2699. // workaround for this nasty 'bug' in ECMAScript
  2700. // see https://stackoverflow.com/questions/18808226/why-is-typeof-null-object
  2701. var typeOfKey = typeof symmetricKey;
  2702. if (symmetricKey === null) {
  2703. typeOfKey = 'null';
  2704. }
  2705. // in case of missing preparation, throw error
  2706. switch (typeOfKey) {
  2707. case 'string':
  2708. // already set, all right
  2709. return;
  2710. case 'null':
  2711. // needs to be generated auto-generate
  2712. symmetricKey = CryptTool.getSymmetricKey();
  2713. break;
  2714. default:
  2715. console.error('current invalid symmetricKey:', symmetricKey);
  2716. throw 'symmetricKey is invalid, probably the module was not prepared';
  2717. }
  2718. // password is optional
  2719. }
  2720. /**
  2721. * called after successful upload
  2722. *
  2723. * @name Uploader.success
  2724. * @private
  2725. * @function
  2726. * @param {int} status
  2727. * @param {int} result - optional
  2728. */
  2729. function success(status, result)
  2730. {
  2731. // add useful data to result
  2732. result.encryptionKey = symmetricKey;
  2733. result.requestData = data;
  2734. if (successFunc !== null) {
  2735. successFunc(status, result);
  2736. }
  2737. }
  2738. /**
  2739. * called after a upload failure
  2740. *
  2741. * @name Uploader.fail
  2742. * @private
  2743. * @function
  2744. * @param {int} status - internal code
  2745. * @param {int} result - original error code
  2746. */
  2747. function fail(status, result)
  2748. {
  2749. if (failureFunc !== null) {
  2750. failureFunc(status, result);
  2751. }
  2752. }
  2753. /**
  2754. * actually uploads the data
  2755. *
  2756. * @name Uploader.run
  2757. * @function
  2758. */
  2759. me.run = function()
  2760. {
  2761. $.ajax({
  2762. type: 'POST',
  2763. url: url,
  2764. data: data,
  2765. dataType: 'json',
  2766. headers: ajaxHeaders,
  2767. success: function(result) {
  2768. if (result.status === 0) {
  2769. success(0, result);
  2770. } else if (result.status === 1) {
  2771. fail(1, result);
  2772. } else {
  2773. fail(2, result);
  2774. }
  2775. }
  2776. })
  2777. .fail(function(jqXHR, textStatus, errorThrown) {
  2778. console.error(textStatus, errorThrown);
  2779. fail(3, jqXHR);
  2780. });
  2781. }
  2782. /**
  2783. * set success function
  2784. *
  2785. * @name Uploader.setUrl
  2786. * @function
  2787. * @param {function} newUrl
  2788. */
  2789. me.setUrl = function(newUrl)
  2790. {
  2791. url = newUrl;
  2792. }
  2793. /**
  2794. * sets the password to use (first value) and optionally also the
  2795. * encryption key (not recommend, it is automatically generated).
  2796. *
  2797. * Note: Call this after prepare() as prepare() resets these values.
  2798. *
  2799. * @name Uploader.setCryptValues
  2800. * @function
  2801. * @param {string} newPassword
  2802. * @param {string} newKey - optional
  2803. */
  2804. me.setCryptParameters = function(newPassword, newKey)
  2805. {
  2806. password = newPassword;
  2807. if (typeof newKey !== 'undefined') {
  2808. symmetricKey = newKey;
  2809. }
  2810. }
  2811. /**
  2812. * set success function
  2813. *
  2814. * @name Uploader.setSuccess
  2815. * @function
  2816. * @param {function} func
  2817. */
  2818. me.setSuccess = function(func)
  2819. {
  2820. successFunc = func;
  2821. }
  2822. /**
  2823. * set failure function
  2824. *
  2825. * @name Uploader.setFailure
  2826. * @function
  2827. * @param {function} func
  2828. */
  2829. me.setFailure = function(func)
  2830. {
  2831. failureFunc = func;
  2832. }
  2833. /**
  2834. * prepares a new upload
  2835. *
  2836. * Call this when doing a new upload to reset any data from potential
  2837. * previous uploads. Must be called before any other method of this
  2838. * module.
  2839. *
  2840. * @name Uploader.prepare
  2841. * @function
  2842. * @return {object}
  2843. */
  2844. me.prepare = function()
  2845. {
  2846. // entropy should already be checked!
  2847. // reset password
  2848. password = '';
  2849. // reset key, so it a new one is generated when it is used
  2850. symmetricKey = null;
  2851. // reset data
  2852. successFunc = null;
  2853. failureFunc = null;
  2854. url = Helper.baseUri();
  2855. data = {};
  2856. }
  2857. /**
  2858. * encrypts and sets the data
  2859. *
  2860. * @name Uploader.setData
  2861. * @function
  2862. * @param {string} index
  2863. * @param {mixed} element
  2864. */
  2865. me.setData = function(index, element)
  2866. {
  2867. checkCryptParameters();
  2868. data[index] = CryptTool.cipher(symmetricKey, password, element);
  2869. }
  2870. /**
  2871. * set the additional metadata to send unencrypted
  2872. *
  2873. * @name Uploader.setUnencryptedData
  2874. * @function
  2875. * @param {string} index
  2876. * @param {mixed} element
  2877. */
  2878. me.setUnencryptedData = function(index, element)
  2879. {
  2880. data[index] = element;
  2881. }
  2882. /**
  2883. * set the additional metadata to send unencrypted passed at once
  2884. *
  2885. * @name Uploader.setUnencryptedData
  2886. * @function
  2887. * @param {object} newData
  2888. */
  2889. me.setUnencryptedBulkData = function(newData)
  2890. {
  2891. $.extend(data, newData);
  2892. }
  2893. /**
  2894. * Helper, which parses shows a general error message based on the result of the Uploader
  2895. *
  2896. * @name Uploader.parseUploadError
  2897. * @function
  2898. * @param {int} status
  2899. * @param {object} data
  2900. * @param {string} doThisThing - a human description of the action, which was tried
  2901. * @return {array}
  2902. */
  2903. me.parseUploadError = function(status, data, doThisThing) {
  2904. var errorArray;
  2905. switch (status) {
  2906. case me.error['custom']:
  2907. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  2908. break;
  2909. case me.error['unknown']:
  2910. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  2911. break;
  2912. case me.error['serverError']:
  2913. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  2914. break;
  2915. default:
  2916. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  2917. break;
  2918. }
  2919. return errorArray;
  2920. }
  2921. /**
  2922. * init Uploader
  2923. *
  2924. * @name Uploader.init
  2925. * @function
  2926. */
  2927. me.init = function()
  2928. {
  2929. // nothing yet
  2930. }
  2931. return me;
  2932. })();
  2933. /**
  2934. * (controller) Responsible for encrypting paste and sending it to server.
  2935. *
  2936. * Does upload, encryption is done transparently by Uploader.
  2937. *
  2938. * @name PasteEncrypter
  2939. * @class
  2940. */
  2941. var PasteEncrypter = (function () {
  2942. var me = {};
  2943. var requirementsChecked = false;
  2944. /**
  2945. * checks whether there is a suitable amount of entrophy
  2946. *
  2947. * @name PasteEncrypter.checkRequirements
  2948. * @private
  2949. * @function
  2950. * @param {function} retryCallback - the callback to execute to retry the upload
  2951. * @return {bool}
  2952. */
  2953. function checkRequirements(retryCallback) {
  2954. // skip double requirement checks
  2955. if (requirementsChecked === true) {
  2956. return true;
  2957. }
  2958. if (!CryptTool.isEntropyReady()) {
  2959. // display a message and wait
  2960. Alert.showStatus('Please move your mouse for more entropy…');
  2961. CryptTool.addEntropySeedListener(retryCallback);
  2962. return false;
  2963. }
  2964. requirementsChecked = true;
  2965. return true;
  2966. }
  2967. /**
  2968. * called after successful paste upload
  2969. *
  2970. * @name PasteEncrypter.showCreatedPaste
  2971. * @private
  2972. * @function
  2973. * @param {int} status
  2974. * @param {object} data
  2975. */
  2976. function showCreatedPaste(status, data) {
  2977. Alert.hideLoading();
  2978. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  2979. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  2980. Alert.hideMessages();
  2981. // show notification
  2982. PasteStatus.createPasteNotification(url, deleteUrl)
  2983. // show new URL in browser bar
  2984. history.pushState({type: 'newpaste'}, document.title, url);
  2985. TopNav.showViewButtons();
  2986. TopNav.hideRawButton();
  2987. Editor.hide();
  2988. // parse and show text
  2989. // (preparation already done in me.sendPaste())
  2990. PasteViewer.run();
  2991. }
  2992. /**
  2993. * called after successful comment upload
  2994. *
  2995. * @name PasteEncrypter.showUploadedComment
  2996. * @private
  2997. * @function
  2998. * @param {int} status
  2999. * @param {object} data
  3000. */
  3001. function showUploadedComment(status, data) {
  3002. // show success message
  3003. // Alert.showStatus('Comment posted.');
  3004. // reload paste
  3005. Controller.refreshPaste(function () {
  3006. // highlight sent comment
  3007. DiscussionViewer.highlightComment(data.id, true);
  3008. // reset error handler
  3009. Alert.setCustomHandler(null);
  3010. });
  3011. }
  3012. /**
  3013. * adds attachments to the Uploader
  3014. *
  3015. * @name PasteEncrypter.encryptAttachments
  3016. * @private
  3017. * @function
  3018. * @param {File|null|undefined} file - optional, falls back to cloned attachment
  3019. * @param {function} callback - excuted when action is successful
  3020. */
  3021. function encryptAttachments(file, callback) {
  3022. if (typeof file !== 'undefined' && file !== null) {
  3023. // check file reader requirements for upload
  3024. if (typeof FileReader === 'undefined') {
  3025. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  3026. // cancels process as it does not execute callback
  3027. return;
  3028. }
  3029. var reader = new FileReader();
  3030. // closure to capture the file information
  3031. reader.onload = function(event) {
  3032. Uploader.setData('attachment', event.target.result);
  3033. Uploader.setData('attachmentname', file.name);
  3034. // run callback
  3035. return callback();
  3036. }
  3037. // actually read first file
  3038. reader.readAsDataURL(file);
  3039. } else if (AttachmentViewer.hasAttachment()) {
  3040. // fall back to cloned part
  3041. var attachment = AttachmentViewer.getAttachment();
  3042. Uploader.setData('attachment', attachment[0]);
  3043. Uploader.setData('attachmentname', attachment[1]);
  3044. return callback();
  3045. } else {
  3046. // if there are no attachments, this is of course still successful
  3047. return callback();
  3048. }
  3049. }
  3050. /**
  3051. * send a reply in a discussion
  3052. *
  3053. * @name PasteEncrypter.sendComment
  3054. * @function
  3055. */
  3056. me.sendComment = function()
  3057. {
  3058. Alert.hideMessages();
  3059. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3060. // UI loading state
  3061. TopNav.hideAllButtons();
  3062. Alert.showLoading('Sending comment…', 0, 'cloud-upload');
  3063. // get data, note that "var [x, y] = " structures aren't supported in all JS environments
  3064. var replyData = DiscussionViewer.getReplyData(),
  3065. plainText = replyData[0],
  3066. nickname = replyData[1],
  3067. parentid = DiscussionViewer.getReplyCommentId();
  3068. // do not send if there is no data
  3069. if (plainText.length === 0) {
  3070. // revert loading status…
  3071. Alert.hideLoading();
  3072. Alert.setCustomHandler(null);
  3073. TopNav.showViewButtons();
  3074. return;
  3075. }
  3076. // check entropy
  3077. if (!checkRequirements(function () {
  3078. me.sendComment();
  3079. })) {
  3080. return; // to prevent multiple executions
  3081. }
  3082. Alert.showLoading(null, 10);
  3083. // prepare Uploader
  3084. Uploader.prepare();
  3085. Uploader.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3086. // set success/fail functions
  3087. Uploader.setSuccess(showUploadedComment);
  3088. Uploader.setFailure(function (status, data) {
  3089. // revert loading status…
  3090. Alert.hideLoading();
  3091. TopNav.showViewButtons();
  3092. // show error message
  3093. Alert.showError(Uploader.parseUploadError(status, data, 'post comment'));
  3094. // reset error handler
  3095. Alert.setCustomHandler(null);
  3096. });
  3097. // fill it with unencrypted params
  3098. Uploader.setUnencryptedData('pasteid', Model.getPasteId());
  3099. if (typeof parentid === 'undefined') {
  3100. // if parent id is not set, this is the top-most comment, so use
  3101. // paste id as parent @TODO is this really good?
  3102. Uploader.setUnencryptedData('parentid', Model.getPasteId());
  3103. } else {
  3104. Uploader.setUnencryptedData('parentid', parentid);
  3105. }
  3106. // encrypt data
  3107. Uploader.setData('data', plainText);
  3108. if (nickname.length > 0) {
  3109. Uploader.setData('nickname', nickname);
  3110. }
  3111. Uploader.run();
  3112. }
  3113. /**
  3114. * sends a new paste to server
  3115. *
  3116. * @name PasteEncrypter.sendPaste
  3117. * @function
  3118. */
  3119. me.sendPaste = function()
  3120. {
  3121. // hide previous (error) messages
  3122. Controller.hideStatusMessages();
  3123. // UI loading state
  3124. TopNav.hideAllButtons();
  3125. Alert.showLoading('Sending paste…', 0, 'cloud-upload');
  3126. TopNav.collapseBar();
  3127. // get data
  3128. var plainText = Editor.getText(),
  3129. format = PasteViewer.getFormat(),
  3130. files = TopNav.getFileList();
  3131. // do not send if there is no data
  3132. if (plainText.length === 0 && files === null) {
  3133. // revert loading status…
  3134. Alert.hideLoading();
  3135. TopNav.showCreateButtons();
  3136. return;
  3137. }
  3138. Alert.showLoading(null, 10);
  3139. // check entropy
  3140. if (!checkRequirements(function () {
  3141. me.sendPaste();
  3142. })) {
  3143. return; // to prevent multiple executions
  3144. }
  3145. // prepare Uploader
  3146. Uploader.prepare();
  3147. Uploader.setCryptParameters(TopNav.getPassword());
  3148. // set success/fail functions
  3149. Uploader.setSuccess(showCreatedPaste);
  3150. Uploader.setFailure(function (status, data) {
  3151. // revert loading status…
  3152. Alert.hideLoading();
  3153. TopNav.showCreateButtons();
  3154. // show error message
  3155. Alert.showError(Uploader.parseUploadError(status, data, 'create paste'));
  3156. });
  3157. // fill it with unencrypted submitted options
  3158. Uploader.setUnencryptedBulkData({
  3159. expire: TopNav.getExpiration(),
  3160. formatter: format,
  3161. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  3162. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  3163. });
  3164. // prepare PasteViewer for later preview
  3165. PasteViewer.setText(plainText);
  3166. PasteViewer.setFormat(format);
  3167. // encrypt cipher data
  3168. Uploader.setData('data', plainText);
  3169. // encrypt attachments
  3170. encryptAttachments(
  3171. files === null ? null : files[0],
  3172. function () {
  3173. // send data
  3174. Uploader.run();
  3175. }
  3176. );
  3177. }
  3178. /**
  3179. * initialize
  3180. *
  3181. * @name PasteEncrypter.init
  3182. * @function
  3183. */
  3184. me.init = function()
  3185. {
  3186. // nothing yet
  3187. }
  3188. return me;
  3189. })();
  3190. /**
  3191. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3192. *
  3193. * Only decryption, no download.
  3194. *
  3195. * @name PasteDecrypter
  3196. * @class
  3197. */
  3198. var PasteDecrypter = (function () {
  3199. var me = {};
  3200. /**
  3201. * decrypt data or prompts for password in cvase of failure
  3202. *
  3203. * @name PasteDecrypter.decryptOrPromptPassword
  3204. * @private
  3205. * @function
  3206. * @param {string} key
  3207. * @param {string} password - optional, may be an empty string
  3208. * @param {string} cipherdata
  3209. * @throws {string}
  3210. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3211. */
  3212. function decryptOrPromptPassword(key, password, cipherdata)
  3213. {
  3214. // try decryption without password
  3215. var plaindata = CryptTool.decipher(key, password, cipherdata);
  3216. // if it fails, request password
  3217. if (plaindata.length === 0 && password.length === 0) {
  3218. // try to get cached password first
  3219. password = Prompt.getPassword();
  3220. // if password is there, re-try
  3221. if (password.length === 0) {
  3222. password = Prompt.requestPassword();
  3223. }
  3224. // recursive
  3225. // note: an infinite loop is prevented as the previous if
  3226. // clause checks whether a password is already set and ignores
  3227. // errors when a password has been passed
  3228. return decryptOrPromptPassword.apply(key, password, cipherdata);
  3229. }
  3230. // if all tries failed, we can only return an error
  3231. if (plaindata.length === 0) {
  3232. throw 'failed to decipher data';
  3233. }
  3234. return plaindata;
  3235. }
  3236. /**
  3237. * decrypt the actual paste text
  3238. *
  3239. * @name PasteDecrypter.decryptOrPromptPassword
  3240. * @private
  3241. * @function
  3242. * @param {object} paste - paste data in object form
  3243. * @param {string} key
  3244. * @param {string} password
  3245. * @param {bool} ignoreError - ignore decryption errors iof set to true
  3246. * @return {bool} whether action was successful
  3247. * @throws {string}
  3248. */
  3249. function decryptPaste(paste, key, password, ignoreError)
  3250. {
  3251. var plaintext
  3252. if (ignoreError === true) {
  3253. plaintext = CryptTool.decipher(key, password, paste.data);
  3254. } else {
  3255. try {
  3256. plaintext = decryptOrPromptPassword(key, password, paste.data);
  3257. } catch (err) {
  3258. throw 'failed to decipher paste text: ' + err
  3259. }
  3260. if (plaintext === false) {
  3261. return false;
  3262. }
  3263. }
  3264. // on success show paste
  3265. PasteViewer.setFormat(paste.meta.formatter);
  3266. PasteViewer.setText(plaintext);
  3267. // trigger to show the text (attachment loaded afterwards)
  3268. PasteViewer.run();
  3269. return true;
  3270. }
  3271. /**
  3272. * decrypts any attachment
  3273. *
  3274. * @name PasteDecrypter.decryptAttachment
  3275. * @private
  3276. * @function
  3277. * @param {object} paste - paste data in object form
  3278. * @param {string} key
  3279. * @param {string} password
  3280. * @return {bool} whether action was successful
  3281. * @throws {string}
  3282. */
  3283. function decryptAttachment(paste, key, password)
  3284. {
  3285. // decrypt attachment
  3286. try {
  3287. var attachment = decryptOrPromptPassword(key, password, paste.attachment);
  3288. } catch (err) {
  3289. throw 'failed to decipher attachment: ' + err
  3290. }
  3291. if (attachment === false) {
  3292. return false;
  3293. }
  3294. // decrypt attachment name
  3295. var attachmentName;
  3296. if (paste.attachmentname) {
  3297. try {
  3298. attachmentName = decryptOrPromptPassword(key, password, paste.attachmentname);
  3299. } catch (err) {
  3300. throw 'failed to decipher attachment name: ' + err
  3301. }
  3302. if (attachmentName === false) {
  3303. return false;
  3304. }
  3305. }
  3306. AttachmentViewer.setAttachment(attachment, attachmentName);
  3307. AttachmentViewer.showAttachment();
  3308. return true;
  3309. }
  3310. /**
  3311. * decrypts all comments and shows them
  3312. *
  3313. * @name PasteDecrypter.decryptComments
  3314. * @private
  3315. * @function
  3316. * @param {object} paste - paste data in object form
  3317. * @param {string} key
  3318. * @param {string} password
  3319. * @return {bool} whether action was successful
  3320. */
  3321. function decryptComments(paste, key, password)
  3322. {
  3323. // remove potentially previous discussion
  3324. DiscussionViewer.prepareNewDisucssion();
  3325. // iterate over comments
  3326. for (var i = 0; i < paste.comments.length; ++i) {
  3327. var comment = paste.comments[i];
  3328. DiscussionViewer.addComment(
  3329. comment,
  3330. CryptTool.decipher(key, password, comment.data),
  3331. CryptTool.decipher(key, password, comment.meta.nickname)
  3332. );
  3333. }
  3334. DiscussionViewer.finishDiscussion();
  3335. DiscussionViewer.showDiscussion();
  3336. return true;
  3337. }
  3338. /**
  3339. * show decrypted text in the display area, including discussion (if open)
  3340. *
  3341. * @name PasteDecrypter.run
  3342. * @function
  3343. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  3344. */
  3345. me.run = function(paste)
  3346. {
  3347. Alert.hideMessages();
  3348. Alert.showLoading('Decrypting paste…', 0, 'cloud-download'); // @TODO icon maybe rotation-lock, but needs full Glyphicons
  3349. if (typeof paste === 'undefined') {
  3350. paste = $.parseJSON(Model.getCipherData());
  3351. }
  3352. var key = Model.getPasteKey(),
  3353. password = Prompt.getPassword();
  3354. if (PasteViewer.isPrettyPrinted()) {
  3355. console.error('Too pretty! (don\'t know why this check)'); //@TODO
  3356. return;
  3357. }
  3358. // try to decrypt the paste
  3359. try {
  3360. // decrypt attachments
  3361. if (paste.attachment) {
  3362. // try to decrypt paste and if it fails (because the password is
  3363. // missing) return to let JS continue and wait for user
  3364. if (!decryptAttachment(paste, key, password)) {
  3365. return;
  3366. }
  3367. // ignore empty paste, as this is allowed when pasting attachments
  3368. decryptPaste(paste, key, password, true);
  3369. } else {
  3370. decryptPaste(paste, key, password);
  3371. }
  3372. // shows the remaining time (until) deletion
  3373. PasteStatus.showRemainingTime(paste.meta);
  3374. // if the discussion is opened on this paste, display it
  3375. if (paste.meta.opendiscussion) {
  3376. decryptComments(paste, key, password);
  3377. }
  3378. Alert.hideLoading();
  3379. TopNav.showViewButtons();
  3380. } catch(err) {
  3381. Alert.hideLoading();
  3382. // log and show error
  3383. console.error(err);
  3384. Alert.showError('Could not decrypt data (Wrong key?)');
  3385. }
  3386. }
  3387. /**
  3388. * initialize
  3389. *
  3390. * @name PasteDecrypter.init
  3391. * @function
  3392. */
  3393. me.init = function()
  3394. {
  3395. // nothing yet
  3396. }
  3397. return me;
  3398. })();
  3399. /**
  3400. * (controller) main PrivateBin logic
  3401. *
  3402. * @name Controller
  3403. * @param {object} window
  3404. * @param {object} document
  3405. * @class
  3406. */
  3407. var Controller = (function (window, document) {
  3408. var me = {};
  3409. /**
  3410. * hides all status messages no matter which module showed them
  3411. *
  3412. * @name Controller.hideStatusMessages
  3413. * @function
  3414. */
  3415. me.hideStatusMessages = function()
  3416. {
  3417. PasteStatus.hideMessages();
  3418. Alert.hideMessages();
  3419. }
  3420. /**
  3421. * creates a new paste
  3422. *
  3423. * @name Controller.newPaste
  3424. * @function
  3425. */
  3426. me.newPaste = function()
  3427. {
  3428. // Important: This *must not* run Alert.hideMessages() as previous
  3429. // errors from viewing a paste should be shown.
  3430. TopNav.hideAllButtons();
  3431. Alert.showLoading('Preparing new paste…', 0, 'time');
  3432. PasteStatus.hideMessages();
  3433. PasteViewer.hide();
  3434. Editor.resetInput();
  3435. Editor.show();
  3436. Editor.focusInput();
  3437. TopNav.showCreateButtons();
  3438. Alert.hideLoading();
  3439. }
  3440. /**
  3441. * shows the loaded paste
  3442. *
  3443. * @name Controller.showPaste
  3444. * @function
  3445. */
  3446. me.showPaste = function()
  3447. {
  3448. try {
  3449. Model.getPasteId();
  3450. Model.getPasteKey();
  3451. } catch (err) {
  3452. console.error(err);
  3453. // missing decryption key (or paste ID) in URL?
  3454. if (window.location.hash.length === 0) {
  3455. Alert.showError('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)');
  3456. // @TODO adjust error message as it is less specific now, probably include thrown exception for a detailed error
  3457. return;
  3458. }
  3459. }
  3460. // show proper elements on screen
  3461. PasteDecrypter.run();
  3462. }
  3463. /**
  3464. * refreshes the loaded paste to show potential new data
  3465. *
  3466. * @name Controller.refreshPaste
  3467. * @function
  3468. * @param {function} callback
  3469. */
  3470. me.refreshPaste = function(callback)
  3471. {
  3472. // save window position to restore it later
  3473. var orgPosition = $(window).scrollTop();
  3474. Uploader.prepare();
  3475. Uploader.setUrl(Helper.baseUri() + '?' + Model.getPasteId());
  3476. Uploader.setFailure(function (status, data) {
  3477. // revert loading status…
  3478. Alert.hideLoading();
  3479. TopNav.showViewButtons();
  3480. // show error message
  3481. Alert.showError(Uploader.parseUploadError(status, data, 'refresh display'));
  3482. })
  3483. Uploader.setSuccess(function (status, data) {
  3484. PasteDecrypter.run(data);
  3485. // restore position
  3486. window.scrollTo(0, orgPosition);
  3487. callback();
  3488. })
  3489. Uploader.run();
  3490. }
  3491. /**
  3492. * clone the current paste
  3493. *
  3494. * @name Controller.clonePaste
  3495. * @function
  3496. * @param {Event} event
  3497. */
  3498. me.clonePaste = function(event)
  3499. {
  3500. TopNav.collapseBar();
  3501. TopNav.hideAllButtons();
  3502. Alert.showLoading('Cloning paste…', 0, 'transfer');
  3503. // hide messages from previous paste
  3504. me.hideStatusMessages();
  3505. // erase the id and the key in url
  3506. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3507. if (AttachmentViewer.hasAttachment()) {
  3508. AttachmentViewer.moveAttachmentTo(
  3509. TopNav.getCustomAttachment(),
  3510. 'Cloned: \'%s\''
  3511. );
  3512. TopNav.hideFileSelector();
  3513. AttachmentViewer.hideAttachment();
  3514. // NOTE: it also looks nice without removing the attachment
  3515. // but for a consistent display we remove it…
  3516. AttachmentViewer.hideAttachmentPreview();
  3517. TopNav.showCustomAttachment();
  3518. // show another status message to make the user aware that the
  3519. // file was cloned too!
  3520. Alert.showStatus(
  3521. [
  3522. 'The cloned file \'%s\' was attached to this paste.',
  3523. AttachmentViewer.getAttachment()[1]
  3524. ], 'copy', true, true);
  3525. }
  3526. Editor.setText(PasteViewer.getText())
  3527. PasteViewer.hide();
  3528. Editor.show();
  3529. Alert.hideLoading();
  3530. TopNav.showCreateButtons();
  3531. }
  3532. /**
  3533. * removes a saved paste
  3534. *
  3535. * @name Controller.removePaste
  3536. * @function
  3537. * @param {string} pasteId
  3538. * @param {string} deleteToken
  3539. */
  3540. me.removePaste = function(pasteId, deleteToken) {
  3541. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3542. // so we use a POST request
  3543. Uploader.prepare();
  3544. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3545. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3546. Uploader.setFailure(function () {
  3547. Alert.showError(I18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  3548. })
  3549. Uploader.run();
  3550. }
  3551. /**
  3552. * application start
  3553. *
  3554. * @name Controller.init
  3555. * @function
  3556. */
  3557. me.init = function()
  3558. {
  3559. // first load translations
  3560. I18n.loadTranslations();
  3561. // initialize other modules/"classes"
  3562. Alert.init();
  3563. Model.init();
  3564. AttachmentViewer.init();
  3565. DiscussionViewer.init();
  3566. Editor.init();
  3567. PasteDecrypter.init();
  3568. PasteEncrypter.init();
  3569. PasteStatus.init();
  3570. PasteViewer.init();
  3571. Prompt.init();
  3572. TopNav.init();
  3573. UiHelper.init();
  3574. Uploader.init();
  3575. // display an existing paste
  3576. if (Model.hasCipherData()) {
  3577. return me.showPaste();
  3578. }
  3579. // otherwise create a new paste
  3580. me.newPaste();
  3581. }
  3582. return me;
  3583. })(window, document);
  3584. return {
  3585. Helper: Helper,
  3586. I18n: I18n,
  3587. CryptTool: CryptTool,
  3588. Model: Model,
  3589. UiHelper: UiHelper,
  3590. Alert: Alert,
  3591. PasteStatus: PasteStatus,
  3592. Prompt: Prompt,
  3593. Editor: Editor,
  3594. PasteViewer: PasteViewer,
  3595. AttachmentViewer: AttachmentViewer,
  3596. DiscussionViewer: DiscussionViewer,
  3597. TopNav: TopNav,
  3598. Uploader: Uploader,
  3599. PasteEncrypter: PasteEncrypter,
  3600. PasteDecrypter: PasteDecrypter,
  3601. Controller: Controller
  3602. };
  3603. }(jQuery, sjcl, Base64, RawDeflate);