1
0

privatebin.js 120 KB

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