privatebin.js 121 KB

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