privatebin.js 141 KB

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