privatebin.js 148 KB

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