privatebin.js 121 KB

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