1
0

privatebin.js 134 KB

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