privatebin.js 120 KB

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