Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.82% covered (success)
95.82%
229 / 239
76.92% covered (warning)
76.92%
10 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Controller
95.82% covered (success)
95.82%
229 / 239
76.92% covered (warning)
76.92%
10 / 13
56
0.00% covered (danger)
0.00%
0 / 1
 __construct
90.00% covered (success)
90.00%
36 / 40
0.00% covered (danger)
0.00%
0 / 1
11.12
 _init
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 _setDefaultLanguage
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 _setDefaultTemplate
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
5.02
 _setCacheHeaders
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 _create
100.00% covered (success)
100.00%
41 / 41
100.00% covered (success)
100.00%
1 / 1
11
 _delete
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 _read
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 _view
96.97% covered (success)
96.97%
64 / 66
0.00% covered (danger)
0.00%
0 / 1
6
 _jsonld
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
4
 _json_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 _json_result
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 _shortenerproxy
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php declare(strict_types=1);
2/**
3 * PrivateBin
4 *
5 * a zero-knowledge paste bin
6 *
7 * @link      https://github.com/PrivateBin/PrivateBin
8 * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
9 * @license   https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
10 */
11
12namespace PrivateBin;
13
14use Exception;
15use PrivateBin\Exception\TranslatedException;
16use PrivateBin\Persistence\ServerSalt;
17use PrivateBin\Persistence\TrafficLimiter;
18use PrivateBin\Proxy\AbstractProxy;
19use PrivateBin\Proxy\ShlinkProxy;
20use PrivateBin\Proxy\YourlsProxy;
21
22/**
23 * Controller
24 *
25 * Puts it all together.
26 */
27class Controller
28{
29    /**
30     * version
31     *
32     * @const string
33     */
34    const VERSION = '2.0.6';
35
36    /**
37     * minimal required PHP version
38     *
39     * @const string
40     */
41    const MIN_PHP_VERSION = '7.4.0';
42
43    /**
44     * show the same error message if the document expired or does not exist
45     *
46     * @const string
47     */
48    const GENERIC_ERROR = 'Document does not exist, has expired or has been deleted.';
49
50    /**
51     * configuration
52     *
53     * @access private
54     * @var    Configuration
55     */
56    private $_conf;
57
58    /**
59     * error message
60     *
61     * @access private
62     * @var    string
63     */
64    private $_error = '';
65
66    /**
67     * status message
68     *
69     * @access private
70     * @var    string
71     */
72    private $_status = '';
73
74    /**
75     * status message
76     *
77     * @access private
78     * @var    bool
79     */
80    private $_is_deleted = false;
81
82    /**
83     * JSON message
84     *
85     * @access private
86     * @var    string
87     */
88    private $_json = '';
89
90    /**
91     * Factory of instance models
92     *
93     * @access private
94     * @var    model
95     */
96    private $_model;
97
98    /**
99     * request
100     *
101     * @access private
102     * @var    request
103     */
104    private $_request;
105
106    /**
107     * URL base
108     *
109     * @access private
110     * @var    string
111     */
112    private $_urlBase;
113
114    /**
115     * constructor
116     *
117     * initializes and runs PrivateBin
118     *
119     * @param ?Configuration $config
120     *
121     * @access public
122     * @throws Exception
123     */
124    public function __construct(?Configuration $config = null)
125    {
126        if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
127            error_log(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION));
128            return;
129        }
130        if (strlen(PATH) > 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
131            error_log(I18n::_('%s requires the PATH to end in a "%s". Please update the PATH in your index.php.', I18n::_('PrivateBin'), DIRECTORY_SEPARATOR));
132            return;
133        }
134
135        // load config (using ini file by default) & initialize required classes
136        $this->_conf = $config ?? new Configuration();
137        $this->_init();
138
139        switch ($this->_request->getOperation()) {
140            case 'create':
141                $this->_create();
142                break;
143            case 'delete':
144                $this->_delete(
145                    $this->_request->getParam('pasteid'),
146                    $this->_request->getParam('deletetoken')
147                );
148                break;
149            case 'read':
150                $this->_read($this->_request->getParam('pasteid'));
151                break;
152            case 'jsonld':
153                $this->_jsonld($this->_request->getParam('jsonld'));
154                return;
155            case 'yourlsproxy':
156                $this->_shortenerproxy(new YourlsProxy($this->_conf, $this->_request->getParam('link')));
157                break;
158            case 'shlinkproxy':
159                $this->_shortenerproxy(new ShlinkProxy($this->_conf, $this->_request->getParam('link')));
160                break;
161        }
162
163        $this->_setCacheHeaders();
164
165        // output JSON or HTML
166        if ($this->_request->isJsonApiCall()) {
167            header('Content-type: ' . Request::MIME_JSON);
168            header('Access-Control-Allow-Origin: *');
169            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
170            header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
171            header('X-Uncompressed-Content-Length: ' . strlen($this->_json));
172            header('Access-Control-Expose-Headers: X-Uncompressed-Content-Length');
173            echo $this->_json;
174        } else {
175            $this->_view();
176        }
177    }
178
179    /**
180     * initialize PrivateBin
181     *
182     * @access private
183     * @throws Exception
184     */
185    private function _init()
186    {
187        $this->_model   = new Model($this->_conf);
188        $this->_request = new Request;
189        $this->_urlBase = $this->_request->getRequestUri();
190
191        $this->_setDefaultLanguage();
192        $this->_setDefaultTemplate();
193    }
194
195    /**
196     * Set default language
197     *
198     * @access private
199     * @throws Exception
200     */
201    private function _setDefaultLanguage()
202    {
203        $lang = $this->_conf->getKey('languagedefault');
204        I18n::setLanguageFallback($lang);
205        // force default language, if language selection is disabled and a default is set
206        if (!$this->_conf->getKey('languageselection') && strlen($lang) === 2) {
207            $_COOKIE['lang'] = $lang;
208            setcookie('lang', $lang, ['SameSite' => 'Lax', 'Secure' => true]);
209        }
210    }
211
212    /**
213     * Set default template
214     *
215     * @access private
216     * @throws Exception
217     */
218    private function _setDefaultTemplate()
219    {
220        $templates = $this->_conf->getKey('availabletemplates');
221        $template  = $this->_conf->getKey('template');
222        if (!in_array($template, $templates, true)) {
223            $templates[] = $template;
224        }
225        TemplateSwitcher::setAvailableTemplates($templates);
226        TemplateSwitcher::setTemplateFallback($template);
227
228        // force default template, if template selection is disabled
229        if (!$this->_conf->getKey('templateselection') && array_key_exists('template', $_COOKIE)) {
230            unset($_COOKIE['template']); // ensure value is not re-used in template switcher
231            $expiredInAllTimezones = time() - 86400;
232            setcookie('template', '', ['expires' => $expiredInAllTimezones, 'SameSite' => 'Lax', 'Secure' => true]);
233        }
234    }
235
236    /**
237     * Turn off browser caching
238     *
239     * @access private
240     */
241    private function _setCacheHeaders()
242    {
243        // set headers to disable caching
244        $time = gmdate('D, d M Y H:i:s \G\M\T');
245        header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
246        header('Pragma: no-cache');
247        header('Expires: ' . $time);
248        header('Last-Modified: ' . $time);
249        header('Vary: Accept');
250    }
251
252    /**
253     * Store new paste or comment
254     *
255     * POST contains:
256     * JSON encoded object with mandatory keys:
257     *   v = 2 (version)
258     *   adata (array)
259     *   ct (base64 encoded, encrypted text)
260     * meta (optional):
261     *   expire = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:1week)
262     * parentid (optional) = in discussions, which comment this comment replies to.
263     * pasteid (optional) = in discussions, which paste this comment belongs to.
264     *
265     * @access private
266     * @throws Exception
267     * @return string
268     */
269    private function _create()
270    {
271        // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
272        ServerSalt::setStore($this->_model->getStore());
273        TrafficLimiter::setConfiguration($this->_conf);
274        TrafficLimiter::setStore($this->_model->getStore());
275        try {
276            TrafficLimiter::canPass();
277        } catch (TranslatedException $e) {
278            $this->_json_error($e->getMessage());
279            return;
280        }
281
282        $data      = $this->_request->getData();
283        $isComment = array_key_exists('pasteid', $data) &&
284            !empty($data['pasteid']) &&
285            array_key_exists('parentid', $data) &&
286            !empty($data['parentid']);
287        if (!FormatV2::isValid($data, $isComment)) {
288            $this->_json_error(I18n::_('Invalid data.'));
289            return;
290        }
291        $sizelimit = $this->_conf->getKey('sizelimit');
292        // Ensure content is not too big.
293        if (strlen($data['ct']) > $sizelimit) {
294            $this->_json_error(
295                I18n::_(
296                    'Document is limited to %s of encrypted data.',
297                    Filter::formatHumanReadableSize($sizelimit)
298                )
299            );
300            return;
301        }
302
303        // The user posts a comment.
304        if ($isComment) {
305            $paste = $this->_model->getPaste($data['pasteid']);
306            if ($paste->exists()) {
307                try {
308                    $comment = $paste->getComment($data['parentid']);
309                    $comment->setData($data);
310                    $comment->store();
311                    $this->_json_result($comment->getId());
312                } catch (Exception $e) {
313                    $this->_json_error($e->getMessage());
314                }
315            } else {
316                $this->_json_error(I18n::_('Invalid data.'));
317            }
318        }
319        // The user posts a standard paste.
320        else {
321            try {
322                $this->_model->purge();
323                $paste = $this->_model->getPaste();
324                $paste->setData($data);
325                $paste->store();
326                $this->_json_result($paste->getId(), ['deletetoken' => $paste->getDeleteToken()]);
327            } catch (Exception $e) {
328                $this->_json_error($e->getMessage());
329            }
330        }
331    }
332
333    /**
334     * Delete an existing document
335     *
336     * @access private
337     * @param  string $dataid
338     * @param  string $deletetoken
339     */
340    private function _delete($dataid, $deletetoken)
341    {
342        try {
343            $paste = $this->_model->getPaste($dataid);
344            if ($paste->exists()) {
345                // accessing this method ensures that the document would be
346                // deleted if it has already expired
347                $paste->get();
348                if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
349                    // Document exists and deletion token is valid: Delete the it.
350                    $paste->delete();
351                    $this->_status     = 'Document was properly deleted.';
352                    $this->_is_deleted = true;
353                } else {
354                    $this->_error = 'Wrong deletion token. Document was not deleted.';
355                }
356            } else {
357                $this->_error = self::GENERIC_ERROR;
358            }
359        } catch (TranslatedException $e) {
360            $this->_error = $e->getMessage();
361        }
362        if ($this->_request->isJsonApiCall()) {
363            if (empty($this->_error)) {
364                $this->_json_result($dataid);
365            } else {
366                $this->_json_error(I18n::_($this->_error));
367            }
368        }
369    }
370
371    /**
372     * Read an existing document, only allowed via a JSON API call
373     *
374     * @access private
375     * @param  string $dataid
376     */
377    private function _read($dataid)
378    {
379        if (!$this->_request->isJsonApiCall()) {
380            return;
381        }
382
383        try {
384            $paste = $this->_model->getPaste($dataid);
385            if ($paste->exists()) {
386                $data = $paste->get();
387                if (array_key_exists('salt', $data['meta'])) {
388                    unset($data['meta']['salt']);
389                }
390                $this->_json_result($dataid, (array) $data);
391            } else {
392                $this->_json_error(I18n::_(self::GENERIC_ERROR));
393            }
394        } catch (TranslatedException $e) {
395            $this->_json_error($e->getMessage());
396        }
397    }
398
399    /**
400     * Display frontend.
401     *
402     * @access private
403     * @throws Exception
404     */
405    private function _view()
406    {
407        header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
408        header('Cross-Origin-Resource-Policy: same-origin');
409        header('Cross-Origin-Embedder-Policy: require-corp');
410        // disabled, because it prevents links from a document to the same site to
411        // be opened. Didn't work with `same-origin-allow-popups` either.
412        // See issue https://github.com/PrivateBin/PrivateBin/issues/970 for details.
413        // header('Cross-Origin-Opener-Policy: same-origin');
414        header('Permissions-Policy: browsing-topics=()');
415        header('Referrer-Policy: no-referrer');
416        header('X-Content-Type-Options: nosniff');
417        header('X-Frame-Options: deny');
418
419        // label all the expiration options
420        $expire = [];
421        foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
422            $expire[$time] = ($seconds === 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
423        }
424
425        // translate all the formatter options
426        $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
427
428        // set language cookie if that functionality was enabled
429        $languageselection = '';
430        if ($this->_conf->getKey('languageselection')) {
431            $languageselection = I18n::getLanguage();
432            setcookie('lang', $languageselection, ['SameSite' => 'Lax', 'Secure' => true]);
433        }
434
435        // set template cookie if that functionality was enabled
436        $templateselection = '';
437        if ($this->_conf->getKey('templateselection')) {
438            $templateselection = TemplateSwitcher::getTemplate();
439            setcookie('template', $templateselection, ['SameSite' => 'Lax', 'Secure' => true]);
440        }
441
442        // strip policies that are unsupported in meta tag
443        $metacspheader = str_replace(
444            [
445                'frame-ancestors \'none\'; ',
446                '; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
447            ],
448            '',
449            $this->_conf->getKey('cspheader')
450        );
451
452        $page = new View;
453        $page->assign('CSPHEADER', $metacspheader);
454        $page->assign('ERROR', I18n::_($this->_error));
455        $page->assign('NAME', $this->_conf->getKey('name'));
456        if (in_array($this->_request->getOperation(), ['shlinkproxy', 'yourlsproxy'], true)) {
457            $page->assign('SHORTURL', $this->_status);
458            $page->draw('shortenerproxy');
459            return;
460        }
461        $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
462        $page->assign('STATUS', I18n::_($this->_status));
463        $page->assign('ISDELETED', $this->_is_deleted);
464        $page->assign('VERSION', self::VERSION);
465        $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
466        $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
467        $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
468        $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
469        $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
470        $page->assign('FORMATTER', $formatters);
471        $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
472        $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
473        $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
474        $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
475        $page->assign('PASSWORD', $this->_conf->getKey('password'));
476        $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
477        $page->assign('LANGUAGESELECTION', $languageselection);
478        $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
479        $page->assign('TEMPLATESELECTION', $templateselection);
480        $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
481        $page->assign('EXPIRE', $expire);
482        $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
483        $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
484        $page->assign('SHORTENBYDEFAULT', $this->_conf->getKey('shortenbydefault'));
485        $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
486        $page->assign('EMAIL', $this->_conf->getKey('email'));
487        $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
488        $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
489        $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
490        $page->assign('SRI', $this->_conf->getSection('sri'));
491        $page->draw(TemplateSwitcher::getTemplate());
492    }
493
494    /**
495     * outputs requested JSON-LD context
496     *
497     * @access private
498     * @param string $type
499     */
500    private function _jsonld($type)
501    {
502        if (!in_array($type, [
503            'comment',
504            'commentmeta',
505            'paste',
506            'pastemeta',
507            'types',
508        ])) {
509            $type = '';
510        }
511        $content = '{}';
512        $file    = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
513        if (is_readable($file)) {
514            $content = str_replace(
515                '?jsonld=',
516                $this->_urlBase . '?jsonld=',
517                file_get_contents($file)
518            );
519        }
520        if ($type === 'types') {
521            $content = str_replace(
522                implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
523                implode('", "', array_keys($this->_conf->getSection('expire_options'))),
524                $content
525            );
526        }
527
528        header('Content-type: application/ld+json');
529        header('Access-Control-Allow-Origin: *');
530        header('Access-Control-Allow-Methods: GET');
531        echo $content;
532    }
533
534    /**
535     * prepares JSON encoded error message
536     *
537     * @access private
538     * @param  string $error
539     * @throws JsonException
540     */
541    private function _json_error($error)
542    {
543        $result = [
544            'status'  => 1,
545            'message' => $error,
546        ];
547        $this->_json = Json::encode($result);
548    }
549
550    /**
551     * prepares JSON encoded result message
552     *
553     * @access private
554     * @param  string $dataid
555     * @param  array $other
556     * @throws JsonException
557     */
558    private function _json_result($dataid, $other = [])
559    {
560        $result = [
561            'status' => 0,
562            'id'     => $dataid,
563            'url'    => $this->_urlBase . '?' . $dataid,
564        ] + $other;
565        $this->_json = Json::encode($result);
566    }
567
568    /**
569     * Proxies a link using the specified proxy class, and updates the status or error with the response.
570     *
571     * @access private
572     * @param AbstractProxy $proxy The instance of the proxy class.
573     */
574    private function _shortenerproxy(AbstractProxy $proxy)
575    {
576        if ($proxy->isError()) {
577            $this->_error = $proxy->getError();
578        } else {
579            $this->_status = $proxy->getUrl();
580        }
581    }
582}