privatebin.js 134 KB

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