privatebin.js 121 KB

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