privatebin.js 120 KB

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