privatebin.js 125 KB

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