privatebin.js 120 KB

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