privatebin.js 121 KB

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