1
0

privatebin.js 128 KB

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