privatebin.js 142 KB

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