privatebin.js 121 KB

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