privatebin.js 141 KB

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