privatebin.js 134 KB

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