privatebin.js 121 KB

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