Passed
Pull Request — master (#447)
by El
03:08
created

Controller::_read()   B

Complexity

Conditions 7
Paths 19

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.0119

Importance

Changes 0
Metric Value
cc 7
eloc 17
nc 19
nop 1
dl 0
loc 30
ccs 15
cts 16
cp 0.9375
crap 7.0119
rs 8.8333
c 0
b 0
f 0
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.2.1
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.2.1';
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 90
    public function __construct()
112
    {
113 90
        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 90
        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 90
        $this->_init();
122
123 86
        switch ($this->_request->getOperation()) {
124 86
            case 'create':
125 38
                $this->_create();
126 38
                break;
127 48
            case 'delete':
128 16
                $this->_delete(
129 16
                    $this->_request->getParam('pasteid'),
130 16
                    $this->_request->getParam('deletetoken')
131
                );
132 16
                break;
133 32
            case 'read':
134 19
                $this->_read($this->_request->getParam('pasteid'));
135 19
                break;
136 13
            case 'jsonld':
137 5
                $this->_jsonld($this->_request->getParam('jsonld'));
138 5
                return;
139
        }
140
141
        // output JSON or HTML
142 81
        if ($this->_request->isJsonApiCall()) {
143 61
            header('Content-type: ' . Request::MIME_JSON);
144 61
            header('Access-Control-Allow-Origin: *');
145 61
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
146 61
            header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
147 61
            echo $this->_json;
148
        } else {
149 20
            $this->_view();
150
        }
151 81
    }
152
153
    /**
154
     * initialize PrivateBin
155
     *
156
     * @access private
157
     * @throws Exception
158
     */
159 90
    private function _init()
160
    {
161 90
        $this->_conf    = new Configuration;
162 88
        $this->_model   = new Model($this->_conf);
163 88
        $this->_request = new Request;
164 86
        $this->_urlBase = $this->_request->getRequestUri();
165 86
        ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
166
167
        // set default language
168 86
        $lang = $this->_conf->getKey('languagedefault');
169 86
        I18n::setLanguageFallback($lang);
170
        // force default language, if language selection is disabled and a default is set
171 86
        if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
172 2
            $_COOKIE['lang'] = $lang;
173 2
            setcookie('lang', $lang);
174
        }
175 86
    }
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 38
    private function _create()
198
    {
199
        // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
200 38
        TrafficLimiter::setConfiguration($this->_conf);
201 38
        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 38
        $data      = $this->_request->getData();
212 38
        $isComment = array_key_exists('pasteid', $data) &&
213 38
            !empty($data['pasteid']) &&
214 38
            array_key_exists('parentid', $data) &&
215 38
            !empty($data['parentid']);
216 38
        if (!FormatV2::isValid($data, $isComment)) {
217 2
            $this->_return_message(1, I18n::_('Invalid data.'));
218 2
            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
Bug introduced by
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 10
                if ($paste->isDeleteTokenCorrect($deletetoken)) {
280
                    // Paste exists and deletion token is valid: Delete the paste.
281 6
                    $paste->delete();
282 6
                    $this->_status = 'Paste was properly deleted.';
283
                } else {
284 10
                    $this->_error = 'Wrong deletion token. Paste was not deleted.';
285
                }
286
            } else {
287 12
                $this->_error = self::GENERIC_ERROR;
288
            }
289 4
        } catch (Exception $e) {
290 4
            $this->_error = $e->getMessage();
291
        }
292 16
        if ($this->_request->isJsonApiCall()) {
293 4
            if (strlen($this->_error)) {
294 2
                $this->_return_message(1, $this->_error);
295
            } else {
296 2
                $this->_return_message(0, $dataid);
297
            }
298
        }
299 16
    }
300
301
    /**
302
     * Read an existing paste or comment, only allowed via a JSON API call
303
     *
304
     * @access private
305
     * @param  string $dataid
306
     */
307 19
    private function _read($dataid)
308
    {
309 19
        if (!$this->_request->isJsonApiCall()) {
310
            return;
311
        }
312
313
        try {
314 19
            $paste = $this->_model->getPaste($dataid);
315 17
            if ($paste->exists()) {
316
                // handle challenge response
317 15
                if (!$paste->isTokenCorrect($this->_request->getParam('token'))) {
318
                    // we send a generic error to avoid leaking information
319
                    // about the existance of a burn after reading pastes
320
                    // this avoids an attacker being able to poll, if it has
321
                    // been read by the intended recipient or not
322 2
                    $this->_return_message(1, self::GENERIC_ERROR);
323 2
                    return;
324
                }
325 11
                $data = $paste->get();
326 11
                foreach (array('salt', 'challenge') as $key) {
327 11
                    if (array_key_exists($key, $data['meta'])) {
328 11
                        unset($data['meta'][$key]);
329
                    }
330
                }
331 11
                $this->_return_message(0, $dataid, (array) $data);
332
            } else {
333 13
                $this->_return_message(1, self::GENERIC_ERROR);
334
            }
335 4
        } catch (Exception $e) {
336 4
            $this->_return_message(1, $e->getMessage());
337
        }
338 17
    }
339
340
    /**
341
     * Display frontend.
342
     *
343
     * @access private
344
     */
345 20
    private function _view()
346
    {
347
        // set headers to disable caching
348 20
        $time = gmdate('D, d M Y H:i:s \G\M\T');
349 20
        header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
350 20
        header('Pragma: no-cache');
351 20
        header('Expires: ' . $time);
352 20
        header('Last-Modified: ' . $time);
353 20
        header('Vary: Accept');
354 20
        header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
355 20
        header('Referrer-Policy: no-referrer');
356 20
        header('X-Xss-Protection: 1; mode=block');
357 20
        header('X-Frame-Options: DENY');
358 20
        header('X-Content-Type-Options: nosniff');
359
360
        // label all the expiration options
361 20
        $expire = array();
362 20
        foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
363 20
            $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
364
        }
365
366
        // translate all the formatter options
367 20
        $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
368
369
        // set language cookie if that functionality was enabled
370 20
        $languageselection = '';
371 20
        if ($this->_conf->getKey('languageselection')) {
372 2
            $languageselection = I18n::getLanguage();
373 2
            setcookie('lang', $languageselection);
374
        }
375
376 20
        $page = new View;
377 20
        $page->assign('NAME', $this->_conf->getKey('name'));
378 20
        $page->assign('ERROR', I18n::_($this->_error));
379 20
        $page->assign('STATUS', I18n::_($this->_status));
380 20
        $page->assign('VERSION', self::VERSION);
381 20
        $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
382 20
        $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
383 20
        $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
384 20
        $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
385 20
        $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
386 20
        $page->assign('FORMATTER', $formatters);
387 20
        $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
388 20
        $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
389 20
        $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
390 20
        $page->assign('PASSWORD', $this->_conf->getKey('password'));
391 20
        $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
392 20
        $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
393 20
        $page->assign('LANGUAGESELECTION', $languageselection);
394 20
        $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
395 20
        $page->assign('EXPIRE', $expire);
396 20
        $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
397 20
        $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
398 20
        $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
399 20
        $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
400 20
        $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
401 20
        $page->draw($this->_conf->getKey('template'));
402 20
    }
403
404
    /**
405
     * outputs requested JSON-LD context
406
     *
407
     * @access private
408
     * @param string $type
409
     */
410 5
    private function _jsonld($type)
411
    {
412
        if (
413 5
            $type !== 'paste' && $type !== 'comment' &&
414 5
            $type !== 'pastemeta' && $type !== 'commentmeta'
415
        ) {
416 1
            $type = '';
417
        }
418 5
        $content = '{}';
419 5
        $file    = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
420 5
        if (is_readable($file)) {
421 4
            $content = str_replace(
422 4
                '?jsonld=',
423 4
                $this->_urlBase . '?jsonld=',
424 4
                file_get_contents($file)
425
            );
426
        }
427
428 5
        header('Content-type: application/ld+json');
429 5
        header('Access-Control-Allow-Origin: *');
430 5
        header('Access-Control-Allow-Methods: GET');
431 5
        echo $content;
432 5
    }
433
434
    /**
435
     * prepares JSON encoded status message
436
     *
437
     * @access private
438
     * @param  int $status
439
     * @param  string $message
440
     * @param  array $other
441
     */
442 61
    private function _return_message($status, $message, $other = array())
443
    {
444 61
        $result = array('status' => $status);
445 61
        if ($status) {
446 30
            $result['message'] = I18n::_($message);
447
        } else {
448 33
            $result['id']  = $message;
449 33
            $result['url'] = $this->_urlBase . '?' . $message;
450
        }
451 61
        $result += $other;
452 61
        $this->_json = Json::encode($result);
453 61
    }
454
}
455