privatebin.js 137 KB

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