privatebin.js 127 KB

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