privatebin.js 146 KB

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