1
0

privatebin.js 144 KB

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