privatebin.js 129 KB

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