Completed
Branch master (79509a)
by El
16:32 queued 06:47
created

js/privatebin.js (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
/**
2
 * PrivateBin
3
 *
4
 * a zero-knowledge paste bin
5
 *
6
 * @link      https://github.com/PrivateBin/PrivateBin
7
 * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
8
 * @license   http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
9
 * @version   0.22
10
 */
11
12
'use strict';
13
14
// Immediately start random number generator collector.
15
sjcl.random.startCollectors();
16
17
$(function() {
18
    /**
19
     * static helper methods
20
     */
21
    var helper = {
22
        /**
23
         * Converts a duration (in seconds) into human friendly approximation.
24
         *
25
         * @param int seconds
26
         * @return array
27
         */
28
        secondsToHuman: function(seconds)
29
        {
30
            if (seconds < 60)
31
            {
32
                var v = Math.floor(seconds);
33
                return [v, 'second'];
34
            }
35
            if (seconds < 60 * 60)
36
            {
37
                var v = Math.floor(seconds / 60);
38
                return [v, 'minute'];
39
            }
40
            if (seconds < 60 * 60 * 24)
41
            {
42
                var v = Math.floor(seconds / (60 * 60));
43
                return [v, 'hour'];
44
            }
45
            // If less than 2 months, display in days:
46
            if (seconds < 60 * 60 * 24 * 60)
47
            {
48
                var v = Math.floor(seconds / (60 * 60 * 24));
49
                return [v, 'day'];
50
            }
51
            var v = Math.floor(seconds / (60 * 60 * 24 * 30));
52
            return [v, 'month'];
53
        },
54
55
        /**
56
         * Converts an associative array to an encoded string
57
         * for appending to the anchor.
58
         *
59
         * @param object associative_array Object to be serialized
60
         * @return string
61
         */
62
        hashToParameterString: function(associativeArray)
63
        {
64
            var parameterString = '';
65
            for (key in associativeArray)
66
            {
67
                if(parameterString === '')
68
                {
69
                    parameterString = encodeURIComponent(key);
70
                    parameterString += '=' + encodeURIComponent(associativeArray[key]);
71
                }
72
                else
73
                {
74
                    parameterString += '&' + encodeURIComponent(key);
75
                    parameterString += '=' + encodeURIComponent(associativeArray[key]);
76
                }
77
            }
78
            // padding for URL shorteners
79
            parameterString += '&p=p';
80
81
            return parameterString;
82
        },
83
84
        /**
85
         * Converts a string to an associative array.
86
         *
87
         * @param string parameter_string String containing parameters
88
         * @return object
89
         */
90
        parameterStringToHash: function(parameterString)
91
        {
92
            var parameterHash = {};
93
            var parameterArray = parameterString.split('&');
94
            for (var i = 0; i < parameterArray.length; i++)
95
            {
96
                var pair = parameterArray[i].split('=');
97
                var key = decodeURIComponent(pair[0]);
98
                var value = decodeURIComponent(pair[1]);
99
                parameterHash[key] = value;
100
            }
101
102
            return parameterHash;
103
        },
104
105
        /**
106
         * Get an associative array of the parameters found in the anchor
107
         *
108
         * @return object
109
         */
110
        getParameterHash: function()
111
        {
112
            var hashIndex = window.location.href.indexOf('#');
113
            if (hashIndex >= 0)
114
            {
115
                return this.parameterStringToHash(window.location.href.substring(hashIndex + 1));
116
            }
117
            else
118
            {
119
                return {};
120
            }
121
        },
122
123
        /**
124
         * Convert all applicable characters to HTML entities
125
         *
126
         * @param string str
127
         * @return string encoded string
128
         */
129
        htmlEntities: function(str)
130
        {
131
            return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
132
        },
133
134
        /**
135
         * Text range selection.
136
         * From: http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse
137
         *
138
         * @param string element : Indentifier of the element to select (id="").
139
         */
140
        selectText: function(element)
141
        {
142
            var doc = document,
143
                text = doc.getElementById(element),
144
                range,
145
                selection;
146
147
            // MS
148
            if (doc.body.createTextRange)
149
            {
150
                range = doc.body.createTextRange();
151
                range.moveToElementText(text);
152
                range.select();
153
            }
154
            // all others
155
            else if (window.getSelection)
156
            {
157
                selection = window.getSelection();
158
                range = doc.createRange();
159
                range.selectNodeContents(text);
160
                selection.removeAllRanges();
161
                selection.addRange(range);
162
            }
163
        },
164
165
        /**
166
         * Set text of a DOM element (required for IE)
167
         * This is equivalent to element.text(text)
168
         *
169
         * @param object element : a DOM element.
170
         * @param string text : the text to enter.
171
         */
172
        setElementText: function(element, text)
173
        {
174
            // For IE<10: Doesn't support white-space:pre-wrap; so we have to do this...
175
            if ($('#oldienotice').is(':visible')) {
176
                var html = this.htmlEntities(text).replace(/\n/ig,'\r\n<br>');
177
                element.html('<pre>'+html+'</pre>');
178
            }
179
            // for other (sane) browsers:
180
            else
181
            {
182
                element.text(text);
183
            }
184
        },
185
186
        /**
187
         * replace last child of element with message
188
         *
189
         * @param object element : a jQuery wrapped DOM element.
190
         * @param string message : the message to append.
191
         */
192
        setMessage: function(element, message)
193
        {
194
            var content = element.contents();
195
            if (content.length > 0)
196
            {
197
                content[content.length - 1].nodeValue = ' ' + message;
198
            }
199
            else
200
            {
201
                this.setElementText(element, message);
202
            }
203
        },
204
205
        /**
206
         * Convert URLs to clickable links.
207
         * URLs to handle:
208
         * <code>
209
         *     magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
210
         *     http://localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
211
         *     http://user:password@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
212
         * </code>
213
         *
214
         * @param object element : a jQuery DOM element.
215
         */
216
        urls2links: function(element)
217
        {
218
            var markup = '<a href="$1" rel="nofollow">$1</a>';
219
            element.html(
220
                element.html().replace(
221
                    /((http|https|ftp):\/\/[\w?=&.\/-;#@~%+-]+(?![\w\s?&.\/;#~%"=-]*>))/ig,
222
                    markup
223
                )
224
            );
225
            element.html(
226
                element.html().replace(
227
                    /((magnet):[\w?=&.\/-;#@~%+-]+)/ig,
228
                    markup
229
                )
230
            );
231
        },
232
233
        /**
234
         * minimal sprintf emulation for %s and %d formats
235
         * From: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914
236
         *
237
         * @param string format
238
         * @param mixed args one or multiple parameters injected into format string
239
         * @return string
240
         */
241
        sprintf: function()
242
        {
243
            var args = arguments;
244
            if (typeof arguments[0] == 'object') args = arguments[0];
245
            var string = args[0],
246
                i = 1;
247
            return string.replace(/%((%)|s|d)/g, function (m) {
248
                // m is the matched format, e.g. %s, %d
249
                var val = null;
250
                if (m[2]) {
251
                    val = m[2];
252
                } else {
253
                    val = args[i];
254
                    // A switch statement so that the formatter can be extended.
255
                    switch (m)
256
                    {
257
                        case '%d':
258
                            val = parseFloat(val);
259
                            if (isNaN(val)) {
260
                                val = 0;
261
                            }
262
                            break;
263
                        // Default is %s
264
                    }
265
                    ++i;
266
                }
267
                return val;
268
            });
269
        },
270
271
        /**
272
         * get value of cookie, if it was set, empty string otherwise
273
         * From: http://www.w3schools.com/js/js_cookies.asp
274
         *
275
         * @param string cname
276
         * @return string
277
         */
278
        getCookie: function(cname) {
279
            var name = cname + '=';
280
            var ca = document.cookie.split(';');
281
            for(var i = 0; i < ca.length; ++i) {
282
                var c = ca[i];
283
                while (c.charAt(0) == ' ') c = c.substring(1);
284
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
285
            }
286
            return '';
287
        }
288
    };
289
290
    /**
291
     * internationalization methods
292
     */
293
    var i18n = {
294
        /**
295
         * supported languages, minus the built in 'en'
296
         */
297
        supportedLanguages: ['de', 'fr', 'pl', 'sl', 'zh'],
298
299
        /**
300
         * translate a string, alias for translate()
301
         *
302
         * @param string $messageId
303
         * @param mixed args one or multiple parameters injected into placeholders
304
         * @return string
305
         */
306
        _: function()
307
        {
308
            return this.translate(arguments);
309
        },
310
311
        /**
312
         * translate a string
313
         *
314
         * @param string $messageId
315
         * @param mixed args one or multiple parameters injected into placeholders
316
         * @return string
317
         */
318
        translate: function()
319
        {
320
            var args = arguments, messageId, usesPlurals;
321
            if (typeof arguments[0] == 'object') args = arguments[0];
322
            if (usesPlurals = $.isArray(args[0]))
323
            {
324
                // use the first plural form as messageId, otherwise the singular
325
                messageId = (args[0].length > 1 ? args[0][1] : args[0][0]);
326
            }
327
            else
328
            {
329
                messageId = args[0];
330
            }
331
            if (messageId.length === 0) return messageId;
332
            if (!this.translations.hasOwnProperty(messageId))
333
            {
334
                if (this.language !== 'en') console.debug(
335
                    'Missing translation for: ' + messageId
336
                );
337
                this.translations[messageId] = args[0];
338
            }
339
            if (usesPlurals && $.isArray(this.translations[messageId]))
340
            {
341
                var n = parseInt(args[1] || 1),
342
                    key = this.getPluralForm(n),
343
                    maxKey = this.translations[messageId].length - 1;
344
                if (key > maxKey) key = maxKey;
345
                args[0] = this.translations[messageId][key];
346
                args[1] = n;
347
            }
348
            else
349
            {
350
                args[0] = this.translations[messageId];
351
            }
352
            return helper.sprintf(args);
353
        },
354
355
        /**
356
         * per language functions to use to determine the plural form
357
         * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
358
         *
359
         * @param int number
360
         * @return int array key
361
         */
362
        getPluralForm: function(n) {
363
            switch (this.language)
364
            {
365
                case 'fr':
366
                case 'zh':
367
                    return (n > 1 ? 1 : 0);
368
                case 'pl':
369
                    return (n === 1 ? 0 : n%10 >= 2 && n %10 <=4 && (n%100 < 10 || n%100 >= 20) ? 1 : 2);
370
                // en, de
371
                default:
372
                    return (n !== 1 ? 1 : 0);
373
            }
374
        },
375
376
        /**
377
         * load translations into cache, then execute callback function
378
         *
379
         * @param function callback
380
         */
381
        loadTranslations: function(callback)
382
        {
383
            var selectedLang = helper.getCookie('lang');
384
            var language = selectedLang.length > 0 ? selectedLang : (navigator.language || navigator.userLanguage).substring(0, 2);
385
            // note that 'en' is built in, so no translation is necessary
386
            if (this.supportedLanguages.indexOf(language) == -1)
387
            {
388
                callback();
389
            }
390
            else
391
            {
392
                $.getJSON('i18n/' + language + '.json', function(data) {
393
                    i18n.language = language;
394
                    i18n.translations = data;
395
                    callback();
396
                });
397
            }
398
        },
399
400
        /**
401
         * built in language
402
         */
403
        language: 'en',
404
405
        /**
406
         * translation cache
407
         */
408
        translations: {}
409
    };
410
411
    /**
412
     * filter methods
413
     */
414
    var filter = {
415
        /**
416
         * Compress a message (deflate compression). Returns base64 encoded data.
417
         *
418
         * @param string message
419
         * @return base64 string data
420
         */
421
        compress: function(message)
422
        {
423
            return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
424
        },
425
426
        /**
427
         * Decompress a message compressed with compress().
428
         *
429
         * @param base64 string data
430
         * @return string message
431
         */
432
        decompress: function(data)
433
        {
434
            return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
435
        },
436
437
        /**
438
         * Compress, then encrypt message with key.
439
         *
440
         * @param string key
441
         * @param string password
442
         * @param string message
443
         * @return encrypted string data
444
         */
445
        cipher: function(key, password, message)
446
        {
447
            if ((password || '').trim().length == 0)
448
            {
449
                return sjcl.encrypt(key, this.compress(message), {mode : 'gcm'});
450
            }
451
            return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), this.compress(message), {mode : 'gcm'});
452
        },
453
454
        /**
455
         * Decrypt message with key, then decompress.
456
         *
457
         * @param string key
458
         * @param string password
459
         * @param encrypted string data
460
         * @return string readable message
461
         */
462
        decipher: function(key, password, data)
463
        {
464
            if (data != undefined)
465
            {
466
                try
467
                {
468
                    return this.decompress(sjcl.decrypt(key, data));
469
                }
470
                catch(err)
471
                {
472
                    try
473
                    {
474
                        return this.decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
475
                    }
476
                    catch(err)
477
                    {}
478
                }
479
            }
480
            return '';
481
        }
482
    };
483
484
    var privatebin = {
485
        /**
486
         * headers to send in AJAX requests
487
         */
488
        headers: {'X-Requested-With': 'JSONHttpRequest'},
489
490
        /**
491
         * Get the current script location (without search or hash part of the URL).
492
         * eg. http://server.com/zero/?aaaa#bbbb --> http://server.com/zero/
493
         *
494
         * @return string current script location
495
         */
496
        scriptLocation: function()
497
        {
498
            var scriptLocation = window.location.href.substring(0,window.location.href.length
499
                - window.location.search.length - window.location.hash.length),
500
                hashIndex = scriptLocation.indexOf('#');
501
            if (hashIndex !== -1)
502
            {
503
                scriptLocation = scriptLocation.substring(0, hashIndex);
504
            }
505
            return scriptLocation;
506
        },
507
508
        /**
509
         * Get the pastes unique identifier from the URL
510
         * eg. http://server.com/zero/?c05354954c49a487#xxx --> c05354954c49a487
511
         *
512
         * @return string unique identifier
513
         */
514
        pasteID: function()
515
        {
516
            return window.location.search.substring(1);
517
        },
518
519
        /**
520
         * Return the deciphering key stored in anchor part of the URL
521
         *
522
         * @return string key
523
         */
524
        pageKey: function()
525
        {
526
            // Some web 2.0 services and redirectors add data AFTER the anchor
527
            // (such as &utm_source=...). We will strip any additional data.
528
529
            var key = window.location.hash.substring(1),    // Get key
530
                i = key.indexOf('=');
531
532
            // First, strip everything after the equal sign (=) which signals end of base64 string.
533
            if (i > -1) key = key.substring(0, i + 1);
534
535
            // If the equal sign was not present, some parameters may remain:
536
            i = key.indexOf('&');
537
            if (i > -1) key = key.substring(0, i);
538
539
            // Then add trailing equal sign if it's missing
540
            if (key.charAt(key.length - 1) !== '=') key += '=';
541
542
            return key;
543
        },
544
545
        /**
546
         * ask the user for the password and return it
547
         *
548
         * @throws error when dialog canceled
549
         * @return string password
550
         */
551
        requestPassword: function()
552
        {
553
            var password = prompt(i18n._('Please enter the password for this paste:'), '');
554
            if (password == null) throw 'password prompt canceled';
555
            if (password.length == 0) return this.requestPassword();
556
            return password;
557
        },
558
559
        /**
560
         * use given format on paste, defaults to plain text
561
         *
562
         * @param string format
563
         * @param string text
564
         */
565
        formatPaste: function(format, text)
566
        {
567
            helper.setElementText(this.clearText, text);
568
            helper.setElementText(this.prettyPrint, text);
569
            switch (format || 'plaintext')
570
            {
571
                case 'markdown':
572
                    if (typeof showdown == 'object')
573
                    {
574
                        showdown.setOption('strikethrough', true);
575
                        showdown.setOption('tables', true);
576
                        showdown.setOption('tablesHeaderId', true);
577
                        var converter = new showdown.Converter();
578
                        this.clearText.html(
579
                            converter.makeHtml(text)
580
                        );
581
                        this.clearText.removeClass('hidden');
582
                    }
583
                    this.prettyMessage.addClass('hidden');
584
                    break;
585
                case 'syntaxhighlighting':
586
                    if (typeof prettyPrintOne == 'function')
587
                    {
588
                        if (typeof prettyPrint == 'function') prettyPrint();
589
                        this.prettyPrint.html(
590
                            prettyPrintOne(text, null, true)
591
                        );
592
                    };
0 ignored issues
show
This node falls through to the next case due to this statement. Please add a comment either directly below this line or between the cases to explain.
Loading history...
593
                default:
594
                    // Convert URLs to clickable links.
595
                    helper.urls2links(this.clearText);
596
                    helper.urls2links(this.prettyPrint);
597
                    this.clearText.addClass('hidden');
598
                    if (format == 'plaintext')
599
                    {
600
                        this.prettyPrint.css('white-space', 'pre-wrap');
601
                        this.prettyPrint.css('word-break', 'normal');
602
                        this.prettyPrint.removeClass('prettyprint');
603
                    }
604
                    this.prettyMessage.removeClass('hidden');
605
            }
606
        },
607
608
        /**
609
         * Show decrypted text in the display area, including discussion (if open)
610
         *
611
         * @param string key : decryption key
612
         * @param object paste : paste object including comments to display (items = array with keys ('data','meta')
613
         */
614
        displayMessages: function(key, paste)
615
        {
616
            // Try to decrypt the paste.
617
            var password = this.passwordInput.val();
618
            if (!this.prettyPrint.hasClass('prettyprinted')) {
619
                try
620
                {
621
                    if (paste.attachment)
622
                    {
623
                        var attachment = filter.decipher(key, password, paste.attachment);
624
                        if (attachment.length == 0)
625
                        {
626
                            if (password.length == 0) password = this.requestPassword();
627
                            attachment = filter.decipher(key, password, paste.attachment);
628
                        }
629
                        if (attachment.length == 0) throw 'failed to decipher attachment';
630
631
                        if (paste.attachmentname)
632
                        {
633
                            var attachmentname = filter.decipher(key, password, paste.attachmentname);
634
                            if (attachmentname.length > 0) this.attachmentLink.attr('download', attachmentname);
635
                        }
636
                        this.attachmentLink.attr('href', attachment);
637
                        this.attachment.removeClass('hidden');
638
639
                        // if the attachment is an image, display it
640
                        var imagePrefix = 'data:image/';
641
                        if (attachment.substring(0, imagePrefix.length) == imagePrefix)
642
                        {
643
                            this.image.html(
644
                                $(document.createElement('img'))
645
                                    .attr('src', attachment)
646
                                    .attr('class', 'img-thumbnail')
647
                            );
648
                            this.image.removeClass('hidden');
649
                        }
650
                    }
651
                    var cleartext = filter.decipher(key, password, paste.data);
652
                    if (cleartext.length == 0 && password.length == 0 && !paste.attachment)
653
                    {
654
                        password = this.requestPassword();
655
                        cleartext = filter.decipher(key, password, paste.data);
656
                    }
657
                    if (cleartext.length == 0 && !paste.attachment) throw 'failed to decipher message';
658
659
                    this.passwordInput.val(password);
660
                    if (cleartext.length > 0)
661
                    {
662
                        this.formatPaste(paste.meta.formatter, cleartext);
663
                    }
664
                }
665
                catch(err)
666
                {
667
                    this.clearText.addClass('hidden');
668
                    this.prettyMessage.addClass('hidden');
669
                    this.cloneButton.addClass('hidden');
670
                    this.showError(i18n._('Could not decrypt data (Wrong key?)'));
671
                    return;
672
                }
673
            }
674
675
            // Display paste expiration / for your eyes only.
676
            if (paste.meta.expire_date)
677
            {
678
                var expiration = helper.secondsToHuman(paste.meta.remaining_time),
679
                    expirationLabel = [
680
                        'This document will expire in %d ' + expiration[1] + '.',
681
                        'This document will expire in %d ' + expiration[1] + 's.'
682
                    ];
683
                helper.setMessage(this.remainingTime, i18n._(expirationLabel, expiration[0]));
684
                this.remainingTime.removeClass('foryoureyesonly')
685
                                  .removeClass('hidden');
686
            }
687
            if (paste.meta.burnafterreading)
688
            {
689
                // unfortunately many web servers don't support DELETE (and PUT) out of the box
690
                $.ajax({
691
                    type: 'POST',
692
                    url: this.scriptLocation() + '?' + this.pasteID(),
693
                    data: {deletetoken: 'burnafterreading'},
694
                    dataType: 'json',
695
                    headers: this.headers
696
                })
697
                .fail(function() {
698
                    privatebin.showError(i18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
699
                });
700
                helper.setMessage(this.remainingTime, i18n._(
701
                    'FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.'
702
                ));
703
                this.remainingTime.addClass('foryoureyesonly')
704
                                  .removeClass('hidden');
705
                // Discourage cloning (as it can't really be prevented).
706
                this.cloneButton.addClass('hidden');
707
            }
708
709
            // If the discussion is opened on this paste, display it.
710
            if (paste.meta.opendiscussion)
711
            {
712
                this.comments.html('');
713
714
                // iterate over comments
715
                for (var i = 0; i < paste.comments.length; ++i)
716
                {
717
                    var place = this.comments;
718
                    var comment = paste.comments[i];
719
                    var cleartext = '[' + i18n._('Could not decrypt comment; Wrong key?') + ']';
720
                    try
721
                    {
722
                        cleartext = filter.decipher(key, password, comment.data);
723
                    }
724
                    catch(err)
725
                    {}
726
                    // If parent comment exists, display below (CSS will automatically shift it right.)
727
                    var cname = '#comment_' + comment.parentid;
728
729
                    // If the element exists in page
730
                    if ($(cname).length)
731
                    {
732
                        place = $(cname);
733
                    }
734
                    var divComment = $('<article><div class="comment" id="comment_' + comment.id + '">'
735
                                   + '<div class="commentmeta"><span class="nickname"></span><span class="commentdate"></span></div><div class="commentdata"></div>'
736
                                   + '<button class="btn btn-default btn-sm">' + i18n._('Reply') + '</button>'
737
                                   + '</div></article>');
738
                    divComment.find('button').click({commentid: comment.id}, $.proxy(this.openReply, this));
739
                    helper.setElementText(divComment.find('div.commentdata'), cleartext);
740
                    // Convert URLs to clickable links in comment.
741
                    helper.urls2links(divComment.find('div.commentdata'));
742
743
                    // Try to get optional nickname:
744
                    var nick = filter.decipher(key, password, comment.meta.nickname);
745
                    if (nick.length > 0)
746
                    {
747
                        divComment.find('span.nickname').text(nick);
748
                    }
749
                    else
750
                    {
751
                        divComment.find('span.nickname').html('<i>' + i18n._('Anonymous') + '</i>');
752
                    }
753
                    divComment.find('span.commentdate')
754
                              .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
755
                              .attr('title', 'CommentID: ' + comment.id);
756
757
                    // If an avatar is available, display it.
758
                    if (comment.meta.vizhash)
759
                    {
760
                        divComment.find('span.nickname')
761
                                  .before(
762
                                    '<img src="' + comment.meta.vizhash + '" class="vizhash" title="' +
763
                                    i18n._('Anonymous avatar (Vizhash of the IP address)') + '" /> '
764
                                  );
765
                    }
766
767
                    place.append(divComment);
768
                }
769
                var divComment = $(
770
                    '<div class="comment"><button class="btn btn-default btn-sm">' +
771
                    i18n._('Add comment') + '</button></div>'
772
                );
773
                divComment.find('button').click({commentid: this.pasteID()}, $.proxy(this.openReply, this));
774
                this.comments.append(divComment);
775
                this.discussion.removeClass('hidden');
776
            }
777
        },
778
779
        /**
780
         * Open the comment entry when clicking the "Reply" button of a comment.
781
         *
782
         * @param Event event
783
         */
784
        openReply: function(event)
785
        {
786
            event.preventDefault();
787
            var source = $(event.target),
788
                commentid = event.data.commentid,
789
                hint = i18n._('Optional nickname...');
790
791
            // Remove any other reply area.
792
            $('div.reply').remove();
793
            var reply = $(
794
                '<div class="reply">' +
795
                '<input type="text" id="nickname" class="form-control" title="' + hint + '" placeholder="' + hint + '" />' +
796
                '<textarea id="replymessage" class="replymessage form-control" cols="80" rows="7"></textarea>' +
797
                '<br /><button id="replybutton" class="btn btn-default btn-sm">' + i18n._('Post comment') + '</button>' +
798
                '<div id="replystatus"> </div>' +
799
                '</div>'
800
            );
801
            reply.find('button').click({parentid: commentid}, $.proxy(this.sendComment, this));
802
            source.after(reply);
803
            $('#replymessage').focus();
804
        },
805
806
        /**
807
         * Send a reply in a discussion.
808
         *
809
         * @param Event event
810
         */
811
        sendComment: function(event)
812
        {
813
            event.preventDefault();
814
            this.errorMessage.addClass('hidden');
815
            // Do not send if no data.
816
            var replyMessage = $('#replymessage');
817
            if (replyMessage.val().length == 0) return;
818
819
            this.showStatus(i18n._('Sending comment...'), true);
820
            var parentid = event.data.parentid;
821
            var cipherdata = filter.cipher(this.pageKey(), this.passwordInput.val(), replyMessage.val());
822
            var ciphernickname = '';
823
            var nick = $('#nickname').val();
824
            if (nick != '')
825
            {
826
                ciphernickname = filter.cipher(this.pageKey(), this.passwordInput.val(), nick);
827
            }
828
            var data_to_send = {
829
                data:     cipherdata,
830
                parentid: parentid,
831
                pasteid:  this.pasteID(),
832
                nickname: ciphernickname
833
            };
834
835
            $.ajax({
836
                type: 'POST',
837
                url: this.scriptLocation(),
838
                data: data_to_send,
839
                dataType: 'json',
840
                headers: this.headers,
841
                success: function(data)
842
                {
843
                    if (data.status == 0)
844
                    {
845
                        privatebin.showStatus(i18n._('Comment posted.'), false);
846
                        $.ajax({
847
                            type: 'GET',
848
                            url: privatebin.scriptLocation() + '?' + privatebin.pasteID(),
849
                            dataType: 'json',
850
                            headers: privatebin.headers,
851
                            success: function(data)
852
                            {
853
                                if (data.status == 0)
854
                                {
855
                                    privatebin.displayMessages(privatebin.pageKey(), data);
856
                                }
857
                                else if (data.status == 1)
858
                                {
859
                                    privatebin.showError(i18n._('Could not refresh display: %s', data.message));
860
                                }
861
                                else
862
                                {
863
                                    privatebin.showError(i18n._('Could not refresh display: %s', i18n._('unknown status')));
864
                                }
865
                            }
866
                        })
867
                        .fail(function() {
868
                            privatebin.showError(i18n._('Could not refresh display: %s', i18n._('server error or not responding')));
869
                        });
870
                    }
871
                    else if (data.status == 1)
872
                    {
873
                        privatebin.showError(i18n._('Could not post comment: %s', data.message));
874
                    }
875
                    else
876
                    {
877
                        privatebin.showError(i18n._('Could not post comment: %s', i18n._('unknown status')));
878
                    }
879
                }
880
            })
881
            .fail(function() {
882
                privatebin.showError(i18n._('Could not post comment: %s', i18n._('server error or not responding')));
883
            });
884
        },
885
886
        /**
887
         * Send a new paste to server
888
         *
889
         * @param Event event
890
         */
891
        sendData: function(event)
892
        {
893
            event.preventDefault();
894
            var file = document.getElementById('file'),
895
                files = (file && file.files) ? file.files : null; // FileList object
896
897
            // Do not send if no data.
898
            if (this.message.val().length == 0 && !(files && files[0])) return;
899
900
            // If sjcl has not collected enough entropy yet, display a message.
901
            if (!sjcl.random.isReady())
902
            {
903
                this.showStatus(i18n._('Sending paste (Please move your mouse for more entropy)...'), true);
904
                sjcl.random.addEventListener('seeded', function() {
905
                    this.sendData(event);
906
                });
907
                return;
908
            }
909
910
            $('.navbar-toggle').click();
911
            this.password.addClass('hidden');
912
            this.showStatus(i18n._('Sending paste...'), true);
913
914
            var randomkey = sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
915
            var cipherdata_attachment;
916
            var password = this.passwordInput.val();
917
            if(files && files[0])
918
            {
919
                if(typeof FileReader === undefined)
920
                {
921
                    this.showError(i18n._('Your browser does not support uploading encrypted files. Please use a newer browser.'));
922
                    return;
923
                }
924
                var reader = new FileReader();
925
                // Closure to capture the file information.
926
                reader.onload = (function(theFile)
927
                {
928
                    return function(e) {
929
                        privatebin.sendDataContinue(
930
                            randomkey,
931
                            filter.cipher(randomkey, password, e.target.result),
932
                            filter.cipher(randomkey, password, theFile.name)
933
                        );
934
                    };
935
                })(files[0]);
936
                reader.readAsDataURL(files[0]);
937
            }
938
            else if(this.attachmentLink.attr('href'))
939
            {
940
                this.sendDataContinue(
941
                    randomkey,
942
                    filter.cipher(randomkey, password, this.attachmentLink.attr('href')),
943
                    this.attachmentLink.attr('download')
944
                );
945
            }
946
            else
947
            {
948
                this.sendDataContinue(randomkey, '', '');
949
            }
950
        },
951
952
        /**
953
         * Send a new paste to server, step 2
954
         *
955
         * @param string randomkey
956
         * @param encrypted string cipherdata_attachment
957
         * @param encrypted string cipherdata_attachment_name
958
         */
959
        sendDataContinue: function(randomkey, cipherdata_attachment, cipherdata_attachment_name)
960
        {
961
            var cipherdata = filter.cipher(randomkey, this.passwordInput.val(), this.message.val());
962
            var data_to_send = {
963
                data:             cipherdata,
964
                expire:           $('#pasteExpiration').val(),
965
                formatter:        $('#pasteFormatter').val(),
966
                burnafterreading: this.burnAfterReading.is(':checked') ? 1 : 0,
967
                opendiscussion:   this.openDiscussion.is(':checked') ? 1 : 0
968
            };
969
            if (cipherdata_attachment.length > 0)
970
            {
971
                data_to_send.attachment = cipherdata_attachment;
972
                if (cipherdata_attachment_name.length > 0)
973
                {
974
                    data_to_send.attachmentname = cipherdata_attachment_name;
975
                }
976
            }
977
            $.ajax({
978
                type: 'POST',
979
                url: this.scriptLocation(),
980
                data: data_to_send,
981
                dataType: 'json',
982
                headers: this.headers,
983
                success: function(data)
984
                {
985
                    if (data.status == 0) {
986
                        privatebin.stateExistingPaste();
987
                        var url = privatebin.scriptLocation() + '?' + data.id + '#' + randomkey;
988
                        var deleteUrl = privatebin.scriptLocation() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
989
                        privatebin.showStatus('', false);
990
                        privatebin.errorMessage.addClass('hidden');
991
992
                        $('#pastelink').html(
993
                            i18n._(
994
                                'Your paste is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit [Ctrl]+[c] to copy)</span>',
995
                                url, url
996
                            ) + privatebin.shortenUrl(url)
997
                        );
998
                        $('#deletelink').html('<a href="' + deleteUrl + '">' + i18n._('Delete data') + '</a>');
999
                        privatebin.pasteResult.removeClass('hidden');
1000
                        // We pre-select the link so that the user only has to [Ctrl]+[c] the link.
1001
                        helper.selectText('pasteurl');
1002
                        privatebin.showStatus('', false);
1003
                        privatebin.formatPaste(data_to_send.formatter, privatebin.message.val());
1004
                    }
1005
                    else if (data.status==1)
1006
                    {
1007
                        privatebin.showError(i18n._('Could not create paste: %s', data.message));
1008
                    }
1009
                    else
1010
                    {
1011
                        privatebin.showError(i18n._('Could not create paste: %s', i18n._('unknown status')));
1012
                    }
1013
                }
1014
            })
1015
            .fail(function()
1016
            {
1017
                privatebin.showError(i18n._('Could not create paste: %s', i18n._('server error or not responding')));
1018
            });
1019
        },
1020
1021
        /**
1022
         * Check if a URL shortener was defined and create HTML containing a link to it.
1023
         *
1024
         * @param string url
1025
         * @return string html
1026
         */
1027
        shortenUrl: function(url)
1028
        {
1029
            var shortenerHtml = $('#shortenbutton');
1030
            if (shortenerHtml) {
1031
                var shortener = shortenerHtml.data('shortener');
1032
                shortenerHtml.attr(
1033
                    'onclick',
1034
                    "window.location.href = '" + shortener + encodeURIComponent(url) + "';"
1035
                );
1036
                return ' ' + $('<div />').append(shortenerHtml.clone()).html();
1037
            }
1038
            return '';
1039
        },
1040
1041
        /**
1042
         * Put the screen in "New paste" mode.
1043
         */
1044
        stateNewPaste: function()
1045
        {
1046
            this.message.text('');
1047
            this.attachment.addClass('hidden');
1048
            this.cloneButton.addClass('hidden');
1049
            this.rawTextButton.addClass('hidden');
1050
            this.remainingTime.addClass('hidden');
1051
            this.pasteResult.addClass('hidden');
1052
            this.clearText.addClass('hidden');
1053
            this.discussion.addClass('hidden');
1054
            this.prettyMessage.addClass('hidden');
1055
            this.sendButton.removeClass('hidden');
1056
            this.expiration.removeClass('hidden');
1057
            this.formatter.removeClass('hidden');
1058
            this.burnAfterReadingOption.removeClass('hidden');
1059
            this.openDisc.removeClass('hidden');
1060
            this.newButton.removeClass('hidden');
1061
            this.password.removeClass('hidden');
1062
            this.attach.removeClass('hidden');
1063
            this.message.removeClass('hidden');
1064
            this.preview.removeClass('hidden');
1065
            this.message.focus();
1066
        },
1067
1068
        /**
1069
         * Put the screen in "Existing paste" mode.
1070
         *
1071
         * @param boolean preview (optional) : tell if the preview tabs should be displayed, defaults to false.
1072
         */
1073
        stateExistingPaste: function(preview)
1074
        {
1075
            preview = preview || false;
1076
1077
            if (!preview)
1078
            {
1079
                // No "clone" for IE<10.
1080
                if ($('#oldienotice').is(":visible"))
1081
                {
1082
                    this.cloneButton.addClass('hidden');
1083
                }
1084
                else
1085
                {
1086
                    this.cloneButton.removeClass('hidden');
1087
                }
1088
1089
                this.rawTextButton.removeClass('hidden');
1090
                this.sendButton.addClass('hidden');
1091
                this.attach.addClass('hidden');
1092
                this.expiration.addClass('hidden');
1093
                this.formatter.addClass('hidden');
1094
                this.burnAfterReadingOption.addClass('hidden');
1095
                this.openDisc.addClass('hidden');
1096
                this.newButton.removeClass('hidden');
1097
                this.preview.addClass('hidden');
1098
            }
1099
1100
            this.pasteResult.addClass('hidden');
1101
            this.message.addClass('hidden');
1102
            this.clearText.addClass('hidden');
1103
            this.prettyMessage.addClass('hidden');
1104
        },
1105
1106
        /**
1107
         * If "burn after reading" is checked, disable discussion.
1108
         */
1109
        changeBurnAfterReading: function()
1110
        {
1111
            if (this.burnAfterReading.is(':checked') )
1112
            {
1113
                this.openDisc.addClass('buttondisabled');
1114
                this.openDiscussion.attr({checked: false, disabled: true});
1115
            }
1116
            else
1117
            {
1118
                this.openDisc.removeClass('buttondisabled');
1119
                this.openDiscussion.removeAttr('disabled');
1120
            }
1121
        },
1122
1123
        /**
1124
         * Reload the page.
1125
         *
1126
         * @param Event event
1127
         */
1128
        reloadPage: function(event)
1129
        {
1130
            event.preventDefault();
1131
            window.location.href = this.scriptLocation();
1132
        },
1133
1134
        /**
1135
         * Return raw text.
1136
         *
1137
         * @param Event event
1138
         */
1139
        rawText: function(event)
1140
        {
1141
            event.preventDefault();
1142
            var paste = this.clearText.html();
1143
            var newDoc = document.open('text/html', 'replace');
1144
            newDoc.write('<pre>' + paste + '</pre>');
1145
            newDoc.close();
1146
        },
1147
1148
        /**
1149
         * Clone the current paste.
1150
         *
1151
         * @param Event event
1152
         */
1153
        clonePaste: function(event)
1154
        {
1155
            event.preventDefault();
1156
            this.stateNewPaste();
1157
1158
            // Erase the id and the key in url
1159
            history.replaceState(document.title, document.title, this.scriptLocation());
1160
1161
            this.showStatus('', false);
1162
            if (this.attachmentLink.attr('href'))
1163
            {
1164
                this.clonedFile.removeClass('hidden');
1165
                this.fileWrap.addClass('hidden');
1166
            }
1167
            this.message.text(this.clearText.text());
1168
            $('.navbar-toggle').click();
1169
        },
1170
1171
        /**
1172
         * Support input of tab character.
1173
         *
1174
         * @param Event event
1175
         */
1176
        supportTabs: function(event)
1177
        {
1178
            var keyCode = event.keyCode || event.which;
1179
            // tab was pressed
1180
            if (keyCode === 9)
1181
            {
1182
                // prevent the textarea to lose focus
1183
                event.preventDefault();
1184
                // get caret position & selection
1185
                var val   = this.value,
1186
                    start = this.selectionStart,
1187
                    end   = this.selectionEnd;
1188
                // set textarea value to: text before caret + tab + text after caret
1189
                this.value = val.substring(0, start) + '\t' + val.substring(end);
1190
                // put caret at right position again
1191
                this.selectionStart = this.selectionEnd = start + 1;
1192
            }
1193
        },
1194
1195
        /**
1196
         * View the editor tab.
1197
         *
1198
         * @param Event event
1199
         */
1200
        viewEditor: function(event)
1201
        {
1202
            event.preventDefault();
1203
            this.messagePreview.parent().removeClass('active');
1204
            this.messageEdit.parent().addClass('active');
1205
            this.message.focus();
1206
            this.stateNewPaste();
1207
        },
1208
1209
        /**
1210
         * View the preview tab.
1211
         *
1212
         * @param Event event
1213
         */
1214
        viewPreview: function(event)
1215
        {
1216
            event.preventDefault();
1217
            this.messageEdit.parent().removeClass('active');
1218
            this.messagePreview.parent().addClass('active');
1219
            this.message.focus();
1220
            this.stateExistingPaste(true);
1221
            this.formatPaste($('#pasteFormatter').val(), this.message.val());
1222
        },
1223
1224
        /**
1225
         * Create a new paste.
1226
         */
1227
        newPaste: function()
1228
        {
1229
            this.stateNewPaste();
1230
            this.showStatus('', false);
1231
            this.message.text('');
1232
        },
1233
1234
        /**
1235
         * Removes an attachment.
1236
         */
1237
        removeAttachment: function()
1238
        {
1239
            this.clonedFile.addClass('hidden');
1240
            // removes the saved decrypted file data
1241
            this.attachmentLink.attr('href', '');
1242
            // the only way to deselect the file is to recreate the input
1243
            this.fileWrap.html(this.fileWrap.html());
1244
            this.fileWrap.removeClass('hidden');
1245
        },
1246
1247
        /**
1248
         * Display an error message
1249
         * (We use the same function for paste and reply to comments)
1250
         *
1251
         * @param string message : text to display
1252
         */
1253
        showError: function(message)
1254
        {
1255
            if (this.status.length)
1256
            {
1257
                this.status.addClass('errorMessage').text(message);
1258
            }
1259
            else
1260
            {
1261
                this.errorMessage.removeClass('hidden');
1262
                helper.setMessage(this.errorMessage, message);
1263
            }
1264
            this.replyStatus.addClass('errorMessage').text(message);
1265
        },
1266
1267
        /**
1268
         * Display a status message
1269
         * (We use the same function for paste and reply to comments)
1270
         *
1271
         * @param string message : text to display
1272
         * @param boolean spin (optional) : tell if the "spinning" animation should be displayed.
1273
         */
1274
        showStatus: function(message, spin)
1275
        {
1276
            this.replyStatus.removeClass('errorMessage').text(message);
1277
            if (!message)
1278
            {
1279
                this.status.html(' ');
1280
                return;
1281
            }
1282
            if (message == '')
1283
            {
1284
                this.status.html(' ');
1285
                return;
1286
            }
1287
            this.status.removeClass('errorMessage').text(message);
1288
            if (spin)
1289
            {
1290
                var img = '<img src="img/busy.gif" style="width:16px;height:9px;margin:0 4px 0 0;" />';
1291
                this.status.prepend(img);
1292
                this.replyStatus.prepend(img);
1293
            }
1294
        },
1295
1296
        /**
1297
         * bind events to DOM elements
1298
         */
1299
        bindEvents: function()
1300
        {
1301
            this.burnAfterReading.change($.proxy(this.changeBurnAfterReading, this));
1302
            this.sendButton.click($.proxy(this.sendData, this));
1303
            this.cloneButton.click($.proxy(this.clonePaste, this));
1304
            this.rawTextButton.click($.proxy(this.rawText, this));
1305
            this.fileRemoveButton.click($.proxy(this.removeAttachment, this));
1306
            $('.reloadlink').click($.proxy(this.reloadPage, this));
1307
            this.message.keydown(this.supportTabs);
1308
            this.messageEdit.click($.proxy(this.viewEditor, this));
1309
            this.messagePreview.click($.proxy(this.viewPreview, this));
1310
        },
1311
1312
        /**
1313
         * main application
1314
         */
1315
        init: function()
1316
        {
1317
            // hide "no javascript" message
1318
            $('#noscript').hide();
1319
1320
            // preload jQuery wrapped DOM elements and bind events
1321
            this.attach = $('#attach');
1322
            this.attachment = $('#attachment');
1323
            this.attachmentLink = $('#attachment a');
1324
            this.burnAfterReading = $('#burnafterreading');
1325
            this.burnAfterReadingOption = $('#burnafterreadingoption');
1326
            this.cipherData = $('#cipherdata');
1327
            this.clearText = $('#cleartext');
1328
            this.cloneButton = $('#clonebutton');
1329
            this.clonedFile = $('#clonedfile');
1330
            this.comments = $('#comments');
1331
            this.discussion = $('#discussion');
1332
            this.errorMessage = $('#errormessage');
1333
            this.expiration = $('#expiration');
1334
            this.fileRemoveButton = $('#fileremovebutton');
1335
            this.fileWrap = $('#filewrap');
1336
            this.formatter = $('#formatter');
1337
            this.image = $('#image');
1338
            this.message = $('#message');
1339
            this.messageEdit = $('#messageedit');
1340
            this.messagePreview = $('#messagepreview');
1341
            this.newButton = $('#newbutton');
1342
            this.openDisc = $('#opendisc');
1343
            this.openDiscussion = $('#opendiscussion');
1344
            this.password = $('#password');
1345
            this.passwordInput = $('#passwordinput');
1346
            this.pasteResult = $('#pasteresult');
1347
            this.prettyMessage = $('#prettymessage');
1348
            this.prettyPrint = $('#prettyprint');
1349
            this.preview = $('#preview');
1350
            this.rawTextButton = $('#rawtextbutton');
1351
            this.remainingTime = $('#remainingtime');
1352
            this.replyStatus = $('#replystatus');
1353
            this.sendButton = $('#sendbutton');
1354
            this.status = $('#status');
1355
            this.bindEvents();
1356
1357
            // Display status returned by php code if any (eg. Paste was properly deleted.)
1358
            if (this.status.text().length > 0)
1359
            {
1360
                this.showStatus(this.status.text(), false);
1361
                return;
1362
            }
1363
1364
            // Keep line height even if content empty.
1365
            this.status.html(' ');
1366
1367
            // Display an existing paste
1368
            if (this.cipherData.text().length > 1)
1369
            {
1370
                // Missing decryption key in URL?
1371
                if (window.location.hash.length == 0)
1372
                {
1373
                    this.showError(i18n._('Cannot decrypt paste: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)'));
1374
                    return;
1375
                }
1376
1377
                // List of messages to display.
1378
                var data = $.parseJSON(this.cipherData.text());
1379
1380
                // Show proper elements on screen.
1381
                this.stateExistingPaste();
1382
1383
                this.displayMessages(this.pageKey(), data);
1384
            }
1385
            // Display error message from php code.
1386
            else if (this.errorMessage.text().length > 1)
1387
            {
1388
                this.showError(this.errorMessage.text());
1389
            }
1390
            // Create a new paste.
1391
            else
1392
            {
1393
                this.newPaste();
1394
            }
1395
        }
1396
    }
1397
1398
    /**
1399
     * main application start, called when DOM is fully loaded
1400
     * runs privatebin when translations were loaded
1401
     */
1402
    i18n.loadTranslations($.proxy(privatebin.init, privatebin));
1403
});
1404
1405