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