privatebin.js 127 KB

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