privatebin.js 120 KB

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