privatebin.js 123 KB

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