privatebin.js 133 KB

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