privatebin.js 128 KB

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