privatebin.js 134 KB

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