privatebin.js 135 KB

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