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