privatebin.js 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063
  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. Helper.setElementText($plainText, text);
  1588. Helper.setElementText($prettyPrint, text);
  1589. switch (format) {
  1590. case 'markdown':
  1591. var converter = new showdown.Converter({
  1592. strikethrough: true,
  1593. tables: true,
  1594. tablesHeaderId: true
  1595. });
  1596. // let showdown convert the HTML and sanitize HTML *afterwards*!
  1597. $plainText.html(
  1598. DOMPurify.sanitize(converter.makeHtml(text), {SAFE_FOR_JQUERY: true})
  1599. );
  1600. // add table classes from bootstrap css
  1601. $plainText.find('table').addClass('table-condensed table-bordered');
  1602. break;
  1603. case 'syntaxhighlighting':
  1604. // @TODO is this really needed or is "one" enough?
  1605. if (typeof prettyPrint === 'function')
  1606. {
  1607. prettyPrint();
  1608. }
  1609. $prettyPrint.html(
  1610. prettyPrintOne(
  1611. Helper.htmlEntities(text), null, true
  1612. )
  1613. );
  1614. // fall through, as the rest is the same
  1615. default: // = 'plaintext'
  1616. // convert URLs to clickable links
  1617. Helper.urls2links($plainText);
  1618. Helper.urls2links($prettyPrint);
  1619. $plainText.html(
  1620. DOMPurify.sanitize(
  1621. $plainText.html(), {SAFE_FOR_JQUERY: true}
  1622. )
  1623. );
  1624. $prettyPrint.html(
  1625. DOMPurify.sanitize(
  1626. $prettyPrint.html(), {SAFE_FOR_JQUERY: true}
  1627. )
  1628. );
  1629. $prettyPrint.css('white-space', 'pre-wrap');
  1630. $prettyPrint.css('word-break', 'normal');
  1631. $prettyPrint.removeClass('prettyprint');
  1632. }
  1633. }
  1634. /**
  1635. * displays the paste
  1636. *
  1637. * @name PasteViewer.showPaste
  1638. * @private
  1639. * @function
  1640. */
  1641. function showPaste()
  1642. {
  1643. // instead of "nothing" better display a placeholder
  1644. if (text === '') {
  1645. $placeholder.removeClass('hidden')
  1646. return;
  1647. }
  1648. // otherwise hide the placeholder
  1649. $placeholder.addClass('hidden')
  1650. switch (format) {
  1651. case 'markdown':
  1652. $plainText.removeClass('hidden');
  1653. $prettyMessage.addClass('hidden');
  1654. break;
  1655. default:
  1656. $plainText.addClass('hidden');
  1657. $prettyMessage.removeClass('hidden');
  1658. break;
  1659. }
  1660. }
  1661. /**
  1662. * sets the format in which the text is shown
  1663. *
  1664. * @name PasteViewer.setFormat
  1665. * @function
  1666. * @param {string} newFormat the new format
  1667. */
  1668. me.setFormat = function(newFormat)
  1669. {
  1670. // skip if there is no update
  1671. if (format === newFormat) {
  1672. return;
  1673. }
  1674. // needs to update display too, if we switch from or to Markdown
  1675. if (format === 'markdown' || newFormat === 'markdown') {
  1676. isDisplayed = false;
  1677. }
  1678. format = newFormat;
  1679. isChanged = true;
  1680. }
  1681. /**
  1682. * returns the current format
  1683. *
  1684. * @name PasteViewer.getFormat
  1685. * @function
  1686. * @return {string}
  1687. */
  1688. me.getFormat = function()
  1689. {
  1690. return format;
  1691. }
  1692. /**
  1693. * returns whether the current view is pretty printed
  1694. *
  1695. * @name PasteViewer.isPrettyPrinted
  1696. * @function
  1697. * @return {bool}
  1698. */
  1699. me.isPrettyPrinted = function()
  1700. {
  1701. return $prettyPrint.hasClass('prettyprinted');
  1702. }
  1703. /**
  1704. * sets the text to show
  1705. *
  1706. * @name PasteViewer.setText
  1707. * @function
  1708. * @param {string} newText the text to show
  1709. */
  1710. me.setText = function(newText)
  1711. {
  1712. if (text !== newText) {
  1713. text = newText;
  1714. isChanged = true;
  1715. }
  1716. }
  1717. /**
  1718. * gets the current cached text
  1719. *
  1720. * @name PasteViewer.getText
  1721. * @function
  1722. * @return {string}
  1723. */
  1724. me.getText = function()
  1725. {
  1726. return text;
  1727. }
  1728. /**
  1729. * show/update the parsed text (preview)
  1730. *
  1731. * @name PasteViewer.run
  1732. * @function
  1733. */
  1734. me.run = function()
  1735. {
  1736. if (isChanged) {
  1737. parsePaste();
  1738. isChanged = false;
  1739. }
  1740. if (!isDisplayed) {
  1741. showPaste();
  1742. isDisplayed = true;
  1743. }
  1744. }
  1745. /**
  1746. * hide parsed text (preview)
  1747. *
  1748. * @name PasteViewer.hide
  1749. * @function
  1750. */
  1751. me.hide = function()
  1752. {
  1753. if (!isDisplayed) {
  1754. console.warn('PasteViewer was called to hide the parsed view, but it is already hidden.');
  1755. }
  1756. $plainText.addClass('hidden');
  1757. $prettyMessage.addClass('hidden');
  1758. $placeholder.addClass('hidden');
  1759. isDisplayed = false;
  1760. }
  1761. /**
  1762. * init status manager
  1763. *
  1764. * preloads jQuery elements
  1765. *
  1766. * @name PasteViewer.init
  1767. * @function
  1768. */
  1769. me.init = function()
  1770. {
  1771. $placeholder = $('#placeholder');
  1772. $plainText = $('#plaintext');
  1773. $prettyMessage = $('#prettymessage');
  1774. $prettyPrint = $('#prettyprint');
  1775. // check requirements
  1776. if (typeof prettyPrintOne !== 'function') {
  1777. Alert.showError([
  1778. 'The library %s is not available. This may cause display errors.',
  1779. 'pretty print'
  1780. ]);
  1781. }
  1782. if (typeof showdown !== 'object') {
  1783. Alert.showError([
  1784. 'The library %s is not available. This may cause display errors.',
  1785. 'showdown'
  1786. ]);
  1787. }
  1788. // get default option from template/HTML or fall back to set value
  1789. format = Model.getFormatDefault() || format;
  1790. text = '';
  1791. isDisplayed = false;
  1792. isChanged = true;
  1793. }
  1794. return me;
  1795. })();
  1796. /**
  1797. * (view) Show attachment and preview if possible
  1798. *
  1799. * @name AttachmentViewer
  1800. * @param {object} window
  1801. * @param {object} document
  1802. * @class
  1803. */
  1804. var AttachmentViewer = (function (window, document) {
  1805. var me = {};
  1806. var $attachmentLink,
  1807. $attachmentPreview,
  1808. $attachment;
  1809. var attachmentHasPreview = false;
  1810. /**
  1811. * sets the attachment but does not yet show it
  1812. *
  1813. * @name AttachmentViewer.setAttachment
  1814. * @function
  1815. * @param {string} attachmentData - base64-encoded data of file
  1816. * @param {string} fileName - optional, file name
  1817. */
  1818. me.setAttachment = function(attachmentData, fileName)
  1819. {
  1820. var imagePrefix = 'data:image/';
  1821. $attachmentLink.attr('href', attachmentData);
  1822. if (typeof fileName !== 'undefined') {
  1823. $attachmentLink.attr('download', fileName);
  1824. }
  1825. // if the attachment is an image, display it
  1826. if (attachmentData.substring(0, imagePrefix.length) === imagePrefix) {
  1827. $attachmentPreview.html(
  1828. $(document.createElement('img'))
  1829. .attr('src', attachmentData)
  1830. .attr('class', 'img-thumbnail')
  1831. );
  1832. attachmentHasPreview = true;
  1833. }
  1834. }
  1835. /**
  1836. * displays the attachment
  1837. *
  1838. * @name AttachmentViewer.showAttachment
  1839. * @function
  1840. */
  1841. me.showAttachment = function()
  1842. {
  1843. $attachment.removeClass('hidden');
  1844. if (attachmentHasPreview) {
  1845. $attachmentPreview.removeClass('hidden');
  1846. }
  1847. }
  1848. /**
  1849. * removes the attachment
  1850. *
  1851. * This automatically hides the attachment containers to, to
  1852. * prevent an inconsistent display.
  1853. *
  1854. * @name AttachmentViewer.removeAttachment
  1855. * @function
  1856. */
  1857. me.removeAttachment = function()
  1858. {
  1859. me.hideAttachment();
  1860. me.hideAttachmentPreview();
  1861. $attachmentLink.prop('href', '');
  1862. $attachmentLink.prop('download', '');
  1863. $attachmentPreview.html('');
  1864. }
  1865. /**
  1866. * hides the attachment
  1867. *
  1868. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  1869. * for that) nor will it hide the attachment link if it was moved somewhere
  1870. * else (see AttachmentViewer.moveAttachmentTo).
  1871. *
  1872. * @name AttachmentViewer.hideAttachment
  1873. * @function
  1874. */
  1875. me.hideAttachment = function()
  1876. {
  1877. $attachment.addClass('hidden');
  1878. }
  1879. /**
  1880. * hides the attachment preview
  1881. *
  1882. * @name AttachmentViewer.hideAttachmentPreview
  1883. * @function
  1884. */
  1885. me.hideAttachmentPreview = function()
  1886. {
  1887. $attachmentPreview.addClass('hidden');
  1888. }
  1889. /**
  1890. * checks if there is an attachment
  1891. *
  1892. * @name AttachmentViewer.hasAttachment
  1893. * @function
  1894. */
  1895. me.hasAttachment = function()
  1896. {
  1897. var link = $attachmentLink.prop('href');
  1898. return (typeof link !== 'undefined' && link !== '')
  1899. }
  1900. /**
  1901. * return the attachment
  1902. *
  1903. * @name AttachmentViewer.getAttachment
  1904. * @function
  1905. * @returns {array}
  1906. */
  1907. me.getAttachment = function()
  1908. {
  1909. return [
  1910. $attachmentLink.prop('href'),
  1911. $attachmentLink.prop('download')
  1912. ];
  1913. }
  1914. /**
  1915. * moves the attachment link to another element
  1916. *
  1917. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  1918. *
  1919. * @name AttachmentViewer.moveAttachmentTo
  1920. * @function
  1921. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  1922. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  1923. */
  1924. me.moveAttachmentTo = function($element, label)
  1925. {
  1926. // move elemement to new place
  1927. $attachmentLink.appendTo($element);
  1928. // update text
  1929. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  1930. }
  1931. /**
  1932. * initiate
  1933. *
  1934. * preloads jQuery elements
  1935. *
  1936. * @name AttachmentViewer.init
  1937. * @function
  1938. */
  1939. me.init = function()
  1940. {
  1941. $attachment = $('#attachment');
  1942. $attachmentLink = $('#attachment a');
  1943. $attachmentPreview = $('#attachmentPreview');
  1944. }
  1945. return me;
  1946. })(window, document);
  1947. /**
  1948. * (view) Shows discussion thread and handles replies
  1949. *
  1950. * @name DiscussionViewer
  1951. * @param {object} window
  1952. * @param {object} document
  1953. * @class
  1954. */
  1955. var DiscussionViewer = (function (window, document) {
  1956. var me = {};
  1957. var $commentTail,
  1958. $discussion,
  1959. $reply,
  1960. $replyMessage,
  1961. $replyNickname,
  1962. $replyStatus,
  1963. $commentContainer;
  1964. var replyCommentId;
  1965. /**
  1966. * initializes the templates
  1967. *
  1968. * @name DiscussionViewer.initTemplates
  1969. * @private
  1970. * @function
  1971. */
  1972. function initTemplates()
  1973. {
  1974. $reply = Model.getTemplate('reply');
  1975. $replyMessage = $reply.find('#replymessage');
  1976. $replyNickname = $reply.find('#nickname');
  1977. $replyStatus = $reply.find('#replystatus');
  1978. // cache jQuery elements
  1979. $commentTail = Model.getTemplate('commenttail');
  1980. }
  1981. /**
  1982. * open the comment entry when clicking the "Reply" button of a comment
  1983. *
  1984. * @name DiscussionViewer.openReply
  1985. * @private
  1986. * @function
  1987. * @param {Event} event
  1988. */
  1989. function openReply(event)
  1990. {
  1991. var $source = $(event.target);
  1992. // clear input
  1993. $replyMessage.val('');
  1994. $replyNickname.val('');
  1995. // get comment id from source element
  1996. replyCommentId = $source.parent().prop('id').split('_')[1];
  1997. // move to correct position
  1998. $source.after($reply);
  1999. // show
  2000. $reply.removeClass('hidden');
  2001. $replyMessage.focus();
  2002. event.preventDefault();
  2003. }
  2004. /**
  2005. * custom handler for displaying notifications in own status message area
  2006. *
  2007. * @name DiscussionViewer.handleNotification
  2008. * @function
  2009. * @param {string} alertType
  2010. * @param {jQuery} $element
  2011. * @param {string|array} args
  2012. * @param {string|null} icon
  2013. * @return {bool|jQuery}
  2014. */
  2015. me.handleNotification = function(alertType, $element, args, icon)
  2016. {
  2017. // ignore loading messages
  2018. if (alertType === 'loading') {
  2019. return false;
  2020. }
  2021. if (alertType === 'danger') {
  2022. $replyStatus.removeClass('alert-info');
  2023. $replyStatus.addClass('alert-danger');
  2024. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2025. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2026. } else {
  2027. $replyStatus.removeClass('alert-danger');
  2028. $replyStatus.addClass('alert-info');
  2029. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2030. $replyStatus.find(':first').addClass('glyphicon-alert');
  2031. }
  2032. return $replyStatus;
  2033. }
  2034. /**
  2035. * adds another comment
  2036. *
  2037. * @name DiscussionViewer.addComment
  2038. * @function
  2039. * @param {object} comment
  2040. * @param {string} commentText
  2041. * @param {jQuery} $place - optional, tries to find the best position otherwise
  2042. */
  2043. me.addComment = function(comment, commentText, nickname, $place)
  2044. {
  2045. if (typeof $place === 'undefined') {
  2046. // starting point (default value/fallback)
  2047. $place = $commentContainer;
  2048. // if parent comment exists
  2049. var $parentComment = $('#comment_' + comment.parentid);
  2050. if ($parentComment.length) {
  2051. // use parent as position for noew comment, so it shifted
  2052. // to the right
  2053. $place = $parentComment;
  2054. }
  2055. }
  2056. if (commentText === '') {
  2057. commentText = 'comment decryption failed';
  2058. }
  2059. // create new comment based on template
  2060. var $commentEntry = Model.getTemplate('comment');
  2061. $commentEntry.prop('id', 'comment_' + comment.id);
  2062. var $commentEntryData = $commentEntry.find('div.commentdata');
  2063. // set & parse text
  2064. Helper.setElementText($commentEntryData, commentText);
  2065. Helper.urls2links($commentEntryData);
  2066. // set nickname
  2067. if (nickname.length > 0) {
  2068. $commentEntry.find('span.nickname').text(nickname);
  2069. } else {
  2070. $commentEntry.find('span.nickname').html('<i></i>');
  2071. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2072. }
  2073. // set date
  2074. $commentEntry.find('span.commentdate')
  2075. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2076. .attr('title', 'CommentID: ' + comment.id);
  2077. // if an avatar is available, display it
  2078. if (comment.meta.vizhash) {
  2079. $commentEntry.find('span.nickname')
  2080. .before(
  2081. '<img src="' + comment.meta.vizhash + '" class="vizhash" /> '
  2082. );
  2083. $(document).on('languageLoaded', function () {
  2084. $commentEntry.find('img.vizhash')
  2085. .prop('title', I18n._('Avatar generated from IP address'));
  2086. });
  2087. }
  2088. // finally append comment
  2089. $place.append($commentEntry);
  2090. }
  2091. /**
  2092. * finishes the discussion area after last comment
  2093. *
  2094. * @name DiscussionViewer.finishDiscussion
  2095. * @function
  2096. */
  2097. me.finishDiscussion = function()
  2098. {
  2099. // add 'add new comment' area
  2100. $commentContainer.append($commentTail);
  2101. // show discussions
  2102. $discussion.removeClass('hidden');
  2103. }
  2104. /**
  2105. * shows the discussion area
  2106. *
  2107. * @name DiscussionViewer.showDiscussion
  2108. * @function
  2109. */
  2110. me.showDiscussion = function()
  2111. {
  2112. $discussion.removeClass('hidden');
  2113. }
  2114. /**
  2115. * removes the old discussion and prepares everything for creating a new
  2116. * one.
  2117. *
  2118. * @name DiscussionViewer.prepareNewDisucssion
  2119. * @function
  2120. */
  2121. me.prepareNewDisucssion = function()
  2122. {
  2123. $commentContainer.html('');
  2124. $discussion.addClass('hidden');
  2125. // (re-)init templates
  2126. initTemplates();
  2127. }
  2128. /**
  2129. * returns the user put into the reply form
  2130. *
  2131. * @name DiscussionViewer.getReplyData
  2132. * @function
  2133. * @return {array}
  2134. */
  2135. me.getReplyData = function()
  2136. {
  2137. return [
  2138. $replyMessage.val(),
  2139. $replyNickname.val()
  2140. ];
  2141. }
  2142. /**
  2143. * highlights a specific comment and scrolls to it if necessary
  2144. *
  2145. * @name DiscussionViewer.highlightComment
  2146. * @function
  2147. * @param {string} commentId
  2148. * @param {bool} fadeOut - whether to fade out the comment
  2149. */
  2150. me.highlightComment = function(commentId, fadeOut)
  2151. {
  2152. var $comment = $('#comment_' + commentId);
  2153. // in case comment does not exist, cancel
  2154. if ($comment.length === 0) {
  2155. return;
  2156. }
  2157. var highlightComment = function () {
  2158. $comment.addClass('highlight');
  2159. if (fadeOut === true) {
  2160. setTimeout(function () {
  2161. $comment.removeClass('highlight');
  2162. }, 300);
  2163. }
  2164. }
  2165. if (UiHelper.isVisible($comment)) {
  2166. return highlightComment();
  2167. }
  2168. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2169. }
  2170. /**
  2171. * returns the id of the parent comment the user is replying to
  2172. *
  2173. * @name DiscussionViewer.getReplyCommentId
  2174. * @function
  2175. * @return {int|undefined}
  2176. */
  2177. me.getReplyCommentId = function()
  2178. {
  2179. return replyCommentId;
  2180. }
  2181. /**
  2182. * initiate
  2183. *
  2184. * preloads jQuery elements
  2185. *
  2186. * @name DiscussionViewer.init
  2187. * @function
  2188. */
  2189. me.init = function()
  2190. {
  2191. // bind events to templates (so they are later cloned)
  2192. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2193. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2194. $commentContainer = $('#commentcontainer');
  2195. $discussion = $('#discussion');
  2196. }
  2197. return me;
  2198. })(window, document);
  2199. /**
  2200. * Manage top (navigation) bar
  2201. *
  2202. * @name TopNav
  2203. * @param {object} window
  2204. * @param {object} document
  2205. * @class
  2206. */
  2207. var TopNav = (function (window, document) {
  2208. var me = {};
  2209. var createButtonsDisplayed = false;
  2210. var viewButtonsDisplayed = false;
  2211. var $attach,
  2212. $burnAfterReading,
  2213. $burnAfterReadingOption,
  2214. $cloneButton,
  2215. $customAttachment,
  2216. $expiration,
  2217. $fileRemoveButton,
  2218. $fileWrap,
  2219. $formatter,
  2220. $newButton,
  2221. $openDiscussion,
  2222. $openDiscussionOption,
  2223. $password,
  2224. $passwordInput,
  2225. $rawTextButton,
  2226. $sendButton;
  2227. var pasteExpiration = '1week';
  2228. /**
  2229. * set the expiration on bootstrap templates in dropdown
  2230. *
  2231. * @name TopNav.updateExpiration
  2232. * @private
  2233. * @function
  2234. * @param {Event} event
  2235. */
  2236. function updateExpiration(event)
  2237. {
  2238. // get selected option
  2239. var target = $(event.target);
  2240. // update dropdown display and save new expiration time
  2241. $('#pasteExpirationDisplay').text(target.text());
  2242. pasteExpiration = target.data('expiration');
  2243. event.preventDefault();
  2244. }
  2245. /**
  2246. * set the format on bootstrap templates in dropdown
  2247. *
  2248. * @name TopNav.updateFormat
  2249. * @private
  2250. * @function
  2251. * @param {Event} event
  2252. */
  2253. function updateFormat(event)
  2254. {
  2255. // get selected option
  2256. var $target = $(event.target);
  2257. // update dropdown display and save new format
  2258. var newFormat = $target.data('format');
  2259. $('#pasteFormatterDisplay').text($target.text());
  2260. PasteViewer.setFormat(newFormat);
  2261. // update preview
  2262. if (Editor.isPreview()) {
  2263. PasteViewer.run();
  2264. }
  2265. event.preventDefault();
  2266. }
  2267. /**
  2268. * when "burn after reading" is checked, disable discussion
  2269. *
  2270. * @name TopNav.changeBurnAfterReading
  2271. * @private
  2272. * @function
  2273. */
  2274. function changeBurnAfterReading()
  2275. {
  2276. if ($burnAfterReading.is(':checked')) {
  2277. $openDiscussionOption.addClass('buttondisabled');
  2278. $openDiscussion.prop('checked', false);
  2279. // if button is actually disabled, force-enable it and uncheck other button
  2280. $burnAfterReadingOption.removeClass('buttondisabled');
  2281. } else {
  2282. $openDiscussionOption.removeClass('buttondisabled');
  2283. }
  2284. }
  2285. /**
  2286. * when discussion is checked, disable "burn after reading"
  2287. *
  2288. * @name TopNav.changeOpenDiscussion
  2289. * @private
  2290. * @function
  2291. */
  2292. function changeOpenDiscussion()
  2293. {
  2294. if ($openDiscussion.is(':checked')) {
  2295. $burnAfterReadingOption.addClass('buttondisabled');
  2296. $burnAfterReading.prop('checked', false);
  2297. // if button is actually disabled, force-enable it and uncheck other button
  2298. $openDiscussionOption.removeClass('buttondisabled');
  2299. } else {
  2300. $burnAfterReadingOption.removeClass('buttondisabled');
  2301. }
  2302. }
  2303. /**
  2304. * return raw text
  2305. *
  2306. * @name TopNav.rawText
  2307. * @private
  2308. * @function
  2309. * @param {Event} event
  2310. */
  2311. function rawText(event)
  2312. {
  2313. TopNav.hideAllButtons();
  2314. Alert.showLoading('Showing raw text…', 0, 'time');
  2315. var paste = PasteViewer.getText();
  2316. // push a new state to allow back navigation with browser back button
  2317. history.pushState(
  2318. {type: 'raw'},
  2319. document.title,
  2320. // recreate paste URL
  2321. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  2322. Model.getPasteKey()
  2323. );
  2324. // we use text/html instead of text/plain to avoid a bug when
  2325. // reloading the raw text view (it reverts to type text/html)
  2326. var $head = $('head').children().not('noscript, script, link[type="text/css"]');
  2327. var newDoc = document.open('text/html', 'replace');
  2328. newDoc.write('<!DOCTYPE html><html><head>');
  2329. for (var i = 0; i < $head.length; i++) {
  2330. newDoc.write($head[i].outerHTML);
  2331. }
  2332. newDoc.write('</head><body><pre>' + Helper.htmlEntities(paste) + '</pre></body></html>');
  2333. newDoc.close();
  2334. }
  2335. /**
  2336. * saves the language in a cookie and reloads the page
  2337. *
  2338. * @name TopNav.setLanguage
  2339. * @private
  2340. * @function
  2341. * @param {Event} event
  2342. */
  2343. function setLanguage(event)
  2344. {
  2345. document.cookie = 'lang=' + $(event.target).data('lang');
  2346. UiHelper.reloadHome();
  2347. }
  2348. /**
  2349. * hides all messages and creates a new paste
  2350. *
  2351. * @name TopNav.clickNewPaste
  2352. * @private
  2353. * @function
  2354. * @param {Event} event
  2355. */
  2356. function clickNewPaste(event)
  2357. {
  2358. Controller.hideStatusMessages();
  2359. Controller.newPaste();
  2360. }
  2361. /**
  2362. * removes the existing attachment
  2363. *
  2364. * @name TopNav.removeAttachment
  2365. * @private
  2366. * @function
  2367. * @param {Event} event
  2368. */
  2369. function removeAttachment(event)
  2370. {
  2371. // if custom attachment is used, remove it first
  2372. if (!$customAttachment.hasClass('hidden')) {
  2373. AttachmentViewer.removeAttachment();
  2374. $customAttachment.addClass('hidden');
  2375. $fileWrap.removeClass('hidden');
  2376. }
  2377. // our up-to-date jQuery can handle it :)
  2378. $fileWrap.find('input').val('');
  2379. // pevent '#' from appearing in the URL
  2380. event.preventDefault();
  2381. }
  2382. /**
  2383. * Shows all elements belonging to viwing an existing pastes
  2384. *
  2385. * @name TopNav.showViewButtons
  2386. * @function
  2387. */
  2388. me.showViewButtons = function()
  2389. {
  2390. if (viewButtonsDisplayed) {
  2391. console.warn('showViewButtons: view buttons are already displayed');
  2392. return;
  2393. }
  2394. $newButton.removeClass('hidden');
  2395. $cloneButton.removeClass('hidden');
  2396. $rawTextButton.removeClass('hidden');
  2397. viewButtonsDisplayed = true;
  2398. }
  2399. /**
  2400. * Hides all elements belonging to existing pastes
  2401. *
  2402. * @name TopNav.hideViewButtons
  2403. * @function
  2404. */
  2405. me.hideViewButtons = function()
  2406. {
  2407. if (!viewButtonsDisplayed) {
  2408. console.warn('hideViewButtons: view buttons are already hidden');
  2409. return;
  2410. }
  2411. $newButton.addClass('hidden');
  2412. $cloneButton.addClass('hidden');
  2413. $rawTextButton.addClass('hidden');
  2414. viewButtonsDisplayed = false;
  2415. }
  2416. /**
  2417. * Hides all elements belonging to existing pastes
  2418. *
  2419. * @name TopNav.hideAllButtons
  2420. * @function
  2421. */
  2422. me.hideAllButtons = function()
  2423. {
  2424. me.hideViewButtons();
  2425. me.hideCreateButtons();
  2426. }
  2427. /**
  2428. * shows all elements needed when creating a new paste
  2429. *
  2430. * @name TopNav.showCreateButtons
  2431. * @function
  2432. */
  2433. me.showCreateButtons = function()
  2434. {
  2435. if (createButtonsDisplayed) {
  2436. console.warn('showCreateButtons: create buttons are already displayed');
  2437. return;
  2438. }
  2439. $sendButton.removeClass('hidden');
  2440. $expiration.removeClass('hidden');
  2441. $formatter.removeClass('hidden');
  2442. $burnAfterReadingOption.removeClass('hidden');
  2443. $openDiscussionOption.removeClass('hidden');
  2444. $newButton.removeClass('hidden');
  2445. $password.removeClass('hidden');
  2446. $attach.removeClass('hidden');
  2447. createButtonsDisplayed = true;
  2448. }
  2449. /**
  2450. * shows all elements needed when creating a new paste
  2451. *
  2452. * @name TopNav.hideCreateButtons
  2453. * @function
  2454. */
  2455. me.hideCreateButtons = function()
  2456. {
  2457. if (!createButtonsDisplayed) {
  2458. console.warn('hideCreateButtons: create buttons are already hidden');
  2459. return;
  2460. }
  2461. $newButton.addClass('hidden');
  2462. $sendButton.addClass('hidden');
  2463. $expiration.addClass('hidden');
  2464. $formatter.addClass('hidden');
  2465. $burnAfterReadingOption.addClass('hidden');
  2466. $openDiscussionOption.addClass('hidden');
  2467. $password.addClass('hidden');
  2468. $attach.addClass('hidden');
  2469. createButtonsDisplayed = false;
  2470. }
  2471. /**
  2472. * only shows the "new paste" button
  2473. *
  2474. * @name TopNav.showNewPasteButton
  2475. * @function
  2476. */
  2477. me.showNewPasteButton = function()
  2478. {
  2479. $newButton.removeClass('hidden');
  2480. }
  2481. /**
  2482. * only hides the clone button
  2483. *
  2484. * @name TopNav.hideCloneButton
  2485. * @function
  2486. */
  2487. me.hideCloneButton = function()
  2488. {
  2489. $cloneButton.addClass('hidden');
  2490. }
  2491. /**
  2492. * only hides the raw text button
  2493. *
  2494. * @name TopNav.hideRawButton
  2495. * @function
  2496. */
  2497. me.hideRawButton = function()
  2498. {
  2499. $rawTextButton.addClass('hidden');
  2500. }
  2501. /**
  2502. * hides the file selector in attachment
  2503. *
  2504. * @name TopNav.hideFileSelector
  2505. * @function
  2506. */
  2507. me.hideFileSelector = function()
  2508. {
  2509. $fileWrap.addClass('hidden');
  2510. }
  2511. /**
  2512. * shows the custom attachment
  2513. *
  2514. * @name TopNav.showCustomAttachment
  2515. * @function
  2516. */
  2517. me.showCustomAttachment = function()
  2518. {
  2519. $customAttachment.removeClass('hidden');
  2520. }
  2521. /**
  2522. * collapses the navigation bar if nedded
  2523. *
  2524. * @name TopNav.collapseBar
  2525. * @function
  2526. */
  2527. me.collapseBar = function()
  2528. {
  2529. var $bar = $('.navbar-toggle');
  2530. // check if bar is expanded
  2531. if ($bar.hasClass('collapse in')) {
  2532. // if so, toggle it
  2533. $bar.click();
  2534. }
  2535. }
  2536. /**
  2537. * returns the currently set expiration time
  2538. *
  2539. * @name TopNav.getExpiration
  2540. * @function
  2541. * @return {int}
  2542. */
  2543. me.getExpiration = function()
  2544. {
  2545. return pasteExpiration;
  2546. }
  2547. /**
  2548. * returns the currently selected file(s)
  2549. *
  2550. * @name TopNav.getFileList
  2551. * @function
  2552. * @return {FileList|null}
  2553. */
  2554. me.getFileList = function()
  2555. {
  2556. var $file = $('#file');
  2557. // if no file given, return null
  2558. if (!$file.length || !$file[0].files.length) {
  2559. return null;
  2560. }
  2561. // @TODO is this really necessary
  2562. if (!($file[0].files && $file[0].files[0])) {
  2563. return null;
  2564. }
  2565. return $file[0].files;
  2566. }
  2567. /**
  2568. * returns the state of the burn after reading checkbox
  2569. *
  2570. * @name TopNav.getExpiration
  2571. * @function
  2572. * @return {bool}
  2573. */
  2574. me.getBurnAfterReading = function()
  2575. {
  2576. return $burnAfterReading.is(':checked');
  2577. }
  2578. /**
  2579. * returns the state of the discussion checkbox
  2580. *
  2581. * @name TopNav.getOpenDiscussion
  2582. * @function
  2583. * @return {bool}
  2584. */
  2585. me.getOpenDiscussion = function()
  2586. {
  2587. return $openDiscussion.is(':checked');
  2588. }
  2589. /**
  2590. * returns the entered password
  2591. *
  2592. * @name TopNav.getPassword
  2593. * @function
  2594. * @return {string}
  2595. */
  2596. me.getPassword = function()
  2597. {
  2598. return $passwordInput.val();
  2599. }
  2600. /**
  2601. * returns the element where custom attachments can be placed
  2602. *
  2603. * Used by AttachmentViewer when an attachment is cloned here.
  2604. *
  2605. * @name TopNav.getCustomAttachment
  2606. * @function
  2607. * @return {jQuery}
  2608. */
  2609. me.getCustomAttachment = function()
  2610. {
  2611. return $customAttachment;
  2612. }
  2613. /**
  2614. * init navigation manager
  2615. *
  2616. * preloads jQuery elements
  2617. *
  2618. * @name TopNav.init
  2619. * @function
  2620. */
  2621. me.init = function()
  2622. {
  2623. $attach = $('#attach');
  2624. $burnAfterReading = $('#burnafterreading');
  2625. $burnAfterReadingOption = $('#burnafterreadingoption');
  2626. $cloneButton = $('#clonebutton');
  2627. $customAttachment = $('#customattachment');
  2628. $expiration = $('#expiration');
  2629. $fileRemoveButton = $('#fileremovebutton');
  2630. $fileWrap = $('#filewrap');
  2631. $formatter = $('#formatter');
  2632. $newButton = $('#newbutton');
  2633. $openDiscussion = $('#opendiscussion');
  2634. $openDiscussionOption = $('#opendiscussionoption');
  2635. $password = $('#password');
  2636. $passwordInput = $('#passwordinput');
  2637. $rawTextButton = $('#rawtextbutton');
  2638. $sendButton = $('#sendbutton');
  2639. // bootstrap template drop down
  2640. $('#language ul.dropdown-menu li a').click(setLanguage);
  2641. // page template drop down
  2642. $('#language select option').click(setLanguage);
  2643. // bind events
  2644. $burnAfterReading.change(changeBurnAfterReading);
  2645. $openDiscussionOption.change(changeOpenDiscussion);
  2646. $newButton.click(clickNewPaste);
  2647. $sendButton.click(PasteEncrypter.sendPaste);
  2648. $cloneButton.click(Controller.clonePaste);
  2649. $rawTextButton.click(rawText);
  2650. $fileRemoveButton.click(removeAttachment);
  2651. // bootstrap template drop downs
  2652. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2653. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2654. // initiate default state of checkboxes
  2655. changeBurnAfterReading();
  2656. changeOpenDiscussion();
  2657. // get default value from template or fall back to set value
  2658. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2659. }
  2660. return me;
  2661. })(window, document);
  2662. /**
  2663. * Responsible for AJAX requests, transparently handles encryption…
  2664. *
  2665. * @name Uploader
  2666. * @class
  2667. */
  2668. var Uploader = (function () {
  2669. var me = {};
  2670. var successFunc = null,
  2671. failureFunc = null,
  2672. url,
  2673. data,
  2674. symmetricKey,
  2675. password;
  2676. /**
  2677. * public variable ('constant') for errors to prevent magic numbers
  2678. *
  2679. * @name Uploader.error
  2680. * @readonly
  2681. * @enum {Object}
  2682. */
  2683. me.error = {
  2684. okay: 0,
  2685. custom: 1,
  2686. unknown: 2,
  2687. serverError: 3
  2688. };
  2689. /**
  2690. * ajaxHeaders to send in AJAX requests
  2691. *
  2692. * @name Uploader.ajaxHeaders
  2693. * @private
  2694. * @readonly
  2695. * @enum {Object}
  2696. */
  2697. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  2698. /**
  2699. * called after successful upload
  2700. *
  2701. * @name Uploader.checkCryptParameters
  2702. * @private
  2703. * @function
  2704. * @throws {string}
  2705. */
  2706. function checkCryptParameters()
  2707. {
  2708. // workaround for this nasty 'bug' in ECMAScript
  2709. // see https://stackoverflow.com/questions/18808226/why-is-typeof-null-object
  2710. var typeOfKey = typeof symmetricKey;
  2711. if (symmetricKey === null) {
  2712. typeOfKey = 'null';
  2713. }
  2714. // in case of missing preparation, throw error
  2715. switch (typeOfKey) {
  2716. case 'string':
  2717. // already set, all right
  2718. return;
  2719. case 'null':
  2720. // needs to be generated auto-generate
  2721. symmetricKey = CryptTool.getSymmetricKey();
  2722. break;
  2723. default:
  2724. console.error('current invalid symmetricKey:', symmetricKey);
  2725. throw 'symmetricKey is invalid, probably the module was not prepared';
  2726. }
  2727. // password is optional
  2728. }
  2729. /**
  2730. * called after successful upload
  2731. *
  2732. * @name Uploader.success
  2733. * @private
  2734. * @function
  2735. * @param {int} status
  2736. * @param {int} result - optional
  2737. */
  2738. function success(status, result)
  2739. {
  2740. // add useful data to result
  2741. result.encryptionKey = symmetricKey;
  2742. result.requestData = data;
  2743. if (successFunc !== null) {
  2744. successFunc(status, result);
  2745. }
  2746. }
  2747. /**
  2748. * called after a upload failure
  2749. *
  2750. * @name Uploader.fail
  2751. * @private
  2752. * @function
  2753. * @param {int} status - internal code
  2754. * @param {int} result - original error code
  2755. */
  2756. function fail(status, result)
  2757. {
  2758. if (failureFunc !== null) {
  2759. failureFunc(status, result);
  2760. }
  2761. }
  2762. /**
  2763. * actually uploads the data
  2764. *
  2765. * @name Uploader.run
  2766. * @function
  2767. */
  2768. me.run = function()
  2769. {
  2770. $.ajax({
  2771. type: 'POST',
  2772. url: url,
  2773. data: data,
  2774. dataType: 'json',
  2775. headers: ajaxHeaders,
  2776. success: function(result) {
  2777. if (result.status === 0) {
  2778. success(0, result);
  2779. } else if (result.status === 1) {
  2780. fail(1, result);
  2781. } else {
  2782. fail(2, result);
  2783. }
  2784. }
  2785. })
  2786. .fail(function(jqXHR, textStatus, errorThrown) {
  2787. console.error(textStatus, errorThrown);
  2788. fail(3, jqXHR);
  2789. });
  2790. }
  2791. /**
  2792. * set success function
  2793. *
  2794. * @name Uploader.setUrl
  2795. * @function
  2796. * @param {function} newUrl
  2797. */
  2798. me.setUrl = function(newUrl)
  2799. {
  2800. url = newUrl;
  2801. }
  2802. /**
  2803. * sets the password to use (first value) and optionally also the
  2804. * encryption key (not recommend, it is automatically generated).
  2805. *
  2806. * Note: Call this after prepare() as prepare() resets these values.
  2807. *
  2808. * @name Uploader.setCryptValues
  2809. * @function
  2810. * @param {string} newPassword
  2811. * @param {string} newKey - optional
  2812. */
  2813. me.setCryptParameters = function(newPassword, newKey)
  2814. {
  2815. password = newPassword;
  2816. if (typeof newKey !== 'undefined') {
  2817. symmetricKey = newKey;
  2818. }
  2819. }
  2820. /**
  2821. * set success function
  2822. *
  2823. * @name Uploader.setSuccess
  2824. * @function
  2825. * @param {function} func
  2826. */
  2827. me.setSuccess = function(func)
  2828. {
  2829. successFunc = func;
  2830. }
  2831. /**
  2832. * set failure function
  2833. *
  2834. * @name Uploader.setFailure
  2835. * @function
  2836. * @param {function} func
  2837. */
  2838. me.setFailure = function(func)
  2839. {
  2840. failureFunc = func;
  2841. }
  2842. /**
  2843. * prepares a new upload
  2844. *
  2845. * Call this when doing a new upload to reset any data from potential
  2846. * previous uploads. Must be called before any other method of this
  2847. * module.
  2848. *
  2849. * @name Uploader.prepare
  2850. * @function
  2851. * @return {object}
  2852. */
  2853. me.prepare = function()
  2854. {
  2855. // entropy should already be checked!
  2856. // reset password
  2857. password = '';
  2858. // reset key, so it a new one is generated when it is used
  2859. symmetricKey = null;
  2860. // reset data
  2861. successFunc = null;
  2862. failureFunc = null;
  2863. url = Helper.baseUri();
  2864. data = {};
  2865. }
  2866. /**
  2867. * encrypts and sets the data
  2868. *
  2869. * @name Uploader.setData
  2870. * @function
  2871. * @param {string} index
  2872. * @param {mixed} element
  2873. */
  2874. me.setData = function(index, element)
  2875. {
  2876. checkCryptParameters();
  2877. data[index] = CryptTool.cipher(symmetricKey, password, element);
  2878. }
  2879. /**
  2880. * set the additional metadata to send unencrypted
  2881. *
  2882. * @name Uploader.setUnencryptedData
  2883. * @function
  2884. * @param {string} index
  2885. * @param {mixed} element
  2886. */
  2887. me.setUnencryptedData = function(index, element)
  2888. {
  2889. data[index] = element;
  2890. }
  2891. /**
  2892. * set the additional metadata to send unencrypted passed at once
  2893. *
  2894. * @name Uploader.setUnencryptedData
  2895. * @function
  2896. * @param {object} newData
  2897. */
  2898. me.setUnencryptedBulkData = function(newData)
  2899. {
  2900. $.extend(data, newData);
  2901. }
  2902. /**
  2903. * Helper, which parses shows a general error message based on the result of the Uploader
  2904. *
  2905. * @name Uploader.parseUploadError
  2906. * @function
  2907. * @param {int} status
  2908. * @param {object} data
  2909. * @param {string} doThisThing - a human description of the action, which was tried
  2910. * @return {array}
  2911. */
  2912. me.parseUploadError = function(status, data, doThisThing) {
  2913. var errorArray;
  2914. switch (status) {
  2915. case me.error['custom']:
  2916. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  2917. break;
  2918. case me.error['unknown']:
  2919. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  2920. break;
  2921. case me.error['serverError']:
  2922. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  2923. break;
  2924. default:
  2925. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  2926. break;
  2927. }
  2928. return errorArray;
  2929. }
  2930. /**
  2931. * init Uploader
  2932. *
  2933. * @name Uploader.init
  2934. * @function
  2935. */
  2936. me.init = function()
  2937. {
  2938. // nothing yet
  2939. }
  2940. return me;
  2941. })();
  2942. /**
  2943. * (controller) Responsible for encrypting paste and sending it to server.
  2944. *
  2945. * Does upload, encryption is done transparently by Uploader.
  2946. *
  2947. * @name PasteEncrypter
  2948. * @class
  2949. */
  2950. var PasteEncrypter = (function () {
  2951. var me = {};
  2952. var requirementsChecked = false;
  2953. /**
  2954. * checks whether there is a suitable amount of entrophy
  2955. *
  2956. * @name PasteEncrypter.checkRequirements
  2957. * @private
  2958. * @function
  2959. * @param {function} retryCallback - the callback to execute to retry the upload
  2960. * @return {bool}
  2961. */
  2962. function checkRequirements(retryCallback) {
  2963. // skip double requirement checks
  2964. if (requirementsChecked === true) {
  2965. return true;
  2966. }
  2967. if (!CryptTool.isEntropyReady()) {
  2968. // display a message and wait
  2969. Alert.showStatus('Please move your mouse for more entropy…');
  2970. CryptTool.addEntropySeedListener(retryCallback);
  2971. return false;
  2972. }
  2973. requirementsChecked = true;
  2974. return true;
  2975. }
  2976. /**
  2977. * called after successful paste upload
  2978. *
  2979. * @name PasteEncrypter.showCreatedPaste
  2980. * @private
  2981. * @function
  2982. * @param {int} status
  2983. * @param {object} data
  2984. */
  2985. function showCreatedPaste(status, data) {
  2986. Alert.hideLoading();
  2987. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  2988. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  2989. Alert.hideMessages();
  2990. // show notification
  2991. PasteStatus.createPasteNotification(url, deleteUrl)
  2992. // show new URL in browser bar
  2993. history.pushState({type: 'newpaste'}, document.title, url);
  2994. TopNav.showViewButtons();
  2995. TopNav.hideRawButton();
  2996. Editor.hide();
  2997. // parse and show text
  2998. // (preparation already done in me.sendPaste())
  2999. PasteViewer.run();
  3000. }
  3001. /**
  3002. * called after successful comment upload
  3003. *
  3004. * @name PasteEncrypter.showUploadedComment
  3005. * @private
  3006. * @function
  3007. * @param {int} status
  3008. * @param {object} data
  3009. */
  3010. function showUploadedComment(status, data) {
  3011. // show success message
  3012. // Alert.showStatus('Comment posted.');
  3013. // reload paste
  3014. Controller.refreshPaste(function () {
  3015. // highlight sent comment
  3016. DiscussionViewer.highlightComment(data.id, true);
  3017. // reset error handler
  3018. Alert.setCustomHandler(null);
  3019. });
  3020. }
  3021. /**
  3022. * adds attachments to the Uploader
  3023. *
  3024. * @name PasteEncrypter.encryptAttachments
  3025. * @private
  3026. * @function
  3027. * @param {File|null|undefined} file - optional, falls back to cloned attachment
  3028. * @param {function} callback - excuted when action is successful
  3029. */
  3030. function encryptAttachments(file, callback) {
  3031. if (typeof file !== 'undefined' && file !== null) {
  3032. // check file reader requirements for upload
  3033. if (typeof FileReader === 'undefined') {
  3034. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  3035. // cancels process as it does not execute callback
  3036. return;
  3037. }
  3038. var reader = new FileReader();
  3039. // closure to capture the file information
  3040. reader.onload = function(event) {
  3041. Uploader.setData('attachment', event.target.result);
  3042. Uploader.setData('attachmentname', file.name);
  3043. // run callback
  3044. return callback();
  3045. }
  3046. // actually read first file
  3047. reader.readAsDataURL(file);
  3048. } else if (AttachmentViewer.hasAttachment()) {
  3049. // fall back to cloned part
  3050. var attachment = AttachmentViewer.getAttachment();
  3051. Uploader.setData('attachment', attachment[0]);
  3052. Uploader.setData('attachmentname', attachment[1]);
  3053. return callback();
  3054. } else {
  3055. // if there are no attachments, this is of course still successful
  3056. return callback();
  3057. }
  3058. }
  3059. /**
  3060. * send a reply in a discussion
  3061. *
  3062. * @name PasteEncrypter.sendComment
  3063. * @function
  3064. */
  3065. me.sendComment = function()
  3066. {
  3067. Alert.hideMessages();
  3068. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3069. // UI loading state
  3070. TopNav.hideAllButtons();
  3071. Alert.showLoading('Sending comment…', 0, 'cloud-upload');
  3072. // get data, note that "var [x, y] = " structures aren't supported in all JS environments
  3073. var replyData = DiscussionViewer.getReplyData(),
  3074. plainText = replyData[0],
  3075. nickname = replyData[1],
  3076. parentid = DiscussionViewer.getReplyCommentId();
  3077. // do not send if there is no data
  3078. if (plainText.length === 0) {
  3079. // revert loading status…
  3080. Alert.hideLoading();
  3081. Alert.setCustomHandler(null);
  3082. TopNav.showViewButtons();
  3083. return;
  3084. }
  3085. // check entropy
  3086. if (!checkRequirements(function () {
  3087. me.sendComment();
  3088. })) {
  3089. return; // to prevent multiple executions
  3090. }
  3091. Alert.showLoading(null, 10);
  3092. // prepare Uploader
  3093. Uploader.prepare();
  3094. Uploader.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3095. // set success/fail functions
  3096. Uploader.setSuccess(showUploadedComment);
  3097. Uploader.setFailure(function (status, data) {
  3098. // revert loading status…
  3099. Alert.hideLoading();
  3100. TopNav.showViewButtons();
  3101. // show error message
  3102. Alert.showError(Uploader.parseUploadError(status, data, 'post comment'));
  3103. // reset error handler
  3104. Alert.setCustomHandler(null);
  3105. });
  3106. // fill it with unencrypted params
  3107. Uploader.setUnencryptedData('pasteid', Model.getPasteId());
  3108. if (typeof parentid === 'undefined') {
  3109. // if parent id is not set, this is the top-most comment, so use
  3110. // paste id as parent @TODO is this really good?
  3111. Uploader.setUnencryptedData('parentid', Model.getPasteId());
  3112. } else {
  3113. Uploader.setUnencryptedData('parentid', parentid);
  3114. }
  3115. // encrypt data
  3116. Uploader.setData('data', plainText);
  3117. if (nickname.length > 0) {
  3118. Uploader.setData('nickname', nickname);
  3119. }
  3120. Uploader.run();
  3121. }
  3122. /**
  3123. * sends a new paste to server
  3124. *
  3125. * @name PasteEncrypter.sendPaste
  3126. * @function
  3127. */
  3128. me.sendPaste = function()
  3129. {
  3130. // hide previous (error) messages
  3131. Controller.hideStatusMessages();
  3132. // UI loading state
  3133. TopNav.hideAllButtons();
  3134. Alert.showLoading('Sending paste…', 0, 'cloud-upload');
  3135. TopNav.collapseBar();
  3136. // get data
  3137. var plainText = Editor.getText(),
  3138. format = PasteViewer.getFormat(),
  3139. files = TopNav.getFileList();
  3140. // do not send if there is no data
  3141. if (plainText.length === 0 && files === null) {
  3142. // revert loading status…
  3143. Alert.hideLoading();
  3144. TopNav.showCreateButtons();
  3145. return;
  3146. }
  3147. Alert.showLoading(null, 10);
  3148. // check entropy
  3149. if (!checkRequirements(function () {
  3150. me.sendPaste();
  3151. })) {
  3152. return; // to prevent multiple executions
  3153. }
  3154. // prepare Uploader
  3155. Uploader.prepare();
  3156. Uploader.setCryptParameters(TopNav.getPassword());
  3157. // set success/fail functions
  3158. Uploader.setSuccess(showCreatedPaste);
  3159. Uploader.setFailure(function (status, data) {
  3160. // revert loading status…
  3161. Alert.hideLoading();
  3162. TopNav.showCreateButtons();
  3163. // show error message
  3164. Alert.showError(Uploader.parseUploadError(status, data, 'create paste'));
  3165. });
  3166. // fill it with unencrypted submitted options
  3167. Uploader.setUnencryptedBulkData({
  3168. expire: TopNav.getExpiration(),
  3169. formatter: format,
  3170. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  3171. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  3172. });
  3173. // prepare PasteViewer for later preview
  3174. PasteViewer.setText(plainText);
  3175. PasteViewer.setFormat(format);
  3176. // encrypt cipher data
  3177. Uploader.setData('data', plainText);
  3178. // encrypt attachments
  3179. encryptAttachments(
  3180. files === null ? null : files[0],
  3181. function () {
  3182. // send data
  3183. Uploader.run();
  3184. }
  3185. );
  3186. }
  3187. /**
  3188. * initialize
  3189. *
  3190. * @name PasteEncrypter.init
  3191. * @function
  3192. */
  3193. me.init = function()
  3194. {
  3195. // nothing yet
  3196. }
  3197. return me;
  3198. })();
  3199. /**
  3200. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3201. *
  3202. * Only decryption, no download.
  3203. *
  3204. * @name PasteDecrypter
  3205. * @class
  3206. */
  3207. var PasteDecrypter = (function () {
  3208. var me = {};
  3209. /**
  3210. * decrypt data or prompts for password in cvase of failure
  3211. *
  3212. * @name PasteDecrypter.decryptOrPromptPassword
  3213. * @private
  3214. * @function
  3215. * @param {string} key
  3216. * @param {string} password - optional, may be an empty string
  3217. * @param {string} cipherdata
  3218. * @throws {string}
  3219. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3220. */
  3221. function decryptOrPromptPassword(key, password, cipherdata)
  3222. {
  3223. // try decryption without password
  3224. var plaindata = CryptTool.decipher(key, password, cipherdata);
  3225. // if it fails, request password
  3226. if (plaindata.length === 0 && password.length === 0) {
  3227. // try to get cached password first
  3228. password = Prompt.getPassword();
  3229. // if password is there, re-try
  3230. if (password.length === 0) {
  3231. password = Prompt.requestPassword();
  3232. }
  3233. // recursive
  3234. // note: an infinite loop is prevented as the previous if
  3235. // clause checks whether a password is already set and ignores
  3236. // errors when a password has been passed
  3237. return decryptOrPromptPassword.apply(key, password, cipherdata);
  3238. }
  3239. // if all tries failed, we can only return an error
  3240. if (plaindata.length === 0) {
  3241. throw 'failed to decipher data';
  3242. }
  3243. return plaindata;
  3244. }
  3245. /**
  3246. * decrypt the actual paste text
  3247. *
  3248. * @name PasteDecrypter.decryptOrPromptPassword
  3249. * @private
  3250. * @function
  3251. * @param {object} paste - paste data in object form
  3252. * @param {string} key
  3253. * @param {string} password
  3254. * @param {bool} ignoreError - ignore decryption errors iof set to true
  3255. * @return {bool} whether action was successful
  3256. * @throws {string}
  3257. */
  3258. function decryptPaste(paste, key, password, ignoreError)
  3259. {
  3260. var plaintext
  3261. if (ignoreError === true) {
  3262. plaintext = CryptTool.decipher(key, password, paste.data);
  3263. } else {
  3264. try {
  3265. plaintext = decryptOrPromptPassword(key, password, paste.data);
  3266. } catch (err) {
  3267. throw 'failed to decipher paste text: ' + err
  3268. }
  3269. if (plaintext === false) {
  3270. return false;
  3271. }
  3272. }
  3273. // on success show paste
  3274. PasteViewer.setFormat(paste.meta.formatter);
  3275. PasteViewer.setText(plaintext);
  3276. // trigger to show the text (attachment loaded afterwards)
  3277. PasteViewer.run();
  3278. return true;
  3279. }
  3280. /**
  3281. * decrypts any attachment
  3282. *
  3283. * @name PasteDecrypter.decryptAttachment
  3284. * @private
  3285. * @function
  3286. * @param {object} paste - paste data in object form
  3287. * @param {string} key
  3288. * @param {string} password
  3289. * @return {bool} whether action was successful
  3290. * @throws {string}
  3291. */
  3292. function decryptAttachment(paste, key, password)
  3293. {
  3294. // decrypt attachment
  3295. try {
  3296. var attachment = decryptOrPromptPassword(key, password, paste.attachment);
  3297. } catch (err) {
  3298. throw 'failed to decipher attachment: ' + err
  3299. }
  3300. if (attachment === false) {
  3301. return false;
  3302. }
  3303. // decrypt attachment name
  3304. var attachmentName;
  3305. if (paste.attachmentname) {
  3306. try {
  3307. attachmentName = decryptOrPromptPassword(key, password, paste.attachmentname);
  3308. } catch (err) {
  3309. throw 'failed to decipher attachment name: ' + err
  3310. }
  3311. if (attachmentName === false) {
  3312. return false;
  3313. }
  3314. }
  3315. AttachmentViewer.setAttachment(attachment, attachmentName);
  3316. AttachmentViewer.showAttachment();
  3317. return true;
  3318. }
  3319. /**
  3320. * decrypts all comments and shows them
  3321. *
  3322. * @name PasteDecrypter.decryptComments
  3323. * @private
  3324. * @function
  3325. * @param {object} paste - paste data in object form
  3326. * @param {string} key
  3327. * @param {string} password
  3328. * @return {bool} whether action was successful
  3329. */
  3330. function decryptComments(paste, key, password)
  3331. {
  3332. // remove potentially previous discussion
  3333. DiscussionViewer.prepareNewDisucssion();
  3334. // iterate over comments
  3335. for (var i = 0; i < paste.comments.length; ++i) {
  3336. var comment = paste.comments[i];
  3337. DiscussionViewer.addComment(
  3338. comment,
  3339. CryptTool.decipher(key, password, comment.data),
  3340. CryptTool.decipher(key, password, comment.meta.nickname)
  3341. );
  3342. }
  3343. DiscussionViewer.finishDiscussion();
  3344. DiscussionViewer.showDiscussion();
  3345. return true;
  3346. }
  3347. /**
  3348. * show decrypted text in the display area, including discussion (if open)
  3349. *
  3350. * @name PasteDecrypter.run
  3351. * @function
  3352. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  3353. */
  3354. me.run = function(paste)
  3355. {
  3356. Alert.hideMessages();
  3357. Alert.showLoading('Decrypting paste…', 0, 'cloud-download'); // @TODO icon maybe rotation-lock, but needs full Glyphicons
  3358. if (typeof paste === 'undefined') {
  3359. paste = $.parseJSON(Model.getCipherData());
  3360. }
  3361. var key = Model.getPasteKey(),
  3362. password = Prompt.getPassword();
  3363. if (PasteViewer.isPrettyPrinted()) {
  3364. console.error('Too pretty! (don\'t know why this check)'); //@TODO
  3365. return;
  3366. }
  3367. // try to decrypt the paste
  3368. try {
  3369. // decrypt attachments
  3370. if (paste.attachment) {
  3371. // try to decrypt paste and if it fails (because the password is
  3372. // missing) return to let JS continue and wait for user
  3373. if (!decryptAttachment(paste, key, password)) {
  3374. return;
  3375. }
  3376. // ignore empty paste, as this is allowed when pasting attachments
  3377. decryptPaste(paste, key, password, true);
  3378. } else {
  3379. decryptPaste(paste, key, password);
  3380. }
  3381. // shows the remaining time (until) deletion
  3382. PasteStatus.showRemainingTime(paste.meta);
  3383. // if the discussion is opened on this paste, display it
  3384. if (paste.meta.opendiscussion) {
  3385. decryptComments(paste, key, password);
  3386. }
  3387. Alert.hideLoading();
  3388. TopNav.showViewButtons();
  3389. } catch(err) {
  3390. Alert.hideLoading();
  3391. // log and show error
  3392. console.error(err);
  3393. Alert.showError('Could not decrypt data (Wrong key?)');
  3394. }
  3395. }
  3396. /**
  3397. * initialize
  3398. *
  3399. * @name PasteDecrypter.init
  3400. * @function
  3401. */
  3402. me.init = function()
  3403. {
  3404. // nothing yet
  3405. }
  3406. return me;
  3407. })();
  3408. /**
  3409. * (controller) main PrivateBin logic
  3410. *
  3411. * @name Controller
  3412. * @param {object} window
  3413. * @param {object} document
  3414. * @class
  3415. */
  3416. var Controller = (function (window, document) {
  3417. var me = {};
  3418. /**
  3419. * hides all status messages no matter which module showed them
  3420. *
  3421. * @name Controller.hideStatusMessages
  3422. * @function
  3423. */
  3424. me.hideStatusMessages = function()
  3425. {
  3426. PasteStatus.hideMessages();
  3427. Alert.hideMessages();
  3428. }
  3429. /**
  3430. * creates a new paste
  3431. *
  3432. * @name Controller.newPaste
  3433. * @function
  3434. */
  3435. me.newPaste = function()
  3436. {
  3437. // Important: This *must not* run Alert.hideMessages() as previous
  3438. // errors from viewing a paste should be shown.
  3439. TopNav.hideAllButtons();
  3440. Alert.showLoading('Preparing new paste…', 0, 'time');
  3441. PasteStatus.hideMessages();
  3442. PasteViewer.hide();
  3443. Editor.resetInput();
  3444. Editor.show();
  3445. Editor.focusInput();
  3446. TopNav.showCreateButtons();
  3447. Alert.hideLoading();
  3448. }
  3449. /**
  3450. * shows the loaded paste
  3451. *
  3452. * @name Controller.showPaste
  3453. * @function
  3454. */
  3455. me.showPaste = function()
  3456. {
  3457. try {
  3458. Model.getPasteId();
  3459. Model.getPasteKey();
  3460. } catch (err) {
  3461. console.error(err);
  3462. // missing decryption key (or paste ID) in URL?
  3463. if (window.location.hash.length === 0) {
  3464. 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?)');
  3465. // @TODO adjust error message as it is less specific now, probably include thrown exception for a detailed error
  3466. return;
  3467. }
  3468. }
  3469. // show proper elements on screen
  3470. PasteDecrypter.run();
  3471. }
  3472. /**
  3473. * refreshes the loaded paste to show potential new data
  3474. *
  3475. * @name Controller.refreshPaste
  3476. * @function
  3477. * @param {function} callback
  3478. */
  3479. me.refreshPaste = function(callback)
  3480. {
  3481. // save window position to restore it later
  3482. var orgPosition = $(window).scrollTop();
  3483. Uploader.prepare();
  3484. Uploader.setUrl(Helper.baseUri() + '?' + Model.getPasteId());
  3485. Uploader.setFailure(function (status, data) {
  3486. // revert loading status…
  3487. Alert.hideLoading();
  3488. TopNav.showViewButtons();
  3489. // show error message
  3490. Alert.showError(Uploader.parseUploadError(status, data, 'refresh display'));
  3491. })
  3492. Uploader.setSuccess(function (status, data) {
  3493. PasteDecrypter.run(data);
  3494. // restore position
  3495. window.scrollTo(0, orgPosition);
  3496. callback();
  3497. })
  3498. Uploader.run();
  3499. }
  3500. /**
  3501. * clone the current paste
  3502. *
  3503. * @name Controller.clonePaste
  3504. * @function
  3505. * @param {Event} event
  3506. */
  3507. me.clonePaste = function(event)
  3508. {
  3509. TopNav.collapseBar();
  3510. TopNav.hideAllButtons();
  3511. Alert.showLoading('Cloning paste…', 0, 'transfer');
  3512. // hide messages from previous paste
  3513. me.hideStatusMessages();
  3514. // erase the id and the key in url
  3515. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3516. if (AttachmentViewer.hasAttachment()) {
  3517. AttachmentViewer.moveAttachmentTo(
  3518. TopNav.getCustomAttachment(),
  3519. 'Cloned: \'%s\''
  3520. );
  3521. TopNav.hideFileSelector();
  3522. AttachmentViewer.hideAttachment();
  3523. // NOTE: it also looks nice without removing the attachment
  3524. // but for a consistent display we remove it…
  3525. AttachmentViewer.hideAttachmentPreview();
  3526. TopNav.showCustomAttachment();
  3527. // show another status message to make the user aware that the
  3528. // file was cloned too!
  3529. Alert.showStatus(
  3530. [
  3531. 'The cloned file \'%s\' was attached to this paste.',
  3532. AttachmentViewer.getAttachment()[1]
  3533. ], 'copy', true, true);
  3534. }
  3535. Editor.setText(PasteViewer.getText())
  3536. PasteViewer.hide();
  3537. Editor.show();
  3538. Alert.hideLoading();
  3539. TopNav.showCreateButtons();
  3540. }
  3541. /**
  3542. * removes a saved paste
  3543. *
  3544. * @name Controller.removePaste
  3545. * @function
  3546. * @param {string} pasteId
  3547. * @param {string} deleteToken
  3548. */
  3549. me.removePaste = function(pasteId, deleteToken) {
  3550. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3551. // so we use a POST request
  3552. Uploader.prepare();
  3553. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3554. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3555. Uploader.setFailure(function () {
  3556. Alert.showError(I18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  3557. })
  3558. Uploader.run();
  3559. }
  3560. /**
  3561. * application start
  3562. *
  3563. * @name Controller.init
  3564. * @function
  3565. */
  3566. me.init = function()
  3567. {
  3568. // first load translations
  3569. I18n.loadTranslations();
  3570. // initialize other modules/"classes"
  3571. Alert.init();
  3572. Model.init();
  3573. AttachmentViewer.init();
  3574. DiscussionViewer.init();
  3575. Editor.init();
  3576. PasteDecrypter.init();
  3577. PasteEncrypter.init();
  3578. PasteStatus.init();
  3579. PasteViewer.init();
  3580. Prompt.init();
  3581. TopNav.init();
  3582. UiHelper.init();
  3583. Uploader.init();
  3584. // display an existing paste
  3585. if (Model.hasCipherData()) {
  3586. return me.showPaste();
  3587. }
  3588. // otherwise create a new paste
  3589. me.newPaste();
  3590. }
  3591. return me;
  3592. })(window, document);
  3593. return {
  3594. Helper: Helper,
  3595. I18n: I18n,
  3596. CryptTool: CryptTool,
  3597. Model: Model,
  3598. UiHelper: UiHelper,
  3599. Alert: Alert,
  3600. PasteStatus: PasteStatus,
  3601. Prompt: Prompt,
  3602. Editor: Editor,
  3603. PasteViewer: PasteViewer,
  3604. AttachmentViewer: AttachmentViewer,
  3605. DiscussionViewer: DiscussionViewer,
  3606. TopNav: TopNav,
  3607. Uploader: Uploader,
  3608. PasteEncrypter: PasteEncrypter,
  3609. PasteDecrypter: PasteDecrypter,
  3610. Controller: Controller
  3611. };
  3612. }(jQuery, sjcl, Base64, RawDeflate);