privatebin.js 120 KB

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