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.warn('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. * @class
  774. */
  775. var UiHelper = (function () {
  776. var me = {};
  777. /**
  778. * handle history (pop) state changes
  779. *
  780. * currently this does only handle redirects to the home page.
  781. *
  782. * @name UiHelper.historyChange
  783. * @private
  784. * @function
  785. * @param {Event} event
  786. */
  787. function historyChange(event)
  788. {
  789. var currentLocation = Helper.baseUri();
  790. if (event.originalEvent.state === null && // no state object passed
  791. event.target.location.href === currentLocation && // target location is home page
  792. window.location.href === currentLocation // and we are not already on the home page
  793. ) {
  794. // redirect to home page
  795. window.location.href = currentLocation;
  796. }
  797. }
  798. /**
  799. * reload the page
  800. *
  801. * This takes the user to the PrivateBin homepage.
  802. *
  803. * @name UiHelper.reloadHome
  804. * @function
  805. */
  806. me.reloadHome = function()
  807. {
  808. window.location.href = Helper.baseUri();
  809. }
  810. /**
  811. * checks whether the element is currently visible in the viewport (so
  812. * the user can actually see it)
  813. *
  814. * @see {@link https://stackoverflow.com/a/40658647}
  815. * @name UiHelper.isVisible
  816. * @function
  817. * @param {jQuery} $element The link hash to move to.
  818. */
  819. me.isVisible = function($element)
  820. {
  821. var elementTop = $element.offset().top;
  822. var viewportTop = $(window).scrollTop();
  823. var viewportBottom = viewportTop + $(window).height();
  824. return (elementTop > viewportTop && elementTop < viewportBottom);
  825. }
  826. /**
  827. * scrolls to a specific element
  828. *
  829. * @see {@link https://stackoverflow.com/questions/4198041/jquery-smooth-scroll-to-an-anchor#answer-12714767}
  830. * @name UiHelper.scrollTo
  831. * @function
  832. * @param {jQuery} $element The link hash to move to.
  833. * @param {(number|string)} animationDuration passed to jQuery .animate, when set to 0 the animation is skipped
  834. * @param {string} animationEffect passed to jQuery .animate
  835. * @param {function} finishedCallback function to call after animation finished
  836. */
  837. me.scrollTo = function($element, animationDuration, animationEffect, finishedCallback)
  838. {
  839. var $body = $('html, body'),
  840. margin = 50,
  841. callbackCalled = false;
  842. //calculate destination place
  843. var dest = 0;
  844. // if it would scroll out of the screen at the bottom only scroll it as
  845. // far as the screen can go
  846. if ($element.offset().top > $(document).height() - $(window).height()) {
  847. dest = $(document).height() - $(window).height();
  848. } else {
  849. dest = $element.offset().top - margin;
  850. }
  851. // skip animation if duration is set to 0
  852. if (animationDuration === 0) {
  853. window.scrollTo(0, dest);
  854. } else {
  855. // stop previous animation
  856. $body.stop();
  857. // scroll to destination
  858. $body.animate({
  859. scrollTop: dest
  860. }, animationDuration, animationEffect);
  861. }
  862. // as we have finished we can enable scrolling again
  863. $body.queue(function (next) {
  864. if (!callbackCalled) {
  865. // call user function if needed
  866. if (typeof finishedCallback !== 'undefined') {
  867. finishedCallback();
  868. }
  869. // prevent calling this function twice
  870. callbackCalled = true;
  871. }
  872. next();
  873. });
  874. }
  875. /**
  876. * trigger a history (pop) state change
  877. *
  878. * used to test the UiHelper.historyChange private function
  879. *
  880. * @name UiHelper.mockHistoryChange
  881. * @function
  882. * @param {string} state (optional) state to mock
  883. */
  884. me.mockHistoryChange = function(state)
  885. {
  886. if (typeof state === 'undefined') {
  887. state = null;
  888. }
  889. historyChange($.Event('popstate', {originalEvent: new PopStateEvent('popstate', {state: state}), target: window}));
  890. }
  891. /**
  892. * initialize
  893. *
  894. * @name UiHelper.init
  895. * @function
  896. */
  897. me.init = function()
  898. {
  899. // update link to home page
  900. $('.reloadlink').prop('href', Helper.baseUri());
  901. $(window).on('popstate', historyChange);
  902. }
  903. return me;
  904. })();
  905. /**
  906. * Alert/error manager
  907. *
  908. * @name Alert
  909. * @class
  910. */
  911. var Alert = (function () {
  912. var me = {};
  913. var $errorMessage,
  914. $loadingIndicator,
  915. $statusMessage,
  916. $remainingTime;
  917. var currentIcon;
  918. var alertType = [
  919. 'loading', // not in bootstrap, but using a good value here
  920. 'info', // status icon
  921. 'warning', // not used yet
  922. 'danger' // error icon
  923. ];
  924. var customHandler;
  925. /**
  926. * forwards a request to the i18n module and shows the element
  927. *
  928. * @name Alert.handleNotification
  929. * @private
  930. * @function
  931. * @param {int} id - id of notification
  932. * @param {jQuery} $element - jQuery object
  933. * @param {string|array} args
  934. * @param {string|null} icon - optional, icon
  935. */
  936. function handleNotification(id, $element, args, icon)
  937. {
  938. // basic parsing/conversion of parameters
  939. if (typeof icon === 'undefined') {
  940. icon = null;
  941. }
  942. if (typeof args === 'undefined') {
  943. args = null;
  944. } else if (typeof args === 'string') {
  945. // convert string to array if needed
  946. args = [args];
  947. }
  948. // pass to custom handler if defined
  949. if (typeof customHandler === 'function') {
  950. var handlerResult = customHandler(alertType[id], $element, args, icon);
  951. if (handlerResult === true) {
  952. // if it returs true, skip own handler
  953. return;
  954. }
  955. if (handlerResult instanceof jQuery) {
  956. // continue processing with new element
  957. $element = handlerResult;
  958. icon = null; // icons not supported in this case
  959. }
  960. }
  961. // handle icon
  962. if (icon !== null && // icon was passed
  963. icon !== currentIcon[id] // and it differs from current icon
  964. ) {
  965. var $glyphIcon = $element.find(':first');
  966. // remove (previous) icon
  967. $glyphIcon.removeClass(currentIcon[id]);
  968. // any other thing as a string (e.g. 'null') (only) removes the icon
  969. if (typeof icon === 'string') {
  970. // set new icon
  971. currentIcon[id] = 'glyphicon-' + icon;
  972. $glyphIcon.addClass(currentIcon[id]);
  973. }
  974. }
  975. // show text
  976. if (args !== null) {
  977. // add jQuery object to it as first parameter
  978. args.unshift($element);
  979. // pass it to I18n
  980. I18n._.apply(this, args);
  981. }
  982. // show notification
  983. $element.removeClass('hidden');
  984. }
  985. /**
  986. * display a status message
  987. *
  988. * This automatically passes the text to I18n for translation.
  989. *
  990. * @name Alert.showStatus
  991. * @function
  992. * @param {string|array} message string, use an array for %s/%d options
  993. * @param {string|null} icon optional, the icon to show,
  994. * default: leave previous icon
  995. * @param {bool} dismissable optional, whether the notification
  996. * can be dismissed (closed), default: false
  997. * @param {bool|int} autoclose optional, after how many seconds the
  998. * notification should be hidden automatically;
  999. * default: disabled (0); use true for default value
  1000. */
  1001. me.showStatus = function(message, icon, dismissable, autoclose)
  1002. {
  1003. console.info('status shown: ', message);
  1004. // @TODO: implement dismissable
  1005. // @TODO: implement autoclose
  1006. handleNotification(1, $statusMessage, message, icon);
  1007. }
  1008. /**
  1009. * display an error message
  1010. *
  1011. * This automatically passes the text to I18n for translation.
  1012. *
  1013. * @name Alert.showError
  1014. * @function
  1015. * @param {string|array} message string, use an array for %s/%d options
  1016. * @param {string|null} icon optional, the icon to show, default:
  1017. * leave previous icon
  1018. * @param {bool} dismissable optional, whether the notification
  1019. * can be dismissed (closed), default: false
  1020. * @param {bool|int} autoclose optional, after how many seconds the
  1021. * notification should be hidden automatically;
  1022. * default: disabled (0); use true for default value
  1023. */
  1024. me.showError = function(message, icon, dismissable, autoclose)
  1025. {
  1026. console.error('error message shown: ', message);
  1027. // @TODO: implement dismissable (bootstrap add-on has it)
  1028. // @TODO: implement autoclose
  1029. handleNotification(3, $errorMessage, message, icon);
  1030. }
  1031. /**
  1032. * display remaining message
  1033. *
  1034. * This automatically passes the text to I18n for translation.
  1035. *
  1036. * @name Alert.showRemaining
  1037. * @function
  1038. * @param {string|array} message string, use an array for %s/%d options
  1039. */
  1040. me.showRemaining = function(message)
  1041. {
  1042. console.info('remaining message shown: ', message);
  1043. handleNotification(1, $remainingTime, message);
  1044. }
  1045. /**
  1046. * shows a loading message, optionally with a percentage
  1047. *
  1048. * This automatically passes all texts to the i10s module.
  1049. *
  1050. * @name Alert.showLoading
  1051. * @function
  1052. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1053. * @param {int} percentage optional, default: null
  1054. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1055. */
  1056. me.showLoading = function(message, percentage, icon)
  1057. {
  1058. if (typeof message !== 'undefined' && message !== null) {
  1059. console.info('status changed: ', message);
  1060. }
  1061. // default message text
  1062. if (typeof message === 'undefined') {
  1063. message = 'Loading…';
  1064. }
  1065. // currently percentage parameter is ignored
  1066. // // @TODO handle it here…
  1067. handleNotification(0, $loadingIndicator, message, icon);
  1068. // show loading status (cursor)
  1069. $('body').addClass('loading');
  1070. }
  1071. /**
  1072. * hides the loading message
  1073. *
  1074. * @name Alert.hideLoading
  1075. * @function
  1076. */
  1077. me.hideLoading = function()
  1078. {
  1079. $loadingIndicator.addClass('hidden');
  1080. // hide loading cursor
  1081. $('body').removeClass('loading');
  1082. }
  1083. /**
  1084. * hides any status/error messages
  1085. *
  1086. * This does not include the loading message.
  1087. *
  1088. * @name Alert.hideMessages
  1089. * @function
  1090. */
  1091. me.hideMessages = function()
  1092. {
  1093. // also possible: $('.statusmessage').addClass('hidden');
  1094. $statusMessage.addClass('hidden');
  1095. $errorMessage.addClass('hidden');
  1096. }
  1097. /**
  1098. * set a custom handler, which gets all notifications.
  1099. *
  1100. * This handler gets the following arguments:
  1101. * alertType (see array), $element, args, icon
  1102. * If it returns true, the own processing will be stopped so the message
  1103. * will not be displayed. Otherwise it will continue.
  1104. * As an aditional feature it can return q jQuery element, which will
  1105. * then be used to add the message there. Icons are not supported in
  1106. * that case and will be ignored.
  1107. * Pass 'null' to reset/delete the custom handler.
  1108. * Note that there is no notification when a message is supposed to get
  1109. * hidden.
  1110. *
  1111. * @name Alert.setCustomHandler
  1112. * @function
  1113. * @param {function|null} newHandler
  1114. */
  1115. me.setCustomHandler = function(newHandler)
  1116. {
  1117. customHandler = newHandler;
  1118. }
  1119. /**
  1120. * init status manager
  1121. *
  1122. * preloads jQuery elements
  1123. *
  1124. * @name Alert.init
  1125. * @function
  1126. */
  1127. me.init = function()
  1128. {
  1129. // hide "no javascript" error message
  1130. $('#noscript').hide();
  1131. // not a reset, but first set of the elements
  1132. $errorMessage = $('#errormessage');
  1133. $loadingIndicator = $('#loadingindicator');
  1134. $statusMessage = $('#status');
  1135. $remainingTime = $('#remainingtime');
  1136. currentIcon = [
  1137. 'glyphicon-time', // loading icon
  1138. 'glyphicon-info-sign', // status icon
  1139. '', // reserved for warning, not used yet
  1140. 'glyphicon-alert' // error icon
  1141. ];
  1142. }
  1143. return me;
  1144. })();
  1145. /**
  1146. * handles paste status/result
  1147. *
  1148. * @name PasteStatus
  1149. * @param {object} window
  1150. * @class
  1151. */
  1152. var PasteStatus = (function (window) {
  1153. var me = {};
  1154. var $pasteSuccess,
  1155. $pasteUrl,
  1156. $remainingTime,
  1157. $shortenButton;
  1158. /**
  1159. * forward to URL shortener
  1160. *
  1161. * @name PasteStatus.sendToShortener
  1162. * @private
  1163. * @function
  1164. * @param {Event} event
  1165. */
  1166. function sendToShortener(event)
  1167. {
  1168. window.location.href = $shortenButton.data('shortener')
  1169. + encodeURIComponent($pasteUrl.attr('href'));
  1170. }
  1171. /**
  1172. * Forces opening the paste if the link does not do this automatically.
  1173. *
  1174. * This is necessary as browsers will not reload the page when it is
  1175. * already loaded (which is fake as it is set via history.pushState()).
  1176. *
  1177. * @name PasteStatus.pasteLinkClick
  1178. * @function
  1179. * @param {Event} event
  1180. */
  1181. function pasteLinkClick(event)
  1182. {
  1183. // check if location is (already) shown in URL bar
  1184. if (window.location.href === $pasteUrl.attr('href')) {
  1185. // if so we need to load link by reloading the current site
  1186. window.location.reload(true);
  1187. }
  1188. }
  1189. /**
  1190. * creates a notification after a successfull paste upload
  1191. *
  1192. * @name PasteStatus.createPasteNotification
  1193. * @function
  1194. * @param {string} url
  1195. * @param {string} deleteUrl
  1196. */
  1197. me.createPasteNotification = function(url, deleteUrl)
  1198. {
  1199. $('#pastelink').html(
  1200. I18n._(
  1201. 'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
  1202. url, url
  1203. )
  1204. );
  1205. // save newly created element
  1206. $pasteUrl = $('#pasteurl');
  1207. // and add click event
  1208. $pasteUrl.click(pasteLinkClick);
  1209. // shorten button
  1210. $('#deletelink').html('<a href="' + deleteUrl + '">' + I18n._('Delete data') + '</a>');
  1211. // show result
  1212. $pasteSuccess.removeClass('hidden');
  1213. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1214. Helper.selectText($pasteUrl[0]);
  1215. }
  1216. /**
  1217. * shows the remaining time
  1218. *
  1219. * @name PasteStatus.showRemainingTime
  1220. * @function
  1221. * @param {object} pasteMetaData
  1222. */
  1223. me.showRemainingTime = function(pasteMetaData)
  1224. {
  1225. if (pasteMetaData.burnafterreading) {
  1226. // display paste "for your eyes only" if it is deleted
  1227. // actually remove paste, before we claim it is deleted
  1228. Controller.removePaste(Model.getPasteId(), 'burnafterreading');
  1229. Alert.showRemaining("FOR YOUR EYES ONLY. Don't close this window, this message can't be displayed again.");
  1230. $remainingTime.addClass('foryoureyesonly');
  1231. // discourage cloning (it cannot really be prevented)
  1232. TopNav.hideCloneButton();
  1233. } else if (pasteMetaData.expire_date) {
  1234. // display paste expiration
  1235. var expiration = Helper.secondsToHuman(pasteMetaData.remaining_time),
  1236. expirationLabel = [
  1237. 'This document will expire in %d ' + expiration[1] + '.',
  1238. 'This document will expire in %d ' + expiration[1] + 's.'
  1239. ];
  1240. Alert.showRemaining([expirationLabel, expiration[0]]);
  1241. $remainingTime.removeClass('foryoureyesonly')
  1242. } else {
  1243. // never expires
  1244. return;
  1245. }
  1246. // in the end, display notification
  1247. $remainingTime.removeClass('hidden');
  1248. }
  1249. /**
  1250. * hides the remaining time and successful upload notification
  1251. *
  1252. * @name PasteStatus.hideRemainingTime
  1253. * @function
  1254. */
  1255. me.hideMessages = function()
  1256. {
  1257. $remainingTime.addClass('hidden');
  1258. $pasteSuccess.addClass('hidden');
  1259. }
  1260. /**
  1261. * init status manager
  1262. *
  1263. * preloads jQuery elements
  1264. *
  1265. * @name PasteStatus.init
  1266. * @function
  1267. */
  1268. me.init = function()
  1269. {
  1270. $pasteSuccess = $('#pasteSuccess');
  1271. // $pasteUrl is saved in me.createPasteNotification() after creation
  1272. $remainingTime = $('#remainingtime');
  1273. $shortenButton = $('#shortenbutton');
  1274. // bind elements
  1275. $shortenButton.click(sendToShortener);
  1276. }
  1277. return me;
  1278. })(window);
  1279. /**
  1280. * password prompt
  1281. *
  1282. * @name Prompt
  1283. * @class
  1284. */
  1285. var Prompt = (function () {
  1286. var me = {};
  1287. var $passwordDecrypt,
  1288. $passwordForm,
  1289. $passwordModal;
  1290. var password = '';
  1291. /**
  1292. * submit a password in the modal dialog
  1293. *
  1294. * @name Prompt.submitPasswordModal
  1295. * @private
  1296. * @function
  1297. * @param {Event} event
  1298. */
  1299. function submitPasswordModal(event)
  1300. {
  1301. event.preventDefault();
  1302. // get input
  1303. password = $passwordDecrypt.val();
  1304. // hide modal
  1305. $passwordModal.modal('hide');
  1306. PasteDecrypter.run();
  1307. }
  1308. /**
  1309. * ask the user for the password and set it
  1310. *
  1311. * @name Prompt.requestPassword
  1312. * @function
  1313. */
  1314. me.requestPassword = function()
  1315. {
  1316. // show new bootstrap method (if available)
  1317. if ($passwordModal.length !== 0) {
  1318. $passwordModal.modal({
  1319. backdrop: 'static',
  1320. keyboard: false
  1321. });
  1322. return;
  1323. }
  1324. // fallback to old method for page template
  1325. var newPassword = prompt(I18n._('Please enter the password for this paste:'), '');
  1326. if (newPassword === null) {
  1327. throw 'password prompt canceled';
  1328. }
  1329. if (password.length === 0) {
  1330. // recursive…
  1331. return me.requestPassword();
  1332. }
  1333. password = newPassword;
  1334. }
  1335. /**
  1336. * getthe cached password
  1337. *
  1338. * If you do not get a password with this function
  1339. * (returns an empty string), use requestPassword.
  1340. *
  1341. * @name Prompt.getPassword
  1342. * @function
  1343. * @return {string}
  1344. */
  1345. me.getPassword = function()
  1346. {
  1347. return password;
  1348. }
  1349. /**
  1350. * init status manager
  1351. *
  1352. * preloads jQuery elements
  1353. *
  1354. * @name Prompt.init
  1355. * @function
  1356. */
  1357. me.init = function()
  1358. {
  1359. $passwordDecrypt = $('#passworddecrypt');
  1360. $passwordForm = $('#passwordform');
  1361. $passwordModal = $('#passwordmodal');
  1362. // bind events
  1363. // focus password input when it is shown
  1364. $passwordModal.on('shown.bs.Model', function () {
  1365. $passwordDecrypt.focus();
  1366. });
  1367. // handle Model password submission
  1368. $passwordForm.submit(submitPasswordModal);
  1369. }
  1370. return me;
  1371. })();
  1372. /**
  1373. * Manage paste/message input, and preview tab
  1374. *
  1375. * Note that the actual preview is handled by PasteViewer.
  1376. *
  1377. * @name Editor
  1378. * @class
  1379. */
  1380. var Editor = (function () {
  1381. var me = {};
  1382. var $editorTabs,
  1383. $messageEdit,
  1384. $messagePreview,
  1385. $message;
  1386. var isPreview = false;
  1387. /**
  1388. * support input of tab character
  1389. *
  1390. * @name Editor.supportTabs
  1391. * @function
  1392. * @param {Event} event
  1393. * @this $message (but not used, so it is jQuery-free, possibly faster)
  1394. */
  1395. function supportTabs(event)
  1396. {
  1397. var keyCode = event.keyCode || event.which;
  1398. // tab was pressed
  1399. if (keyCode === 9) {
  1400. // get caret position & selection
  1401. var val = this.value,
  1402. start = this.selectionStart,
  1403. end = this.selectionEnd;
  1404. // set textarea value to: text before caret + tab + text after caret
  1405. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1406. // put caret at right position again
  1407. this.selectionStart = this.selectionEnd = start + 1;
  1408. // prevent the textarea to lose focus
  1409. event.preventDefault();
  1410. }
  1411. }
  1412. /**
  1413. * view the Editor tab
  1414. *
  1415. * @name Editor.viewEditor
  1416. * @function
  1417. * @param {Event} event - optional
  1418. */
  1419. function viewEditor(event)
  1420. {
  1421. // toggle buttons
  1422. $messageEdit.addClass('active');
  1423. $messagePreview.removeClass('active');
  1424. PasteViewer.hide();
  1425. // reshow input
  1426. $message.removeClass('hidden');
  1427. me.focusInput();
  1428. // finish
  1429. isPreview = false;
  1430. // prevent jumping of page to top
  1431. if (typeof event !== 'undefined') {
  1432. event.preventDefault();
  1433. }
  1434. }
  1435. /**
  1436. * view the preview tab
  1437. *
  1438. * @name Editor.viewPreview
  1439. * @function
  1440. * @param {Event} event
  1441. */
  1442. function viewPreview(event)
  1443. {
  1444. // toggle buttons
  1445. $messageEdit.removeClass('active');
  1446. $messagePreview.addClass('active');
  1447. // hide input as now preview is shown
  1448. $message.addClass('hidden');
  1449. // show preview
  1450. PasteViewer.setText($message.val());
  1451. PasteViewer.run();
  1452. // finish
  1453. isPreview = true;
  1454. // prevent jumping of page to top
  1455. if (typeof event !== 'undefined') {
  1456. event.preventDefault();
  1457. }
  1458. }
  1459. /**
  1460. * get the state of the preview
  1461. *
  1462. * @name Editor.isPreview
  1463. * @function
  1464. */
  1465. me.isPreview = function()
  1466. {
  1467. return isPreview;
  1468. }
  1469. /**
  1470. * reset the Editor view
  1471. *
  1472. * @name Editor.resetInput
  1473. * @function
  1474. */
  1475. me.resetInput = function()
  1476. {
  1477. // go back to input
  1478. if (isPreview) {
  1479. viewEditor();
  1480. }
  1481. // clear content
  1482. $message.val('');
  1483. }
  1484. /**
  1485. * shows the Editor
  1486. *
  1487. * @name Editor.show
  1488. * @function
  1489. */
  1490. me.show = function()
  1491. {
  1492. $message.removeClass('hidden');
  1493. $editorTabs.removeClass('hidden');
  1494. }
  1495. /**
  1496. * hides the Editor
  1497. *
  1498. * @name Editor.reset
  1499. * @function
  1500. */
  1501. me.hide = function()
  1502. {
  1503. $message.addClass('hidden');
  1504. $editorTabs.addClass('hidden');
  1505. }
  1506. /**
  1507. * focuses the message input
  1508. *
  1509. * @name Editor.focusInput
  1510. * @function
  1511. */
  1512. me.focusInput = function()
  1513. {
  1514. $message.focus();
  1515. }
  1516. /**
  1517. * sets a new text
  1518. *
  1519. * @name Editor.setText
  1520. * @function
  1521. * @param {string} newText
  1522. */
  1523. me.setText = function(newText)
  1524. {
  1525. $message.val(newText);
  1526. }
  1527. /**
  1528. * returns the current text
  1529. *
  1530. * @name Editor.getText
  1531. * @function
  1532. * @return {string}
  1533. */
  1534. me.getText = function()
  1535. {
  1536. return $message.val()
  1537. }
  1538. /**
  1539. * init status manager
  1540. *
  1541. * preloads jQuery elements
  1542. *
  1543. * @name Editor.init
  1544. * @function
  1545. */
  1546. me.init = function()
  1547. {
  1548. $editorTabs = $('#editorTabs');
  1549. $message = $('#message');
  1550. // bind events
  1551. $message.keydown(supportTabs);
  1552. // bind click events to tab switchers (a), but save parent of them
  1553. // (li)
  1554. $messageEdit = $('#messageedit').click(viewEditor).parent();
  1555. $messagePreview = $('#messagepreview').click(viewPreview).parent();
  1556. }
  1557. return me;
  1558. })();
  1559. /**
  1560. * (view) Parse and show paste.
  1561. *
  1562. * @name PasteViewer
  1563. * @class
  1564. */
  1565. var PasteViewer = (function () {
  1566. var me = {};
  1567. var $placeholder,
  1568. $prettyMessage,
  1569. $prettyPrint,
  1570. $plainText;
  1571. var text,
  1572. format = 'plaintext',
  1573. isDisplayed = false,
  1574. isChanged = true; // by default true as nothing was parsed yet
  1575. /**
  1576. * apply the set format on paste and displays it
  1577. *
  1578. * @name PasteViewer.parsePaste
  1579. * @private
  1580. * @function
  1581. */
  1582. function parsePaste()
  1583. {
  1584. // skip parsing if no text is given
  1585. if (text === '') {
  1586. return;
  1587. }
  1588. // set text
  1589. Helper.setElementText($plainText, text);
  1590. Helper.setElementText($prettyPrint, text);
  1591. switch (format) {
  1592. case 'markdown':
  1593. var converter = new showdown.Converter({
  1594. strikethrough: true,
  1595. tables: true,
  1596. tablesHeaderId: true
  1597. });
  1598. $plainText.html(
  1599. converter.makeHtml(text)
  1600. );
  1601. // add table classes from bootstrap css
  1602. $plainText.find('table').addClass('table-condensed table-bordered');
  1603. break;
  1604. case 'syntaxhighlighting':
  1605. // @TODO is this really needed or is "one" enough?
  1606. if (typeof prettyPrint === 'function')
  1607. {
  1608. prettyPrint();
  1609. }
  1610. $prettyPrint.html(
  1611. prettyPrintOne(
  1612. Helper.htmlEntities(text), null, true
  1613. )
  1614. );
  1615. // fall through, as the rest is the same
  1616. default: // = 'plaintext'
  1617. // convert URLs to clickable links
  1618. Helper.urls2links($plainText);
  1619. Helper.urls2links($prettyPrint);
  1620. $prettyPrint.css('white-space', 'pre-wrap');
  1621. $prettyPrint.css('word-break', 'normal');
  1622. $prettyPrint.removeClass('prettyprint');
  1623. }
  1624. }
  1625. /**
  1626. * displays the paste
  1627. *
  1628. * @name PasteViewer.showPaste
  1629. * @private
  1630. * @function
  1631. */
  1632. function showPaste()
  1633. {
  1634. // instead of "nothing" better display a placeholder
  1635. if (text === '') {
  1636. $placeholder.removeClass('hidden')
  1637. return;
  1638. }
  1639. // otherwise hide the placeholder
  1640. $placeholder.addClass('hidden')
  1641. switch (format) {
  1642. case 'markdown':
  1643. $plainText.removeClass('hidden');
  1644. $prettyMessage.addClass('hidden');
  1645. break;
  1646. default:
  1647. $plainText.addClass('hidden');
  1648. $prettyMessage.removeClass('hidden');
  1649. break;
  1650. }
  1651. }
  1652. /**
  1653. * sets the format in which the text is shown
  1654. *
  1655. * @name PasteViewer.setFormat
  1656. * @function
  1657. * @param {string} newFormat the the new format
  1658. */
  1659. me.setFormat = function(newFormat)
  1660. {
  1661. // skip if there is no update
  1662. if (format === newFormat) {
  1663. return;
  1664. }
  1665. // needs to update display too, if from or to Markdown is switched
  1666. if (format === 'markdown' || newFormat === 'markdown') {
  1667. isDisplayed = false;
  1668. }
  1669. format = newFormat;
  1670. isChanged = true;
  1671. }
  1672. /**
  1673. * returns the current format
  1674. *
  1675. * @name PasteViewer.getFormat
  1676. * @function
  1677. * @return {string}
  1678. */
  1679. me.getFormat = function()
  1680. {
  1681. return format;
  1682. }
  1683. /**
  1684. * returns whether the current view is pretty printed
  1685. *
  1686. * @name PasteViewer.isPrettyPrinted
  1687. * @function
  1688. * @return {bool}
  1689. */
  1690. me.isPrettyPrinted = function()
  1691. {
  1692. return $prettyPrint.hasClass('prettyprinted');
  1693. }
  1694. /**
  1695. * sets the text to show
  1696. *
  1697. * @name PasteViewer.setText
  1698. * @function
  1699. * @param {string} newText the text to show
  1700. */
  1701. me.setText = function(newText)
  1702. {
  1703. if (text !== newText) {
  1704. text = newText;
  1705. isChanged = true;
  1706. }
  1707. }
  1708. /**
  1709. * gets the current cached text
  1710. *
  1711. * @name PasteViewer.getText
  1712. * @function
  1713. * @return {string}
  1714. */
  1715. me.getText = function()
  1716. {
  1717. return text;
  1718. }
  1719. /**
  1720. * show/update the parsed text (preview)
  1721. *
  1722. * @name PasteViewer.run
  1723. * @function
  1724. */
  1725. me.run = function()
  1726. {
  1727. if (isChanged) {
  1728. parsePaste();
  1729. isChanged = false;
  1730. }
  1731. if (!isDisplayed) {
  1732. showPaste();
  1733. isDisplayed = true;
  1734. }
  1735. }
  1736. /**
  1737. * hide parsed text (preview)
  1738. *
  1739. * @name PasteViewer.hide
  1740. * @function
  1741. */
  1742. me.hide = function()
  1743. {
  1744. if (!isDisplayed) {
  1745. console.warn('PasteViewer was called to hide the parsed view, but it is already hidden.');
  1746. }
  1747. $plainText.addClass('hidden');
  1748. $prettyMessage.addClass('hidden');
  1749. $placeholder.addClass('hidden');
  1750. isDisplayed = false;
  1751. }
  1752. /**
  1753. * init status manager
  1754. *
  1755. * preloads jQuery elements
  1756. *
  1757. * @name PasteViewer.init
  1758. * @function
  1759. */
  1760. me.init = function()
  1761. {
  1762. $placeholder = $('#placeholder');
  1763. $plainText = $('#plaintext');
  1764. $prettyMessage = $('#prettymessage');
  1765. $prettyPrint = $('#prettyprint');
  1766. // check requirements
  1767. if (typeof prettyPrintOne !== 'function') {
  1768. Alert.showError([
  1769. 'The library %s is not available. This may cause display errors.',
  1770. 'pretty print'
  1771. ]);
  1772. }
  1773. if (typeof showdown !== 'object') {
  1774. Alert.showError([
  1775. 'The library %s is not available. This may cause display errors.',
  1776. 'showdown'
  1777. ]);
  1778. }
  1779. // get default option from template/HTML or fall back to set value
  1780. format = Model.getFormatDefault() || format;
  1781. }
  1782. return me;
  1783. })();
  1784. /**
  1785. * (view) Show attachment and preview if possible
  1786. *
  1787. * @name AttachmentViewer
  1788. * @param {object} window
  1789. * @param {object} document
  1790. * @class
  1791. */
  1792. var AttachmentViewer = (function (window, document) {
  1793. var me = {};
  1794. var $attachmentLink,
  1795. $attachmentPreview,
  1796. $attachment;
  1797. var attachmentHasPreview = false;
  1798. /**
  1799. * sets the attachment but does not yet show it
  1800. *
  1801. * @name AttachmentViewer.setAttachment
  1802. * @function
  1803. * @param {string} attachmentData - base64-encoded data of file
  1804. * @param {string} fileName - optional, file name
  1805. */
  1806. me.setAttachment = function(attachmentData, fileName)
  1807. {
  1808. var imagePrefix = 'data:image/';
  1809. $attachmentLink.attr('href', attachmentData);
  1810. if (typeof fileName !== 'undefined') {
  1811. $attachmentLink.attr('download', fileName);
  1812. }
  1813. // if the attachment is an image, display it
  1814. if (attachmentData.substring(0, imagePrefix.length) === imagePrefix) {
  1815. $attachmentPreview.html(
  1816. $(document.createElement('img'))
  1817. .attr('src', attachmentData)
  1818. .attr('class', 'img-thumbnail')
  1819. );
  1820. attachmentHasPreview = true;
  1821. }
  1822. }
  1823. /**
  1824. * displays the attachment
  1825. *
  1826. * @name AttachmentViewer.showAttachment
  1827. * @function
  1828. */
  1829. me.showAttachment = function()
  1830. {
  1831. $attachment.removeClass('hidden');
  1832. if (attachmentHasPreview) {
  1833. $attachmentPreview.removeClass('hidden');
  1834. }
  1835. }
  1836. /**
  1837. * removes the attachment
  1838. *
  1839. * This automatically hides the attachment containers to, to
  1840. * prevent an inconsistent display.
  1841. *
  1842. * @name AttachmentViewer.removeAttachment
  1843. * @function
  1844. */
  1845. me.removeAttachment = function()
  1846. {
  1847. me.hideAttachment();
  1848. me.hideAttachmentPreview();
  1849. $attachmentLink.prop('href', '');
  1850. $attachmentLink.prop('download', '');
  1851. $attachmentPreview.html('');
  1852. }
  1853. /**
  1854. * hides the attachment
  1855. *
  1856. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  1857. * for that) nor will it hide the attachment link if it was moved somewhere
  1858. * else (see AttachmentViewer.moveAttachmentTo).
  1859. *
  1860. * @name AttachmentViewer.hideAttachment
  1861. * @function
  1862. */
  1863. me.hideAttachment = function()
  1864. {
  1865. $attachment.addClass('hidden');
  1866. }
  1867. /**
  1868. * hides the attachment preview
  1869. *
  1870. * @name AttachmentViewer.hideAttachmentPreview
  1871. * @function
  1872. */
  1873. me.hideAttachmentPreview = function()
  1874. {
  1875. $attachmentPreview.addClass('hidden');
  1876. }
  1877. /**
  1878. * checks if there is an attachment
  1879. *
  1880. * @name AttachmentViewer.hasAttachment
  1881. * @function
  1882. */
  1883. me.hasAttachment = function()
  1884. {
  1885. var link = $attachmentLink.prop('href');
  1886. return (typeof link !== 'undefined' && link !== '')
  1887. }
  1888. /**
  1889. * return the attachment
  1890. *
  1891. * @name AttachmentViewer.getAttachment
  1892. * @function
  1893. * @returns {array}
  1894. */
  1895. me.getAttachment = function()
  1896. {
  1897. return [
  1898. $attachmentLink.prop('href'),
  1899. $attachmentLink.prop('download')
  1900. ];
  1901. }
  1902. /**
  1903. * moves the attachment link to another element
  1904. *
  1905. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  1906. *
  1907. * @name AttachmentViewer.moveAttachmentTo
  1908. * @function
  1909. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  1910. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  1911. */
  1912. me.moveAttachmentTo = function($element, label)
  1913. {
  1914. // move elemement to new place
  1915. $attachmentLink.appendTo($element);
  1916. // update text
  1917. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  1918. }
  1919. /**
  1920. * initiate
  1921. *
  1922. * preloads jQuery elements
  1923. *
  1924. * @name AttachmentViewer.init
  1925. * @function
  1926. */
  1927. me.init = function()
  1928. {
  1929. $attachment = $('#attachment');
  1930. $attachmentLink = $('#attachment a');
  1931. $attachmentPreview = $('#attachmentPreview');
  1932. }
  1933. return me;
  1934. })(window, document);
  1935. /**
  1936. * (view) Shows discussion thread and handles replies
  1937. *
  1938. * @name DiscussionViewer
  1939. * @param {object} window
  1940. * @param {object} document
  1941. * @class
  1942. */
  1943. var DiscussionViewer = (function (window, document) {
  1944. var me = {};
  1945. var $commentTail,
  1946. $discussion,
  1947. $reply,
  1948. $replyMessage,
  1949. $replyNickname,
  1950. $replyStatus,
  1951. $commentContainer;
  1952. var replyCommentId;
  1953. /**
  1954. * initializes the templates
  1955. *
  1956. * @name DiscussionViewer.initTemplates
  1957. * @private
  1958. * @function
  1959. */
  1960. function initTemplates()
  1961. {
  1962. $reply = Model.getTemplate('reply');
  1963. $replyMessage = $reply.find('#replymessage');
  1964. $replyNickname = $reply.find('#nickname');
  1965. $replyStatus = $reply.find('#replystatus');
  1966. // cache jQuery elements
  1967. $commentTail = Model.getTemplate('commenttail');
  1968. }
  1969. /**
  1970. * open the comment entry when clicking the "Reply" button of a comment
  1971. *
  1972. * @name DiscussionViewer.openReply
  1973. * @private
  1974. * @function
  1975. * @param {Event} event
  1976. */
  1977. function openReply(event)
  1978. {
  1979. var $source = $(event.target);
  1980. // clear input
  1981. $replyMessage.val('');
  1982. $replyNickname.val('');
  1983. // get comment id from source element
  1984. replyCommentId = $source.parent().prop('id').split('_')[1];
  1985. // move to correct position
  1986. $source.after($reply);
  1987. // show
  1988. $reply.removeClass('hidden');
  1989. $replyMessage.focus();
  1990. event.preventDefault();
  1991. }
  1992. /**
  1993. * custom handler for displaying notifications in own status message area
  1994. *
  1995. * @name DiscussionViewer.handleNotification
  1996. * @function
  1997. * @param {string} alertType
  1998. * @param {jQuery} $element
  1999. * @param {string|array} args
  2000. * @param {string|null} icon
  2001. * @return {bool|jQuery}
  2002. */
  2003. me.handleNotification = function(alertType, $element, args, icon)
  2004. {
  2005. // ignore loading messages
  2006. if (alertType === 'loading') {
  2007. return false;
  2008. }
  2009. if (alertType === 'danger') {
  2010. $replyStatus.removeClass('alert-info');
  2011. $replyStatus.addClass('alert-danger');
  2012. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2013. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2014. } else {
  2015. $replyStatus.removeClass('alert-danger');
  2016. $replyStatus.addClass('alert-info');
  2017. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2018. $replyStatus.find(':first').addClass('glyphicon-alert');
  2019. }
  2020. return $replyStatus;
  2021. }
  2022. /**
  2023. * adds another comment
  2024. *
  2025. * @name DiscussionViewer.addComment
  2026. * @function
  2027. * @param {object} comment
  2028. * @param {string} commentText
  2029. * @param {jQuery} $place - optional, tries to find the best position otherwise
  2030. */
  2031. me.addComment = function(comment, commentText, nickname, $place)
  2032. {
  2033. if (typeof $place === 'undefined') {
  2034. // starting point (default value/fallback)
  2035. $place = $commentContainer;
  2036. // if parent comment exists
  2037. var $parentComment = $('#comment_' + comment.parentid);
  2038. if ($parentComment.length) {
  2039. // use parent as position for noew comment, so it shifted
  2040. // to the right
  2041. $place = $parentComment;
  2042. }
  2043. }
  2044. if (commentText === '') {
  2045. commentText = 'comment decryption failed';
  2046. }
  2047. // create new comment based on template
  2048. var $commentEntry = Model.getTemplate('comment');
  2049. $commentEntry.prop('id', 'comment_' + comment.id);
  2050. var $commentEntryData = $commentEntry.find('div.commentdata');
  2051. // set & parse text
  2052. Helper.setElementText($commentEntryData, commentText);
  2053. Helper.urls2links($commentEntryData);
  2054. // set nickname
  2055. if (nickname.length > 0) {
  2056. $commentEntry.find('span.nickname').text(nickname);
  2057. } else {
  2058. $commentEntry.find('span.nickname').html('<i></i>');
  2059. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2060. }
  2061. // set date
  2062. $commentEntry.find('span.commentdate')
  2063. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2064. .attr('title', 'CommentID: ' + comment.id);
  2065. // if an avatar is available, display it
  2066. if (comment.meta.vizhash) {
  2067. $commentEntry.find('span.nickname')
  2068. .before(
  2069. '<img src="' + comment.meta.vizhash + '" class="vizhash" /> '
  2070. );
  2071. $(document).on('languageLoaded', function () {
  2072. $commentEntry.find('img.vizhash')
  2073. .prop('title', I18n._('Avatar generated from IP address'));
  2074. });
  2075. }
  2076. // finally append comment
  2077. $place.append($commentEntry);
  2078. }
  2079. /**
  2080. * finishes the discussion area after last comment
  2081. *
  2082. * @name DiscussionViewer.finishDiscussion
  2083. * @function
  2084. */
  2085. me.finishDiscussion = function()
  2086. {
  2087. // add 'add new comment' area
  2088. $commentContainer.append($commentTail);
  2089. // show discussions
  2090. $discussion.removeClass('hidden');
  2091. }
  2092. /**
  2093. * shows the discussion area
  2094. *
  2095. * @name DiscussionViewer.showDiscussion
  2096. * @function
  2097. */
  2098. me.showDiscussion = function()
  2099. {
  2100. $discussion.removeClass('hidden');
  2101. }
  2102. /**
  2103. * removes the old discussion and prepares everything for creating a new
  2104. * one.
  2105. *
  2106. * @name DiscussionViewer.prepareNewDisucssion
  2107. * @function
  2108. */
  2109. me.prepareNewDisucssion = function()
  2110. {
  2111. $commentContainer.html('');
  2112. $discussion.addClass('hidden');
  2113. // (re-)init templates
  2114. initTemplates();
  2115. }
  2116. /**
  2117. * returns the user put into the reply form
  2118. *
  2119. * @name DiscussionViewer.getReplyData
  2120. * @function
  2121. * @return {array}
  2122. */
  2123. me.getReplyData = function()
  2124. {
  2125. return [
  2126. $replyMessage.val(),
  2127. $replyNickname.val()
  2128. ];
  2129. }
  2130. /**
  2131. * highlights a specific comment and scrolls to it if necessary
  2132. *
  2133. * @name DiscussionViewer.highlightComment
  2134. * @function
  2135. * @param {string} commentId
  2136. * @param {bool} fadeOut - whether to fade out the comment
  2137. */
  2138. me.highlightComment = function(commentId, fadeOut)
  2139. {
  2140. var $comment = $('#comment_' + commentId);
  2141. // in case comment does not exist, cancel
  2142. if ($comment.length === 0) {
  2143. return;
  2144. }
  2145. var highlightComment = function () {
  2146. $comment.addClass('highlight');
  2147. if (fadeOut === true) {
  2148. setTimeout(function () {
  2149. $comment.removeClass('highlight');
  2150. }, 300);
  2151. }
  2152. }
  2153. if (UiHelper.isVisible($comment)) {
  2154. return highlightComment();
  2155. }
  2156. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2157. }
  2158. /**
  2159. * returns the id of the parent comment the user is replying to
  2160. *
  2161. * @name DiscussionViewer.getReplyCommentId
  2162. * @function
  2163. * @return {int|undefined}
  2164. */
  2165. me.getReplyCommentId = function()
  2166. {
  2167. return replyCommentId;
  2168. }
  2169. /**
  2170. * initiate
  2171. *
  2172. * preloads jQuery elements
  2173. *
  2174. * @name DiscussionViewer.init
  2175. * @function
  2176. */
  2177. me.init = function()
  2178. {
  2179. // bind events to templates (so they are later cloned)
  2180. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2181. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2182. $commentContainer = $('#commentcontainer');
  2183. $discussion = $('#discussion');
  2184. }
  2185. return me;
  2186. })(window, document);
  2187. /**
  2188. * Manage top (navigation) bar
  2189. *
  2190. * @name TopNav
  2191. * @param {object} window
  2192. * @param {object} document
  2193. * @class
  2194. */
  2195. var TopNav = (function (window, document) {
  2196. var me = {};
  2197. var createButtonsDisplayed = false;
  2198. var viewButtonsDisplayed = false;
  2199. var $attach,
  2200. $burnAfterReading,
  2201. $burnAfterReadingOption,
  2202. $cloneButton,
  2203. $customAttachment,
  2204. $expiration,
  2205. $fileRemoveButton,
  2206. $fileWrap,
  2207. $formatter,
  2208. $newButton,
  2209. $openDiscussion,
  2210. $openDiscussionOption,
  2211. $password,
  2212. $passwordInput,
  2213. $rawTextButton,
  2214. $sendButton;
  2215. var pasteExpiration = '1week';
  2216. /**
  2217. * set the expiration on bootstrap templates in dropdown
  2218. *
  2219. * @name TopNav.updateExpiration
  2220. * @private
  2221. * @function
  2222. * @param {Event} event
  2223. */
  2224. function updateExpiration(event)
  2225. {
  2226. // get selected option
  2227. var target = $(event.target);
  2228. // update dropdown display and save new expiration time
  2229. $('#pasteExpirationDisplay').text(target.text());
  2230. pasteExpiration = target.data('expiration');
  2231. event.preventDefault();
  2232. }
  2233. /**
  2234. * set the format on bootstrap templates in dropdown
  2235. *
  2236. * @name TopNav.updateFormat
  2237. * @private
  2238. * @function
  2239. * @param {Event} event
  2240. */
  2241. function updateFormat(event)
  2242. {
  2243. // get selected option
  2244. var $target = $(event.target);
  2245. // update dropdown display and save new format
  2246. var newFormat = $target.data('format');
  2247. $('#pasteFormatterDisplay').text($target.text());
  2248. PasteViewer.setFormat(newFormat);
  2249. // update preview
  2250. if (Editor.isPreview()) {
  2251. PasteViewer.run();
  2252. }
  2253. event.preventDefault();
  2254. }
  2255. /**
  2256. * when "burn after reading" is checked, disable discussion
  2257. *
  2258. * @name TopNav.changeBurnAfterReading
  2259. * @private
  2260. * @function
  2261. */
  2262. function changeBurnAfterReading()
  2263. {
  2264. if ($burnAfterReading.is(':checked')) {
  2265. $openDiscussionOption.addClass('buttondisabled');
  2266. $openDiscussion.prop('checked', false);
  2267. // if button is actually disabled, force-enable it and uncheck other button
  2268. $burnAfterReadingOption.removeClass('buttondisabled');
  2269. } else {
  2270. $openDiscussionOption.removeClass('buttondisabled');
  2271. }
  2272. }
  2273. /**
  2274. * when discussion is checked, disable "burn after reading"
  2275. *
  2276. * @name TopNav.changeOpenDiscussion
  2277. * @private
  2278. * @function
  2279. */
  2280. function changeOpenDiscussion()
  2281. {
  2282. if ($openDiscussion.is(':checked')) {
  2283. $burnAfterReadingOption.addClass('buttondisabled');
  2284. $burnAfterReading.prop('checked', false);
  2285. // if button is actually disabled, force-enable it and uncheck other button
  2286. $openDiscussionOption.removeClass('buttondisabled');
  2287. } else {
  2288. $burnAfterReadingOption.removeClass('buttondisabled');
  2289. }
  2290. }
  2291. /**
  2292. * return raw text
  2293. *
  2294. * @name TopNav.rawText
  2295. * @private
  2296. * @function
  2297. * @param {Event} event
  2298. */
  2299. function rawText(event)
  2300. {
  2301. TopNav.hideAllButtons();
  2302. Alert.showLoading('Showing raw text…', 0, 'time');
  2303. var paste = PasteViewer.getText();
  2304. // push a new state to allow back navigation with browser back button
  2305. history.pushState(
  2306. {type: 'raw'},
  2307. document.title,
  2308. // recreate paste URL
  2309. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  2310. Model.getPasteKey()
  2311. );
  2312. // we use text/html instead of text/plain to avoid a bug when
  2313. // reloading the raw text view (it reverts to type text/html)
  2314. var $head = $('head').children().not('noscript, script, link[type="text/css"]');
  2315. var newDoc = document.open('text/html', 'replace');
  2316. newDoc.write('<!DOCTYPE html><html><head>');
  2317. for (var i = 0; i < $head.length; i++) {
  2318. newDoc.write($head[i].outerHTML);
  2319. }
  2320. newDoc.write('</head><body><pre>' + Helper.htmlEntities(paste) + '</pre></body></html>');
  2321. newDoc.close();
  2322. }
  2323. /**
  2324. * saves the language in a cookie and reloads the page
  2325. *
  2326. * @name TopNav.setLanguage
  2327. * @private
  2328. * @function
  2329. * @param {Event} event
  2330. */
  2331. function setLanguage(event)
  2332. {
  2333. document.cookie = 'lang=' + $(event.target).data('lang');
  2334. UiHelper.reloadHome();
  2335. }
  2336. /**
  2337. * hides all messages and creates a new paste
  2338. *
  2339. * @name TopNav.clickNewPaste
  2340. * @private
  2341. * @function
  2342. * @param {Event} event
  2343. */
  2344. function clickNewPaste(event)
  2345. {
  2346. Controller.hideStatusMessages();
  2347. Controller.newPaste();
  2348. }
  2349. /**
  2350. * removes the existing attachment
  2351. *
  2352. * @name TopNav.removeAttachment
  2353. * @private
  2354. * @function
  2355. * @param {Event} event
  2356. */
  2357. function removeAttachment(event)
  2358. {
  2359. // if custom attachment is used, remove it first
  2360. if (!$customAttachment.hasClass('hidden')) {
  2361. AttachmentViewer.removeAttachment();
  2362. $customAttachment.addClass('hidden');
  2363. $fileWrap.removeClass('hidden');
  2364. }
  2365. // our up-to-date jQuery can handle it :)
  2366. $fileWrap.find('input').val('');
  2367. // pevent '#' from appearing in the URL
  2368. event.preventDefault();
  2369. }
  2370. /**
  2371. * Shows all elements belonging to viwing an existing pastes
  2372. *
  2373. * @name TopNav.showViewButtons
  2374. * @function
  2375. */
  2376. me.showViewButtons = function()
  2377. {
  2378. if (viewButtonsDisplayed) {
  2379. console.warn('showViewButtons: view buttons are already displayed');
  2380. return;
  2381. }
  2382. $newButton.removeClass('hidden');
  2383. $cloneButton.removeClass('hidden');
  2384. $rawTextButton.removeClass('hidden');
  2385. viewButtonsDisplayed = true;
  2386. }
  2387. /**
  2388. * Hides all elements belonging to existing pastes
  2389. *
  2390. * @name TopNav.hideViewButtons
  2391. * @function
  2392. */
  2393. me.hideViewButtons = function()
  2394. {
  2395. if (!viewButtonsDisplayed) {
  2396. console.warn('hideViewButtons: view buttons are already hidden');
  2397. return;
  2398. }
  2399. $newButton.addClass('hidden');
  2400. $cloneButton.addClass('hidden');
  2401. $rawTextButton.addClass('hidden');
  2402. viewButtonsDisplayed = false;
  2403. }
  2404. /**
  2405. * Hides all elements belonging to existing pastes
  2406. *
  2407. * @name TopNav.hideAllButtons
  2408. * @function
  2409. */
  2410. me.hideAllButtons = function()
  2411. {
  2412. me.hideViewButtons();
  2413. me.hideCreateButtons();
  2414. }
  2415. /**
  2416. * shows all elements needed when creating a new paste
  2417. *
  2418. * @name TopNav.showCreateButtons
  2419. * @function
  2420. */
  2421. me.showCreateButtons = function()
  2422. {
  2423. if (createButtonsDisplayed) {
  2424. console.warn('showCreateButtons: create buttons are already displayed');
  2425. return;
  2426. }
  2427. $sendButton.removeClass('hidden');
  2428. $expiration.removeClass('hidden');
  2429. $formatter.removeClass('hidden');
  2430. $burnAfterReadingOption.removeClass('hidden');
  2431. $openDiscussionOption.removeClass('hidden');
  2432. $newButton.removeClass('hidden');
  2433. $password.removeClass('hidden');
  2434. $attach.removeClass('hidden');
  2435. createButtonsDisplayed = true;
  2436. }
  2437. /**
  2438. * shows all elements needed when creating a new paste
  2439. *
  2440. * @name TopNav.hideCreateButtons
  2441. * @function
  2442. */
  2443. me.hideCreateButtons = function()
  2444. {
  2445. if (!createButtonsDisplayed) {
  2446. console.warn('hideCreateButtons: create buttons are already hidden');
  2447. return;
  2448. }
  2449. $newButton.addClass('hidden');
  2450. $sendButton.addClass('hidden');
  2451. $expiration.addClass('hidden');
  2452. $formatter.addClass('hidden');
  2453. $burnAfterReadingOption.addClass('hidden');
  2454. $openDiscussionOption.addClass('hidden');
  2455. $password.addClass('hidden');
  2456. $attach.addClass('hidden');
  2457. createButtonsDisplayed = false;
  2458. }
  2459. /**
  2460. * only shows the "new paste" button
  2461. *
  2462. * @name TopNav.showNewPasteButton
  2463. * @function
  2464. */
  2465. me.showNewPasteButton = function()
  2466. {
  2467. $newButton.removeClass('hidden');
  2468. }
  2469. /**
  2470. * only hides the clone button
  2471. *
  2472. * @name TopNav.hideCloneButton
  2473. * @function
  2474. */
  2475. me.hideCloneButton = function()
  2476. {
  2477. $cloneButton.addClass('hidden');
  2478. }
  2479. /**
  2480. * only hides the raw text button
  2481. *
  2482. * @name TopNav.hideRawButton
  2483. * @function
  2484. */
  2485. me.hideRawButton = function()
  2486. {
  2487. $rawTextButton.addClass('hidden');
  2488. }
  2489. /**
  2490. * hides the file selector in attachment
  2491. *
  2492. * @name TopNav.hideFileSelector
  2493. * @function
  2494. */
  2495. me.hideFileSelector = function()
  2496. {
  2497. $fileWrap.addClass('hidden');
  2498. }
  2499. /**
  2500. * shows the custom attachment
  2501. *
  2502. * @name TopNav.showCustomAttachment
  2503. * @function
  2504. */
  2505. me.showCustomAttachment = function()
  2506. {
  2507. $customAttachment.removeClass('hidden');
  2508. }
  2509. /**
  2510. * collapses the navigation bar if nedded
  2511. *
  2512. * @name TopNav.collapseBar
  2513. * @function
  2514. */
  2515. me.collapseBar = function()
  2516. {
  2517. var $bar = $('.navbar-toggle');
  2518. // check if bar is expanded
  2519. if ($bar.hasClass('collapse in')) {
  2520. // if so, toggle it
  2521. $bar.click();
  2522. }
  2523. }
  2524. /**
  2525. * returns the currently set expiration time
  2526. *
  2527. * @name TopNav.getExpiration
  2528. * @function
  2529. * @return {int}
  2530. */
  2531. me.getExpiration = function()
  2532. {
  2533. return pasteExpiration;
  2534. }
  2535. /**
  2536. * returns the currently selected file(s)
  2537. *
  2538. * @name TopNav.getFileList
  2539. * @function
  2540. * @return {FileList|null}
  2541. */
  2542. me.getFileList = function()
  2543. {
  2544. var $file = $('#file');
  2545. // if no file given, return null
  2546. if (!$file.length || !$file[0].files.length) {
  2547. return null;
  2548. }
  2549. // @TODO is this really necessary
  2550. if (!($file[0].files && $file[0].files[0])) {
  2551. return null;
  2552. }
  2553. return $file[0].files;
  2554. }
  2555. /**
  2556. * returns the state of the burn after reading checkbox
  2557. *
  2558. * @name TopNav.getExpiration
  2559. * @function
  2560. * @return {bool}
  2561. */
  2562. me.getBurnAfterReading = function()
  2563. {
  2564. return $burnAfterReading.is(':checked');
  2565. }
  2566. /**
  2567. * returns the state of the discussion checkbox
  2568. *
  2569. * @name TopNav.getOpenDiscussion
  2570. * @function
  2571. * @return {bool}
  2572. */
  2573. me.getOpenDiscussion = function()
  2574. {
  2575. return $openDiscussion.is(':checked');
  2576. }
  2577. /**
  2578. * returns the entered password
  2579. *
  2580. * @name TopNav.getPassword
  2581. * @function
  2582. * @return {string}
  2583. */
  2584. me.getPassword = function()
  2585. {
  2586. return $passwordInput.val();
  2587. }
  2588. /**
  2589. * returns the element where custom attachments can be placed
  2590. *
  2591. * Used by AttachmentViewer when an attachment is cloned here.
  2592. *
  2593. * @name TopNav.getCustomAttachment
  2594. * @function
  2595. * @return {jQuery}
  2596. */
  2597. me.getCustomAttachment = function()
  2598. {
  2599. return $customAttachment;
  2600. }
  2601. /**
  2602. * init navigation manager
  2603. *
  2604. * preloads jQuery elements
  2605. *
  2606. * @name TopNav.init
  2607. * @function
  2608. */
  2609. me.init = function()
  2610. {
  2611. $attach = $('#attach');
  2612. $burnAfterReading = $('#burnafterreading');
  2613. $burnAfterReadingOption = $('#burnafterreadingoption');
  2614. $cloneButton = $('#clonebutton');
  2615. $customAttachment = $('#customattachment');
  2616. $expiration = $('#expiration');
  2617. $fileRemoveButton = $('#fileremovebutton');
  2618. $fileWrap = $('#filewrap');
  2619. $formatter = $('#formatter');
  2620. $newButton = $('#newbutton');
  2621. $openDiscussion = $('#opendiscussion');
  2622. $openDiscussionOption = $('#opendiscussionoption');
  2623. $password = $('#password');
  2624. $passwordInput = $('#passwordinput');
  2625. $rawTextButton = $('#rawtextbutton');
  2626. $sendButton = $('#sendbutton');
  2627. // bootstrap template drop down
  2628. $('#language ul.dropdown-menu li a').click(setLanguage);
  2629. // page template drop down
  2630. $('#language select option').click(setLanguage);
  2631. // bind events
  2632. $burnAfterReading.change(changeBurnAfterReading);
  2633. $openDiscussionOption.change(changeOpenDiscussion);
  2634. $newButton.click(clickNewPaste);
  2635. $sendButton.click(PasteEncrypter.sendPaste);
  2636. $cloneButton.click(Controller.clonePaste);
  2637. $rawTextButton.click(rawText);
  2638. $fileRemoveButton.click(removeAttachment);
  2639. // bootstrap template drop downs
  2640. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2641. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2642. // initiate default state of checkboxes
  2643. changeBurnAfterReading();
  2644. changeOpenDiscussion();
  2645. // get default value from template or fall back to set value
  2646. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2647. }
  2648. return me;
  2649. })(window, document);
  2650. /**
  2651. * Responsible for AJAX requests, transparently handles encryption…
  2652. *
  2653. * @name Uploader
  2654. * @class
  2655. */
  2656. var Uploader = (function () {
  2657. var me = {};
  2658. var successFunc = null,
  2659. failureFunc = null,
  2660. url,
  2661. data,
  2662. symmetricKey,
  2663. password;
  2664. /**
  2665. * public variable ('constant') for errors to prevent magic numbers
  2666. *
  2667. * @name Uploader.error
  2668. * @readonly
  2669. * @enum {Object}
  2670. */
  2671. me.error = {
  2672. okay: 0,
  2673. custom: 1,
  2674. unknown: 2,
  2675. serverError: 3
  2676. };
  2677. /**
  2678. * ajaxHeaders to send in AJAX requests
  2679. *
  2680. * @name Uploader.ajaxHeaders
  2681. * @private
  2682. * @readonly
  2683. * @enum {Object}
  2684. */
  2685. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  2686. /**
  2687. * called after successful upload
  2688. *
  2689. * @name Uploader.checkCryptParameters
  2690. * @private
  2691. * @function
  2692. * @throws {string}
  2693. */
  2694. function checkCryptParameters()
  2695. {
  2696. // workaround for this nasty 'bug' in ECMAScript
  2697. // see https://stackoverflow.com/questions/18808226/why-is-typeof-null-object
  2698. var typeOfKey = typeof symmetricKey;
  2699. if (symmetricKey === null) {
  2700. typeOfKey = 'null';
  2701. }
  2702. // in case of missing preparation, throw error
  2703. switch (typeOfKey) {
  2704. case 'string':
  2705. // already set, all right
  2706. return;
  2707. case 'null':
  2708. // needs to be generated auto-generate
  2709. symmetricKey = CryptTool.getSymmetricKey();
  2710. break;
  2711. default:
  2712. console.error('current invalid symmetricKey:', symmetricKey);
  2713. throw 'symmetricKey is invalid, probably the module was not prepared';
  2714. }
  2715. // password is optional
  2716. }
  2717. /**
  2718. * called after successful upload
  2719. *
  2720. * @name Uploader.success
  2721. * @private
  2722. * @function
  2723. * @param {int} status
  2724. * @param {int} result - optional
  2725. */
  2726. function success(status, result)
  2727. {
  2728. // add useful data to result
  2729. result.encryptionKey = symmetricKey;
  2730. result.requestData = data;
  2731. if (successFunc !== null) {
  2732. successFunc(status, result);
  2733. }
  2734. }
  2735. /**
  2736. * called after a upload failure
  2737. *
  2738. * @name Uploader.fail
  2739. * @private
  2740. * @function
  2741. * @param {int} status - internal code
  2742. * @param {int} result - original error code
  2743. */
  2744. function fail(status, result)
  2745. {
  2746. if (failureFunc !== null) {
  2747. failureFunc(status, result);
  2748. }
  2749. }
  2750. /**
  2751. * actually uploads the data
  2752. *
  2753. * @name Uploader.run
  2754. * @function
  2755. */
  2756. me.run = function()
  2757. {
  2758. $.ajax({
  2759. type: 'POST',
  2760. url: url,
  2761. data: data,
  2762. dataType: 'json',
  2763. headers: ajaxHeaders,
  2764. success: function(result) {
  2765. if (result.status === 0) {
  2766. success(0, result);
  2767. } else if (result.status === 1) {
  2768. fail(1, result);
  2769. } else {
  2770. fail(2, result);
  2771. }
  2772. }
  2773. })
  2774. .fail(function(jqXHR, textStatus, errorThrown) {
  2775. console.error(textStatus, errorThrown);
  2776. fail(3, jqXHR);
  2777. });
  2778. }
  2779. /**
  2780. * set success function
  2781. *
  2782. * @name Uploader.setUrl
  2783. * @function
  2784. * @param {function} newUrl
  2785. */
  2786. me.setUrl = function(newUrl)
  2787. {
  2788. url = newUrl;
  2789. }
  2790. /**
  2791. * sets the password to use (first value) and optionally also the
  2792. * encryption key (not recommend, it is automatically generated).
  2793. *
  2794. * Note: Call this after prepare() as prepare() resets these values.
  2795. *
  2796. * @name Uploader.setCryptValues
  2797. * @function
  2798. * @param {string} newPassword
  2799. * @param {string} newKey - optional
  2800. */
  2801. me.setCryptParameters = function(newPassword, newKey)
  2802. {
  2803. password = newPassword;
  2804. if (typeof newKey !== 'undefined') {
  2805. symmetricKey = newKey;
  2806. }
  2807. }
  2808. /**
  2809. * set success function
  2810. *
  2811. * @name Uploader.setSuccess
  2812. * @function
  2813. * @param {function} func
  2814. */
  2815. me.setSuccess = function(func)
  2816. {
  2817. successFunc = func;
  2818. }
  2819. /**
  2820. * set failure function
  2821. *
  2822. * @name Uploader.setFailure
  2823. * @function
  2824. * @param {function} func
  2825. */
  2826. me.setFailure = function(func)
  2827. {
  2828. failureFunc = func;
  2829. }
  2830. /**
  2831. * prepares a new upload
  2832. *
  2833. * Call this when doing a new upload to reset any data from potential
  2834. * previous uploads. Must be called before any other method of this
  2835. * module.
  2836. *
  2837. * @name Uploader.prepare
  2838. * @function
  2839. * @return {object}
  2840. */
  2841. me.prepare = function()
  2842. {
  2843. // entropy should already be checked!
  2844. // reset password
  2845. password = '';
  2846. // reset key, so it a new one is generated when it is used
  2847. symmetricKey = null;
  2848. // reset data
  2849. successFunc = null;
  2850. failureFunc = null;
  2851. url = Helper.baseUri();
  2852. data = {};
  2853. }
  2854. /**
  2855. * encrypts and sets the data
  2856. *
  2857. * @name Uploader.setData
  2858. * @function
  2859. * @param {string} index
  2860. * @param {mixed} element
  2861. */
  2862. me.setData = function(index, element)
  2863. {
  2864. checkCryptParameters();
  2865. data[index] = CryptTool.cipher(symmetricKey, password, element);
  2866. }
  2867. /**
  2868. * set the additional metadata to send unencrypted
  2869. *
  2870. * @name Uploader.setUnencryptedData
  2871. * @function
  2872. * @param {string} index
  2873. * @param {mixed} element
  2874. */
  2875. me.setUnencryptedData = function(index, element)
  2876. {
  2877. data[index] = element;
  2878. }
  2879. /**
  2880. * set the additional metadata to send unencrypted passed at once
  2881. *
  2882. * @name Uploader.setUnencryptedData
  2883. * @function
  2884. * @param {object} newData
  2885. */
  2886. me.setUnencryptedBulkData = function(newData)
  2887. {
  2888. $.extend(data, newData);
  2889. }
  2890. /**
  2891. * Helper, which parses shows a general error message based on the result of the Uploader
  2892. *
  2893. * @name Uploader.parseUploadError
  2894. * @function
  2895. * @param {int} status
  2896. * @param {object} data
  2897. * @param {string} doThisThing - a human description of the action, which was tried
  2898. * @return {array}
  2899. */
  2900. me.parseUploadError = function(status, data, doThisThing) {
  2901. var errorArray;
  2902. switch (status) {
  2903. case me.error['custom']:
  2904. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  2905. break;
  2906. case me.error['unknown']:
  2907. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  2908. break;
  2909. case me.error['serverError']:
  2910. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  2911. break;
  2912. default:
  2913. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  2914. break;
  2915. }
  2916. return errorArray;
  2917. }
  2918. /**
  2919. * init Uploader
  2920. *
  2921. * @name Uploader.init
  2922. * @function
  2923. */
  2924. me.init = function()
  2925. {
  2926. // nothing yet
  2927. }
  2928. return me;
  2929. })();
  2930. /**
  2931. * (controller) Responsible for encrypting paste and sending it to server.
  2932. *
  2933. * Does upload, encryption is done transparently by Uploader.
  2934. *
  2935. * @name PasteEncrypter
  2936. * @class
  2937. */
  2938. var PasteEncrypter = (function () {
  2939. var me = {};
  2940. var requirementsChecked = false;
  2941. /**
  2942. * checks whether there is a suitable amount of entrophy
  2943. *
  2944. * @name PasteEncrypter.checkRequirements
  2945. * @private
  2946. * @function
  2947. * @param {function} retryCallback - the callback to execute to retry the upload
  2948. * @return {bool}
  2949. */
  2950. function checkRequirements(retryCallback) {
  2951. // skip double requirement checks
  2952. if (requirementsChecked === true) {
  2953. return true;
  2954. }
  2955. if (!CryptTool.isEntropyReady()) {
  2956. // display a message and wait
  2957. Alert.showStatus('Please move your mouse for more entropy…');
  2958. CryptTool.addEntropySeedListener(retryCallback);
  2959. return false;
  2960. }
  2961. requirementsChecked = true;
  2962. return true;
  2963. }
  2964. /**
  2965. * called after successful paste upload
  2966. *
  2967. * @name PasteEncrypter.showCreatedPaste
  2968. * @private
  2969. * @function
  2970. * @param {int} status
  2971. * @param {object} data
  2972. */
  2973. function showCreatedPaste(status, data) {
  2974. Alert.hideLoading();
  2975. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  2976. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  2977. Alert.hideMessages();
  2978. // show notification
  2979. PasteStatus.createPasteNotification(url, deleteUrl)
  2980. // show new URL in browser bar
  2981. history.pushState({type: 'newpaste'}, document.title, url);
  2982. TopNav.showViewButtons();
  2983. TopNav.hideRawButton();
  2984. Editor.hide();
  2985. // parse and show text
  2986. // (preparation already done in me.sendPaste())
  2987. PasteViewer.run();
  2988. }
  2989. /**
  2990. * called after successful comment upload
  2991. *
  2992. * @name PasteEncrypter.showUploadedComment
  2993. * @private
  2994. * @function
  2995. * @param {int} status
  2996. * @param {object} data
  2997. */
  2998. function showUploadedComment(status, data) {
  2999. // show success message
  3000. // Alert.showStatus('Comment posted.');
  3001. // reload paste
  3002. Controller.refreshPaste(function () {
  3003. // highlight sent comment
  3004. DiscussionViewer.highlightComment(data.id, true);
  3005. // reset error handler
  3006. Alert.setCustomHandler(null);
  3007. });
  3008. }
  3009. /**
  3010. * adds attachments to the Uploader
  3011. *
  3012. * @name PasteEncrypter.encryptAttachments
  3013. * @private
  3014. * @function
  3015. * @param {File|null|undefined} file - optional, falls back to cloned attachment
  3016. * @param {function} callback - excuted when action is successful
  3017. */
  3018. function encryptAttachments(file, callback) {
  3019. if (typeof file !== 'undefined' && file !== null) {
  3020. // check file reader requirements for upload
  3021. if (typeof FileReader === 'undefined') {
  3022. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  3023. // cancels process as it does not execute callback
  3024. return;
  3025. }
  3026. var reader = new FileReader();
  3027. // closure to capture the file information
  3028. reader.onload = function(event) {
  3029. Uploader.setData('attachment', event.target.result);
  3030. Uploader.setData('attachmentname', file.name);
  3031. // run callback
  3032. return callback();
  3033. }
  3034. // actually read first file
  3035. reader.readAsDataURL(file);
  3036. } else if (AttachmentViewer.hasAttachment()) {
  3037. // fall back to cloned part
  3038. var attachment = AttachmentViewer.getAttachment();
  3039. Uploader.setData('attachment', attachment[0]);
  3040. Uploader.setData('attachmentname', attachment[1]);
  3041. return callback();
  3042. } else {
  3043. // if there are no attachments, this is of course still successful
  3044. return callback();
  3045. }
  3046. }
  3047. /**
  3048. * send a reply in a discussion
  3049. *
  3050. * @name PasteEncrypter.sendComment
  3051. * @function
  3052. */
  3053. me.sendComment = function()
  3054. {
  3055. Alert.hideMessages();
  3056. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3057. // UI loading state
  3058. TopNav.hideAllButtons();
  3059. Alert.showLoading('Sending comment…', 0, 'cloud-upload');
  3060. // get data, note that "var [x, y] = " structures aren't supported in all JS environments
  3061. var replyData = DiscussionViewer.getReplyData(),
  3062. plainText = replyData[0],
  3063. nickname = replyData[1],
  3064. parentid = DiscussionViewer.getReplyCommentId();
  3065. // do not send if there is no data
  3066. if (plainText.length === 0) {
  3067. // revert loading status…
  3068. Alert.hideLoading();
  3069. Alert.setCustomHandler(null);
  3070. TopNav.showViewButtons();
  3071. return;
  3072. }
  3073. // check entropy
  3074. if (!checkRequirements(function () {
  3075. me.sendComment();
  3076. })) {
  3077. return; // to prevent multiple executions
  3078. }
  3079. Alert.showLoading(null, 10);
  3080. // prepare Uploader
  3081. Uploader.prepare();
  3082. Uploader.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3083. // set success/fail functions
  3084. Uploader.setSuccess(showUploadedComment);
  3085. Uploader.setFailure(function (status, data) {
  3086. // revert loading status…
  3087. Alert.hideLoading();
  3088. TopNav.showViewButtons();
  3089. // show error message
  3090. Alert.showError(Uploader.parseUploadError(status, data, 'post comment'));
  3091. // reset error handler
  3092. Alert.setCustomHandler(null);
  3093. });
  3094. // fill it with unencrypted params
  3095. Uploader.setUnencryptedData('pasteid', Model.getPasteId());
  3096. if (typeof parentid === 'undefined') {
  3097. // if parent id is not set, this is the top-most comment, so use
  3098. // paste id as parent @TODO is this really good?
  3099. Uploader.setUnencryptedData('parentid', Model.getPasteId());
  3100. } else {
  3101. Uploader.setUnencryptedData('parentid', parentid);
  3102. }
  3103. // encrypt data
  3104. Uploader.setData('data', plainText);
  3105. if (nickname.length > 0) {
  3106. Uploader.setData('nickname', nickname);
  3107. }
  3108. Uploader.run();
  3109. }
  3110. /**
  3111. * sends a new paste to server
  3112. *
  3113. * @name PasteEncrypter.sendPaste
  3114. * @function
  3115. */
  3116. me.sendPaste = function()
  3117. {
  3118. // hide previous (error) messages
  3119. Controller.hideStatusMessages();
  3120. // UI loading state
  3121. TopNav.hideAllButtons();
  3122. Alert.showLoading('Sending paste…', 0, 'cloud-upload');
  3123. TopNav.collapseBar();
  3124. // get data
  3125. var plainText = Editor.getText(),
  3126. format = PasteViewer.getFormat(),
  3127. files = TopNav.getFileList();
  3128. // do not send if there is no data
  3129. if (plainText.length === 0 && files === null) {
  3130. // revert loading status…
  3131. Alert.hideLoading();
  3132. TopNav.showCreateButtons();
  3133. return;
  3134. }
  3135. Alert.showLoading(null, 10);
  3136. // check entropy
  3137. if (!checkRequirements(function () {
  3138. me.sendPaste();
  3139. })) {
  3140. return; // to prevent multiple executions
  3141. }
  3142. // prepare Uploader
  3143. Uploader.prepare();
  3144. Uploader.setCryptParameters(TopNav.getPassword());
  3145. // set success/fail functions
  3146. Uploader.setSuccess(showCreatedPaste);
  3147. Uploader.setFailure(function (status, data) {
  3148. // revert loading status…
  3149. Alert.hideLoading();
  3150. TopNav.showCreateButtons();
  3151. // show error message
  3152. Alert.showError(Uploader.parseUploadError(status, data, 'create paste'));
  3153. });
  3154. // fill it with unencrypted submitted options
  3155. Uploader.setUnencryptedBulkData({
  3156. expire: TopNav.getExpiration(),
  3157. formatter: format,
  3158. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  3159. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  3160. });
  3161. // prepare PasteViewer for later preview
  3162. PasteViewer.setText(plainText);
  3163. PasteViewer.setFormat(format);
  3164. // encrypt cipher data
  3165. Uploader.setData('data', plainText);
  3166. // encrypt attachments
  3167. encryptAttachments(
  3168. files === null ? null : files[0],
  3169. function () {
  3170. // send data
  3171. Uploader.run();
  3172. }
  3173. );
  3174. }
  3175. /**
  3176. * initialize
  3177. *
  3178. * @name PasteEncrypter.init
  3179. * @function
  3180. */
  3181. me.init = function()
  3182. {
  3183. // nothing yet
  3184. }
  3185. return me;
  3186. })();
  3187. /**
  3188. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3189. *
  3190. * Only decryption, no download.
  3191. *
  3192. * @name PasteDecrypter
  3193. * @class
  3194. */
  3195. var PasteDecrypter = (function () {
  3196. var me = {};
  3197. /**
  3198. * decrypt data or prompts for password in cvase of failure
  3199. *
  3200. * @name PasteDecrypter.decryptOrPromptPassword
  3201. * @private
  3202. * @function
  3203. * @param {string} key
  3204. * @param {string} password - optional, may be an empty string
  3205. * @param {string} cipherdata
  3206. * @throws {string}
  3207. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3208. */
  3209. function decryptOrPromptPassword(key, password, cipherdata)
  3210. {
  3211. // try decryption without password
  3212. var plaindata = CryptTool.decipher(key, password, cipherdata);
  3213. // if it fails, request password
  3214. if (plaindata.length === 0 && password.length === 0) {
  3215. // try to get cached password first
  3216. password = Prompt.getPassword();
  3217. // if password is there, re-try
  3218. if (password.length === 0) {
  3219. password = Prompt.requestPassword();
  3220. }
  3221. // recursive
  3222. // note: an infinite loop is prevented as the previous if
  3223. // clause checks whether a password is already set and ignores
  3224. // errors when a password has been passed
  3225. return decryptOrPromptPassword.apply(key, password, cipherdata);
  3226. }
  3227. // if all tries failed, we can only return an error
  3228. if (plaindata.length === 0) {
  3229. throw 'failed to decipher data';
  3230. }
  3231. return plaindata;
  3232. }
  3233. /**
  3234. * decrypt the actual paste text
  3235. *
  3236. * @name PasteDecrypter.decryptOrPromptPassword
  3237. * @private
  3238. * @function
  3239. * @param {object} paste - paste data in object form
  3240. * @param {string} key
  3241. * @param {string} password
  3242. * @param {bool} ignoreError - ignore decryption errors iof set to true
  3243. * @return {bool} whether action was successful
  3244. * @throws {string}
  3245. */
  3246. function decryptPaste(paste, key, password, ignoreError)
  3247. {
  3248. var plaintext
  3249. if (ignoreError === true) {
  3250. plaintext = CryptTool.decipher(key, password, paste.data);
  3251. } else {
  3252. try {
  3253. plaintext = decryptOrPromptPassword(key, password, paste.data);
  3254. } catch (err) {
  3255. throw 'failed to decipher paste text: ' + err
  3256. }
  3257. if (plaintext === false) {
  3258. return false;
  3259. }
  3260. }
  3261. // on success show paste
  3262. PasteViewer.setFormat(paste.meta.formatter);
  3263. PasteViewer.setText(plaintext);
  3264. // trigger to show the text (attachment loaded afterwards)
  3265. PasteViewer.run();
  3266. return true;
  3267. }
  3268. /**
  3269. * decrypts any attachment
  3270. *
  3271. * @name PasteDecrypter.decryptAttachment
  3272. * @private
  3273. * @function
  3274. * @param {object} paste - paste data in object form
  3275. * @param {string} key
  3276. * @param {string} password
  3277. * @return {bool} whether action was successful
  3278. * @throws {string}
  3279. */
  3280. function decryptAttachment(paste, key, password)
  3281. {
  3282. // decrypt attachment
  3283. try {
  3284. var attachment = decryptOrPromptPassword(key, password, paste.attachment);
  3285. } catch (err) {
  3286. throw 'failed to decipher attachment: ' + err
  3287. }
  3288. if (attachment === false) {
  3289. return false;
  3290. }
  3291. // decrypt attachment name
  3292. var attachmentName;
  3293. if (paste.attachmentname) {
  3294. try {
  3295. attachmentName = decryptOrPromptPassword(key, password, paste.attachmentname);
  3296. } catch (err) {
  3297. throw 'failed to decipher attachment name: ' + err
  3298. }
  3299. if (attachmentName === false) {
  3300. return false;
  3301. }
  3302. }
  3303. AttachmentViewer.setAttachment(attachment, attachmentName);
  3304. AttachmentViewer.showAttachment();
  3305. return true;
  3306. }
  3307. /**
  3308. * decrypts all comments and shows them
  3309. *
  3310. * @name PasteDecrypter.decryptComments
  3311. * @private
  3312. * @function
  3313. * @param {object} paste - paste data in object form
  3314. * @param {string} key
  3315. * @param {string} password
  3316. * @return {bool} whether action was successful
  3317. */
  3318. function decryptComments(paste, key, password)
  3319. {
  3320. // remove potentially previous discussion
  3321. DiscussionViewer.prepareNewDisucssion();
  3322. // iterate over comments
  3323. for (var i = 0; i < paste.comments.length; ++i) {
  3324. var comment = paste.comments[i];
  3325. DiscussionViewer.addComment(
  3326. comment,
  3327. CryptTool.decipher(key, password, comment.data),
  3328. CryptTool.decipher(key, password, comment.meta.nickname)
  3329. );
  3330. }
  3331. DiscussionViewer.finishDiscussion();
  3332. DiscussionViewer.showDiscussion();
  3333. return true;
  3334. }
  3335. /**
  3336. * show decrypted text in the display area, including discussion (if open)
  3337. *
  3338. * @name PasteDecrypter.run
  3339. * @function
  3340. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  3341. */
  3342. me.run = function(paste)
  3343. {
  3344. Alert.hideMessages();
  3345. Alert.showLoading('Decrypting paste…', 0, 'cloud-download'); // @TODO icon maybe rotation-lock, but needs full Glyphicons
  3346. if (typeof paste === 'undefined') {
  3347. paste = $.parseJSON(Model.getCipherData());
  3348. }
  3349. var key = Model.getPasteKey(),
  3350. password = Prompt.getPassword();
  3351. if (PasteViewer.isPrettyPrinted()) {
  3352. console.error('Too pretty! (don\'t know why this check)'); //@TODO
  3353. return;
  3354. }
  3355. // try to decrypt the paste
  3356. try {
  3357. // decrypt attachments
  3358. if (paste.attachment) {
  3359. // try to decrypt paste and if it fails (because the password is
  3360. // missing) return to let JS continue and wait for user
  3361. if (!decryptAttachment(paste, key, password)) {
  3362. return;
  3363. }
  3364. // ignore empty paste, as this is allowed when pasting attachments
  3365. decryptPaste(paste, key, password, true);
  3366. } else {
  3367. decryptPaste(paste, key, password);
  3368. }
  3369. // shows the remaining time (until) deletion
  3370. PasteStatus.showRemainingTime(paste.meta);
  3371. // if the discussion is opened on this paste, display it
  3372. if (paste.meta.opendiscussion) {
  3373. decryptComments(paste, key, password);
  3374. }
  3375. Alert.hideLoading();
  3376. TopNav.showViewButtons();
  3377. } catch(err) {
  3378. Alert.hideLoading();
  3379. // log and show error
  3380. console.error(err);
  3381. Alert.showError('Could not decrypt data (Wrong key?)');
  3382. }
  3383. }
  3384. /**
  3385. * initialize
  3386. *
  3387. * @name PasteDecrypter.init
  3388. * @function
  3389. */
  3390. me.init = function()
  3391. {
  3392. // nothing yet
  3393. }
  3394. return me;
  3395. })();
  3396. /**
  3397. * (controller) main PrivateBin logic
  3398. *
  3399. * @name Controller
  3400. * @param {object} window
  3401. * @param {object} document
  3402. * @class
  3403. */
  3404. var Controller = (function (window, document) {
  3405. var me = {};
  3406. /**
  3407. * hides all status messages no matter which module showed them
  3408. *
  3409. * @name Controller.hideStatusMessages
  3410. * @function
  3411. */
  3412. me.hideStatusMessages = function()
  3413. {
  3414. PasteStatus.hideMessages();
  3415. Alert.hideMessages();
  3416. }
  3417. /**
  3418. * creates a new paste
  3419. *
  3420. * @name Controller.newPaste
  3421. * @function
  3422. */
  3423. me.newPaste = function()
  3424. {
  3425. // Important: This *must not* run Alert.hideMessages() as previous
  3426. // errors from viewing a paste should be shown.
  3427. TopNav.hideAllButtons();
  3428. Alert.showLoading('Preparing new paste…', 0, 'time');
  3429. PasteStatus.hideMessages();
  3430. PasteViewer.hide();
  3431. Editor.resetInput();
  3432. Editor.show();
  3433. Editor.focusInput();
  3434. TopNav.showCreateButtons();
  3435. Alert.hideLoading();
  3436. }
  3437. /**
  3438. * shows the loaded paste
  3439. *
  3440. * @name Controller.showPaste
  3441. * @function
  3442. */
  3443. me.showPaste = function()
  3444. {
  3445. try {
  3446. Model.getPasteId();
  3447. Model.getPasteKey();
  3448. } catch (err) {
  3449. console.error(err);
  3450. // missing decryption key (or paste ID) in URL?
  3451. if (window.location.hash.length === 0) {
  3452. 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?)');
  3453. // @TODO adjust error message as it is less specific now, probably include thrown exception for a detailed error
  3454. return;
  3455. }
  3456. }
  3457. // show proper elements on screen
  3458. PasteDecrypter.run();
  3459. }
  3460. /**
  3461. * refreshes the loaded paste to show potential new data
  3462. *
  3463. * @name Controller.refreshPaste
  3464. * @function
  3465. * @param {function} callback
  3466. */
  3467. me.refreshPaste = function(callback)
  3468. {
  3469. // save window position to restore it later
  3470. var orgPosition = $(window).scrollTop();
  3471. Uploader.prepare();
  3472. Uploader.setUrl(Helper.baseUri() + '?' + Model.getPasteId());
  3473. Uploader.setFailure(function (status, data) {
  3474. // revert loading status…
  3475. Alert.hideLoading();
  3476. TopNav.showViewButtons();
  3477. // show error message
  3478. Alert.showError(Uploader.parseUploadError(status, data, 'refresh display'));
  3479. })
  3480. Uploader.setSuccess(function (status, data) {
  3481. PasteDecrypter.run(data);
  3482. // restore position
  3483. window.scrollTo(0, orgPosition);
  3484. callback();
  3485. })
  3486. Uploader.run();
  3487. }
  3488. /**
  3489. * clone the current paste
  3490. *
  3491. * @name Controller.clonePaste
  3492. * @function
  3493. * @param {Event} event
  3494. */
  3495. me.clonePaste = function(event)
  3496. {
  3497. TopNav.collapseBar();
  3498. TopNav.hideAllButtons();
  3499. Alert.showLoading('Cloning paste…', 0, 'transfer');
  3500. // hide messages from previous paste
  3501. me.hideStatusMessages();
  3502. // erase the id and the key in url
  3503. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3504. if (AttachmentViewer.hasAttachment()) {
  3505. AttachmentViewer.moveAttachmentTo(
  3506. TopNav.getCustomAttachment(),
  3507. 'Cloned: \'%s\''
  3508. );
  3509. TopNav.hideFileSelector();
  3510. AttachmentViewer.hideAttachment();
  3511. // NOTE: it also looks nice without removing the attachment
  3512. // but for a consistent display we remove it…
  3513. AttachmentViewer.hideAttachmentPreview();
  3514. TopNav.showCustomAttachment();
  3515. // show another status message to make the user aware that the
  3516. // file was cloned too!
  3517. Alert.showStatus(
  3518. [
  3519. 'The cloned file \'%s\' was attached to this paste.',
  3520. AttachmentViewer.getAttachment()[1]
  3521. ], 'copy', true, true);
  3522. }
  3523. Editor.setText(PasteViewer.getText())
  3524. PasteViewer.hide();
  3525. Editor.show();
  3526. Alert.hideLoading();
  3527. TopNav.showCreateButtons();
  3528. }
  3529. /**
  3530. * removes a saved paste
  3531. *
  3532. * @name Controller.removePaste
  3533. * @function
  3534. * @param {string} pasteId
  3535. * @param {string} deleteToken
  3536. */
  3537. me.removePaste = function(pasteId, deleteToken) {
  3538. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3539. // so we use a POST request
  3540. Uploader.prepare();
  3541. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3542. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3543. Uploader.setFailure(function () {
  3544. Controller.showError(I18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  3545. })
  3546. Uploader.run();
  3547. }
  3548. /**
  3549. * application start
  3550. *
  3551. * @name Controller.init
  3552. * @function
  3553. */
  3554. me.init = function()
  3555. {
  3556. // first load translations
  3557. I18n.loadTranslations();
  3558. // initialize other modules/"classes"
  3559. Alert.init();
  3560. Model.init();
  3561. AttachmentViewer.init();
  3562. DiscussionViewer.init();
  3563. Editor.init();
  3564. PasteDecrypter.init();
  3565. PasteEncrypter.init();
  3566. PasteStatus.init();
  3567. PasteViewer.init();
  3568. Prompt.init();
  3569. TopNav.init();
  3570. UiHelper.init();
  3571. Uploader.init();
  3572. // display an existing paste
  3573. if (Model.hasCipherData()) {
  3574. return me.showPaste();
  3575. }
  3576. // otherwise create a new paste
  3577. me.newPaste();
  3578. }
  3579. return me;
  3580. })(window, document);
  3581. return {
  3582. Helper: Helper,
  3583. I18n: I18n,
  3584. CryptTool: CryptTool,
  3585. Model: Model,
  3586. UiHelper: UiHelper,
  3587. Alert: Alert,
  3588. PasteStatus: PasteStatus,
  3589. Prompt: Prompt,
  3590. Editor: Editor,
  3591. PasteViewer: PasteViewer,
  3592. AttachmentViewer: AttachmentViewer,
  3593. DiscussionViewer: DiscussionViewer,
  3594. TopNav: TopNav,
  3595. Uploader: Uploader,
  3596. PasteEncrypter: PasteEncrypter,
  3597. PasteDecrypter: PasteDecrypter,
  3598. Controller: Controller
  3599. };
  3600. }(jQuery, sjcl, Base64, RawDeflate);