privatebin.js 147 KB

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