privatebin.js 133 KB

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