Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.96% covered (success)
94.96%
226 / 238
76.92% covered (warning)
76.92%
10 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Controller
94.96% covered (success)
94.96%
226 / 238
76.92% covered (warning)
76.92%
10 / 13
57.42
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%
33 / 33
100.00% covered (success)
100.00%
1 / 1
10
 _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.1';
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, '<')) {
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        $data = [];
284        try {
285            TrafficLimiter::canPass();
286            $data = $this->_request->getData($this->_conf->getKey('sizelimit'));
287        } catch (TranslatedException $e) {
288            $this->_json_error($e->getMessage());
289            return;
290        }
291
292        $isComment = array_key_exists('pasteid', $data) &&
293            !empty($data['pasteid']) &&
294            array_key_exists('parentid', $data) &&
295            !empty($data['parentid']);
296        if (!FormatV2::isValid($data, $isComment)) {
297            $this->_json_error(I18n::_('Invalid data.'));
298            return;
299        }
300
301        // The user posts a comment.
302        if ($isComment) {
303            $paste = $this->_model->getPaste($data['pasteid']);
304            if ($paste->exists()) {
305                try {
306                    $comment = $paste->getComment($data['parentid']);
307                    $comment->setData($data);
308                    $comment->store();
309                    $this->_json_result($comment->getId());
310                } catch (Exception $e) {
311                    $this->_json_error($e->getMessage());
312                }
313            } else {
314                $this->_json_error(I18n::_('Invalid data.'));
315            }
316        }
317        // The user posts a standard paste.
318        else {
319            try {
320                $this->_model->purge();
321                $paste = $this->_model->getPaste();
322                $paste->setData($data);
323                $paste->store();
324                $this->_json_result($paste->getId(), ['deletetoken' => $paste->getDeleteToken()]);
325            } catch (Exception $e) {
326                $this->_json_error($e->getMessage());
327            }
328        }
329    }
330
331    /**
332     * Delete an existing document
333     *
334     * @access private
335     * @param  string $dataid
336     * @param  string $deletetoken
337     */
338    private function _delete($dataid, $deletetoken)
339    {
340        try {
341            $paste = $this->_model->getPaste($dataid);
342            if ($paste->exists()) {
343                // accessing this method ensures that the document would be
344                // deleted if it has already expired
345                $paste->get();
346                if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
347                    // Document exists and deletion token is valid: Delete the it.
348                    $paste->delete();
349                    $this->_status = 'Document was properly deleted.';
350                    $this->_is_deleted = true;
351                } else {
352                    $this->_error = 'Wrong deletion token. Document was not deleted.';
353                }
354            } else {
355                $this->_error = self::GENERIC_ERROR;
356            }
357        } catch (TranslatedException $e) {
358            $this->_error = $e->getMessage();
359        }
360        if ($this->_request->isJsonApiCall()) {
361            if (empty($this->_error)) {
362                $this->_json_result($dataid);
363            } else {
364                $this->_json_error(I18n::_($this->_error));
365            }
366        }
367    }
368
369    /**
370     * Read an existing document, only allowed via a JSON API call
371     *
372     * @access private
373     * @param  string $dataid
374     */
375    private function _read($dataid)
376    {
377        if (!$this->_request->isJsonApiCall()) {
378            return;
379        }
380
381        try {
382            $paste = $this->_model->getPaste($dataid);
383            if ($paste->exists()) {
384                $data = $paste->get();
385                if (array_key_exists('salt', $data['meta'])) {
386                    unset($data['meta']['salt']);
387                }
388                $this->_json_result($dataid, (array) $data);
389            } else {
390                $this->_json_error(I18n::_(self::GENERIC_ERROR));
391            }
392        } catch (TranslatedException $e) {
393            $this->_json_error($e->getMessage());
394        }
395    }
396
397    /**
398     * Display frontend.
399     *
400     * @access private
401     * @throws Exception
402     */
403    private function _view()
404    {
405        header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
406        header('Cross-Origin-Resource-Policy: same-origin');
407        header('Cross-Origin-Embedder-Policy: require-corp');
408        // disabled, because it prevents links from a document to the same site to
409        // be opened. Didn't work with `same-origin-allow-popups` either.
410        // See issue https://github.com/PrivateBin/PrivateBin/issues/970 for details.
411        // header('Cross-Origin-Opener-Policy: same-origin');
412        header('Permissions-Policy: browsing-topics=()');
413        header('Referrer-Policy: no-referrer');
414        header('X-Content-Type-Options: nosniff');
415        header('X-Frame-Options: deny');
416
417        // label all the expiration options
418        $expire = [];
419        foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
420            $expire[$time] = ($seconds === 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
421        }
422
423        // translate all the formatter options
424        $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
425
426        // set language cookie if that functionality was enabled
427        $languageselection = '';
428        if ($this->_conf->getKey('languageselection')) {
429            $languageselection = I18n::getLanguage();
430            setcookie('lang', $languageselection, ['SameSite' => 'Lax', 'Secure' => true]);
431        }
432
433        // set template cookie if that functionality was enabled
434        $templateselection = '';
435        if ($this->_conf->getKey('templateselection')) {
436            $templateselection = TemplateSwitcher::getTemplate();
437            setcookie('template', $templateselection, ['SameSite' => 'Lax', 'Secure' => true]);
438        }
439
440        // strip policies that are unsupported in meta tag
441        $metacspheader = str_replace(
442            [
443                'frame-ancestors \'none\'; ',
444                '; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
445            ],
446            '',
447            $this->_conf->getKey('cspheader')
448        );
449
450        $page = new View;
451        $page->assign('CSPHEADER', $metacspheader);
452        $page->assign('ERROR', I18n::_($this->_error));
453        $page->assign('NAME', $this->_conf->getKey('name'));
454        if (in_array($this->_request->getOperation(), ['shlinkproxy', 'yourlsproxy', 'chhotoproxy'], true)) {
455            $page->assign('SHORTURL', $this->_status);
456            $page->draw('shortenerproxy');
457            return;
458        }
459        $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
460        $page->assign('STATUS', I18n::_($this->_status));
461        $page->assign('ISDELETED', $this->_is_deleted);
462        $page->assign('VERSION', self::VERSION);
463        $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
464        $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
465        $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
466        $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
467        $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
468        $page->assign('FORMATTER', $formatters);
469        $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
470        $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
471        $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
472        $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
473        $page->assign('PASSWORD', $this->_conf->getKey('password'));
474        $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
475        $page->assign('LANGUAGESELECTION', $languageselection);
476        $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
477        $page->assign('TEMPLATESELECTION', $templateselection);
478        $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
479        $page->assign('EXPIRE', $expire);
480        $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
481        $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
482        $page->assign('SHORTENBYDEFAULT', $this->_conf->getKey('shortenbydefault'));
483        $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
484        $page->assign('EMAIL', $this->_conf->getKey('email'));
485        $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
486        $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
487        $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
488        $page->assign('SRI', $this->_conf->getSection('sri'));
489        $page->draw(TemplateSwitcher::getTemplate());
490    }
491
492    /**
493     * outputs requested JSON-LD context
494     *
495     * @access private
496     * @param string $type
497     */
498    private function _jsonld($type)
499    {
500        if (!in_array($type, [
501            'comment',
502            'commentmeta',
503            'paste',
504            'pastemeta',
505            'types',
506        ])) {
507            $type = '';
508        }
509        $content = '{}';
510        $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
511        if (is_readable($file)) {
512            $content = str_replace(
513                '?jsonld=',
514                trim(Json::encode($this->_urlBase), '"') . '?jsonld=',
515                file_get_contents($file)
516            );
517        }
518        if ($type === 'types') {
519            $content = str_replace(
520                implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
521                implode('", "', array_keys($this->_conf->getSection('expire_options'))),
522                $content
523            );
524        }
525
526        header('Content-type: application/ld+json');
527        header('Access-Control-Allow-Origin: *');
528        header('Access-Control-Allow-Methods: GET');
529        header('X-Content-Type-Options: nosniff');
530        echo $content;
531    }
532
533    /**
534     * prepares JSON encoded error message
535     *
536     * @access private
537     * @param  string $error
538     * @throws JsonException
539     */
540    private function _json_error($error)
541    {
542        $result = [
543            'status'  => 1,
544            'message' => $error,
545        ];
546        $this->_json = Json::encode($result);
547    }
548
549    /**
550     * prepares JSON encoded result message
551     *
552     * @access private
553     * @param  string $dataid
554     * @param  array $other
555     * @throws JsonException
556     */
557    private function _json_result($dataid, $other = [])
558    {
559        $result = [
560            'status' => 0,
561            'id'     => $dataid,
562            'url'    => $this->_urlBase . '?' . $dataid,
563        ] + $other;
564        $this->_json = Json::encode($result);
565    }
566
567    /**
568     * Proxies a link using the specified proxy class, and updates the status or error with the response.
569     *
570     * @access private
571     * @param AbstractProxy $proxy The instance of the proxy class.
572     */
573    private function _shortenerproxy(AbstractProxy $proxy)
574    {
575        if ($proxy->isError()) {
576            $this->_error = $proxy->getError();
577        } else {
578            $this->_status = $proxy->getUrl();
579        }
580    }
581}