privatebin.js 142 KB

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