privatebin.js 120 KB

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