privatebin.js 149 KB

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