privatebin.js 150 KB

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