privatebin.js 140 KB

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