Issues (10)

lib/Controller.php (1 issue)

Labels
Severity
1
<?php
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
 * @version   1.3
11
 */
12
13
namespace PrivateBin;
14
15
use Exception;
16
use PrivateBin\Persistence\ServerSalt;
17
use PrivateBin\Persistence\TrafficLimiter;
18
19
/**
20
 * Controller
21
 *
22
 * Puts it all together.
23
 */
24
class Controller
25
{
26
    /**
27
     * version
28
     *
29
     * @const string
30
     */
31
    const VERSION = '1.3';
32
33
    /**
34
     * minimal required PHP version
35
     *
36
     * @const string
37
     */
38
    const MIN_PHP_VERSION = '5.5.0';
39
40
    /**
41
     * show the same error message if the paste expired or does not exist
42
     *
43
     * @const string
44
     */
45
    const GENERIC_ERROR = 'Paste does not exist, has expired or has been deleted.';
46
47
    /**
48
     * configuration
49
     *
50
     * @access private
51
     * @var    Configuration
52
     */
53
    private $_conf;
54
55
    /**
56
     * error message
57
     *
58
     * @access private
59
     * @var    string
60
     */
61
    private $_error = '';
62
63
    /**
64
     * status message
65
     *
66
     * @access private
67
     * @var    string
68
     */
69
    private $_status = '';
70
71
    /**
72
     * JSON message
73
     *
74
     * @access private
75
     * @var    string
76
     */
77
    private $_json = '';
78
79
    /**
80
     * Factory of instance models
81
     *
82
     * @access private
83
     * @var    model
84
     */
85
    private $_model;
86
87
    /**
88
     * request
89
     *
90
     * @access private
91
     * @var    request
92
     */
93
    private $_request;
94
95
    /**
96
     * URL base
97
     *
98
     * @access private
99
     * @var    string
100
     */
101
    private $_urlBase;
102
103
    /**
104
     * constructor
105
     *
106
     * initializes and runs PrivateBin
107
     *
108
     * @access public
109
     * @throws Exception
110
     */
111 84
    public function __construct()
112
    {
113 84
        if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
114
            throw new Exception(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION), 1);
115
        }
116 84
        if (strlen(PATH) < 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
117
            throw new Exception(I18n::_('%s requires the PATH to end in a "%s". Please update the PATH in your index.php.', I18n::_('PrivateBin'), DIRECTORY_SEPARATOR), 5);
118
        }
119
120
        // load config from ini file, initialize required classes
121 84
        $this->_init();
122
123 80
        switch ($this->_request->getOperation()) {
124 80
            case 'create':
125 36
                $this->_create();
126 36
                break;
127 44
            case 'delete':
128 16
                $this->_delete(
129 16
                    $this->_request->getParam('pasteid'),
130 16
                    $this->_request->getParam('deletetoken')
131
                );
132 16
                break;
133 28
            case 'read':
134 15
                $this->_read($this->_request->getParam('pasteid'));
135 15
                break;
136 13
            case 'jsonld':
137 5
                $this->_jsonld($this->_request->getParam('jsonld'));
138 5
                return;
139
        }
140
141
        // output JSON or HTML
142 75
        if ($this->_request->isJsonApiCall()) {
143 55
            header('Content-type: ' . Request::MIME_JSON);
144 55
            header('Access-Control-Allow-Origin: *');
145 55
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
146 55
            header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
147 55
            echo $this->_json;
148
        } else {
149 20
            $this->_view();
150
        }
151 75
    }
152
153
    /**
154
     * initialize PrivateBin
155
     *
156
     * @access private
157
     * @throws Exception
158
     */
159 84
    private function _init()
160
    {
161 84
        $this->_conf    = new Configuration;
162 82
        $this->_model   = new Model($this->_conf);
163 82
        $this->_request = new Request;
164 80
        $this->_urlBase = $this->_request->getRequestUri();
165 80
        ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
166
167
        // set default language
168 80
        $lang = $this->_conf->getKey('languagedefault');
169 80
        I18n::setLanguageFallback($lang);
170
        // force default language, if language selection is disabled and a default is set
171 80
        if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
172 2
            $_COOKIE['lang'] = $lang;
173 2
            setcookie('lang', $lang);
174
        }
175 80
    }
176
177
    /**
178
     * Store new paste or comment
179
     *
180
     * POST contains one or both:
181
     * data = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
182
     * attachment = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
183
     *
184
     * All optional data will go to meta information:
185
     * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
186
     * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
187
     * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
188
     * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
189
     * attachmentname = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
190
     * nickname (optional) = in discussion, encoded FormatV2 encrypted text nickname of author of comment (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
191
     * parentid (optional) = in discussion, which comment this comment replies to.
192
     * pasteid (optional) = in discussion, which paste this comment belongs to.
193
     *
194
     * @access private
195
     * @return string
196
     */
197 36
    private function _create()
198
    {
199
        // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
200 36
        TrafficLimiter::setConfiguration($this->_conf);
201 36
        if (!TrafficLimiter::canPass()) {
202 2
            $this->_return_message(
203 2
                1, I18n::_(
204 2
                    'Please wait %d seconds between each post.',
205 2
                    $this->_conf->getKey('limit', 'traffic')
206
                )
207
            );
208 2
            return;
209
        }
210
211 36
        $data      = $this->_request->getData();
212 36
        $isComment = array_key_exists('pasteid', $data) &&
213 36
            !empty($data['pasteid']) &&
214 36
            array_key_exists('parentid', $data) &&
215 36
            !empty($data['parentid']);
216 36
        if (!FormatV2::isValid($data, $isComment)) {
217
            $this->_return_message(1, I18n::_('Invalid data.'));
218
            return;
219
        }
220 36
        $sizelimit = $this->_conf->getKey('sizelimit');
221
        // Ensure content is not too big.
222 36
        if (strlen($data['ct']) > $sizelimit) {
223 2
            $this->_return_message(
224 2
                1,
225 2
                I18n::_(
226 2
                    'Paste is limited to %s of encrypted data.',
227 2
                    Filter::formatHumanReadableSize($sizelimit)
228
                )
229
            );
230 2
            return;
231
        }
232
233
        // The user posts a comment.
234 34
        if ($isComment) {
235 10
            $paste = $this->_model->getPaste($data['pasteid']);
236 10
            if ($paste->exists()) {
237
                try {
238 8
                    $comment = $paste->getComment($data['parentid']);
239 6
                    $comment->setData($data);
240 6
                    $comment->store();
241 6
                } catch (Exception $e) {
242 6
                    $this->_return_message(1, $e->getMessage());
243 6
                    return;
244
                }
245 2
                $this->_return_message(0, $comment->getId());
246
            } else {
247 4
                $this->_return_message(1, I18n::_('Invalid data.'));
248
            }
249
        }
250
        // The user posts a standard paste.
251
        else {
252 24
            $this->_model->purge();
253 24
            $paste = $this->_model->getPaste();
254
            try {
255 24
                $paste->setData($data);
256 20
                $paste->store();
257 6
            } catch (Exception $e) {
258 6
                return $this->_return_message(1, $e->getMessage());
0 ignored issues
show
Are you sure the usage of $this->_return_message(1, $e->getMessage()) targeting PrivateBin\Controller::_return_message() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
259
            }
260 18
            $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
261
        }
262 22
    }
263
264
    /**
265
     * Delete an existing paste
266
     *
267
     * @access private
268
     * @param  string $dataid
269
     * @param  string $deletetoken
270
     */
271 16
    private function _delete($dataid, $deletetoken)
272
    {
273
        try {
274 16
            $paste = $this->_model->getPaste($dataid);
275 14
            if ($paste->exists()) {
276
                // accessing this method ensures that the paste would be
277
                // deleted if it has already expired
278 12
                $paste->get();
279
                if (
280 10
                    Filter::slowEquals($deletetoken, $paste->getDeleteToken())
281
                ) {
282
                    // Paste exists and deletion token is valid: Delete the paste.
283 6
                    $paste->delete();
284 6
                    $this->_status = 'Paste was properly deleted.';
285
                } else {
286 10
                    $this->_error = 'Wrong deletion token. Paste was not deleted.';
287
                }
288
            } else {
289 12
                $this->_error = self::GENERIC_ERROR;
290
            }
291 4
        } catch (Exception $e) {
292 4
            $this->_error = $e->getMessage();
293
        }
294 16
        if ($this->_request->isJsonApiCall()) {
295 4
            if (strlen($this->_error)) {
296 2
                $this->_return_message(1, $this->_error);
297
            } else {
298 2
                $this->_return_message(0, $dataid);
299
            }
300
        }
301 16
    }
302
303
    /**
304
     * Read an existing paste or comment, only allowed via a JSON API call
305
     *
306
     * @access private
307
     * @param  string $dataid
308
     */
309 15
    private function _read($dataid)
310
    {
311 15
        if (!$this->_request->isJsonApiCall()) {
312
            return;
313
        }
314
315
        try {
316 15
            $paste = $this->_model->getPaste($dataid);
317 13
            if ($paste->exists()) {
318 11
                $data = $paste->get();
319 9
                if (array_key_exists('salt', $data['meta'])) {
320 9
                    unset($data['meta']['salt']);
321
                }
322 9
                $this->_return_message(0, $dataid, (array) $data);
323
            } else {
324 11
                $this->_return_message(1, self::GENERIC_ERROR);
325
            }
326 4
        } catch (Exception $e) {
327 4
            $this->_return_message(1, $e->getMessage());
328
        }
329 15
    }
330
331
    /**
332
     * Display frontend.
333
     *
334
     * @access private
335
     */
336 20
    private function _view()
337
    {
338
        // set headers to disable caching
339 20
        $time = gmdate('D, d M Y H:i:s \G\M\T');
340 20
        header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
341 20
        header('Pragma: no-cache');
342 20
        header('Expires: ' . $time);
343 20
        header('Last-Modified: ' . $time);
344 20
        header('Vary: Accept');
345 20
        header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
346 20
        header('Referrer-Policy: no-referrer');
347 20
        header('X-Xss-Protection: 1; mode=block');
348 20
        header('X-Frame-Options: DENY');
349 20
        header('X-Content-Type-Options: nosniff');
350
351
        // label all the expiration options
352 20
        $expire = array();
353 20
        foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
354 20
            $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
355
        }
356
357
        // translate all the formatter options
358 20
        $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
359
360
        // set language cookie if that functionality was enabled
361 20
        $languageselection = '';
362 20
        if ($this->_conf->getKey('languageselection')) {
363 2
            $languageselection = I18n::getLanguage();
364 2
            setcookie('lang', $languageselection);
365
        }
366
367 20
        $page = new View;
368 20
        $page->assign('NAME', $this->_conf->getKey('name'));
369 20
        $page->assign('ERROR', I18n::_($this->_error));
370 20
        $page->assign('STATUS', I18n::_($this->_status));
371 20
        $page->assign('VERSION', self::VERSION);
372 20
        $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
373 20
        $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
374 20
        $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
375 20
        $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
376 20
        $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
377 20
        $page->assign('FORMATTER', $formatters);
378 20
        $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
379 20
        $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
380 20
        $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
381 20
        $page->assign('PASSWORD', $this->_conf->getKey('password'));
382 20
        $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
383 20
        $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
384 20
        $page->assign('LANGUAGESELECTION', $languageselection);
385 20
        $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
386 20
        $page->assign('EXPIRE', $expire);
387 20
        $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
388 20
        $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
389 20
        $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
390 20
        $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
391 20
        $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
392 20
        $page->draw($this->_conf->getKey('template'));
393 20
    }
394
395
    /**
396
     * outputs requested JSON-LD context
397
     *
398
     * @access private
399
     * @param string $type
400
     */
401 5
    private function _jsonld($type)
402
    {
403
        if (
404 5
            $type !== 'paste' && $type !== 'comment' &&
405 5
            $type !== 'pastemeta' && $type !== 'commentmeta'
406
        ) {
407 1
            $type = '';
408
        }
409 5
        $content = '{}';
410 5
        $file    = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
411 5
        if (is_readable($file)) {
412 4
            $content = str_replace(
413 4
                '?jsonld=',
414 4
                $this->_urlBase . '?jsonld=',
415 4
                file_get_contents($file)
416
            );
417
        }
418
419 5
        header('Content-type: application/ld+json');
420 5
        header('Access-Control-Allow-Origin: *');
421 5
        header('Access-Control-Allow-Methods: GET');
422 5
        echo $content;
423 5
    }
424
425
    /**
426
     * prepares JSON encoded status message
427
     *
428
     * @access private
429
     * @param  int $status
430
     * @param  string $message
431
     * @param  array $other
432
     */
433 55
    private function _return_message($status, $message, $other = array())
434
    {
435 55
        $result = array('status' => $status);
436 55
        if ($status) {
437 26
            $result['message'] = I18n::_($message);
438
        } else {
439 31
            $result['id']  = $message;
440 31
            $result['url'] = $this->_urlBase . '?' . $message;
441
        }
442 55
        $result += $other;
443 55
        $this->_json = Json::encode($result);
444 55
    }
445
}
446