privatebin.js 143 KB

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