privatebin.js 141 KB

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