privatebin.js 142 KB

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