1
0

privatebin.js 154 KB

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