| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571 |
- <?php declare(strict_types=1);
- /**
- * PrivateBin
- *
- * a zero-knowledge paste bin
- *
- * @link https://github.com/PrivateBin/PrivateBin
- * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
- * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
- */
- namespace PrivateBin;
- use Exception;
- use PrivateBin\Persistence\ServerSalt;
- use PrivateBin\Persistence\TrafficLimiter;
- use PrivateBin\Proxy\AbstractProxy;
- use PrivateBin\Proxy\ShlinkProxy;
- use PrivateBin\Proxy\YourlsProxy;
- /**
- * Controller
- *
- * Puts it all together.
- */
- class Controller
- {
- /**
- * version
- *
- * @const string
- */
- const VERSION = '2.0.1';
- /**
- * minimal required PHP version
- *
- * @const string
- */
- const MIN_PHP_VERSION = '7.4.0';
- /**
- * show the same error message if the document expired or does not exist
- *
- * @const string
- */
- const GENERIC_ERROR = 'Document does not exist, has expired or has been deleted.';
- /**
- * configuration
- *
- * @access private
- * @var Configuration
- */
- private $_conf;
- /**
- * error message
- *
- * @access private
- * @var string
- */
- private $_error = '';
- /**
- * status message
- *
- * @access private
- * @var string
- */
- private $_status = '';
- /**
- * status message
- *
- * @access private
- * @var bool
- */
- private $_is_deleted = false;
- /**
- * JSON message
- *
- * @access private
- * @var string
- */
- private $_json = '';
- /**
- * Factory of instance models
- *
- * @access private
- * @var model
- */
- private $_model;
- /**
- * request
- *
- * @access private
- * @var request
- */
- private $_request;
- /**
- * URL base
- *
- * @access private
- * @var string
- */
- private $_urlBase;
- /**
- * constructor
- *
- * initializes and runs PrivateBin
- *
- * @param ?Configuration $config
- *
- * @access public
- * @throws Exception
- */
- public function __construct(?Configuration $config = null)
- {
- if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
- error_log(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION));
- return;
- }
- if (strlen(PATH) < 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
- error_log(I18n::_('%s requires the PATH to end in a "%s". Please update the PATH in your index.php.', I18n::_('PrivateBin'), DIRECTORY_SEPARATOR));
- return;
- }
- // load config (using ini file by default) & initialize required classes
- $this->_conf = $config ?? new Configuration();
- $this->_init();
- switch ($this->_request->getOperation()) {
- case 'create':
- $this->_create();
- break;
- case 'delete':
- $this->_delete(
- $this->_request->getParam('pasteid'),
- $this->_request->getParam('deletetoken')
- );
- break;
- case 'read':
- $this->_read($this->_request->getParam('pasteid'));
- break;
- case 'jsonld':
- $this->_jsonld($this->_request->getParam('jsonld'));
- return;
- case 'yourlsproxy':
- $this->_shortenerproxy(new YourlsProxy($this->_conf, $this->_request->getParam('link')));
- break;
- case 'shlinkproxy':
- $this->_shortenerproxy(new ShlinkProxy($this->_conf, $this->_request->getParam('link')));
- break;
- }
- $this->_setCacheHeaders();
- // output JSON or HTML
- if ($this->_request->isJsonApiCall()) {
- header('Content-type: ' . Request::MIME_JSON);
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
- header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
- header('X-Uncompressed-Content-Length: ' . strlen($this->_json));
- header('Access-Control-Expose-Headers: X-Uncompressed-Content-Length');
- echo $this->_json;
- } else {
- $this->_view();
- }
- }
- /**
- * initialize PrivateBin
- *
- * @access private
- * @throws Exception
- */
- private function _init()
- {
- $this->_model = new Model($this->_conf);
- $this->_request = new Request;
- $this->_urlBase = $this->_request->getRequestUri();
- $this->_setDefaultLanguage();
- $this->_setDefaultTemplate();
- }
- /**
- * Set default language
- *
- * @access private
- */
- private function _setDefaultLanguage()
- {
- $lang = $this->_conf->getKey('languagedefault');
- I18n::setLanguageFallback($lang);
- // force default language, if language selection is disabled and a default is set
- if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
- $_COOKIE['lang'] = $lang;
- setcookie('lang', $lang, array('SameSite' => 'Lax', 'Secure' => true));
- }
- }
- /**
- * Set default template
- *
- * @access private
- */
- private function _setDefaultTemplate()
- {
- $templates = $this->_conf->getKey('availabletemplates');
- $template = $this->_conf->getKey('template');
- TemplateSwitcher::setAvailableTemplates($templates);
- TemplateSwitcher::setTemplateFallback($template);
- // force default template, if template selection is disabled and a default is set
- if (!$this->_conf->getKey('templateselection') && !empty($template)) {
- $_COOKIE['template'] = $template;
- setcookie('template', $template, array('SameSite' => 'Lax', 'Secure' => true));
- }
- }
- /**
- * Turn off browser caching
- *
- * @access private
- */
- private function _setCacheHeaders()
- {
- // set headers to disable caching
- $time = gmdate('D, d M Y H:i:s \G\M\T');
- header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
- header('Pragma: no-cache');
- header('Expires: ' . $time);
- header('Last-Modified: ' . $time);
- header('Vary: Accept');
- }
- /**
- * Store new paste or comment
- *
- * POST contains:
- * JSON encoded object with mandatory keys:
- * v = 2 (version)
- * adata (array)
- * ct (base64 encoded, encrypted text)
- * meta (optional):
- * expire = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:1week)
- * parentid (optional) = in discussions, which comment this comment replies to.
- * pasteid (optional) = in discussions, which paste this comment belongs to.
- *
- * @access private
- * @return string
- */
- private function _create()
- {
- // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
- ServerSalt::setStore($this->_model->getStore());
- TrafficLimiter::setConfiguration($this->_conf);
- TrafficLimiter::setStore($this->_model->getStore());
- try {
- TrafficLimiter::canPass();
- } catch (Exception $e) {
- $this->_return_message(1, $e->getMessage());
- return;
- }
- $data = $this->_request->getData();
- $isComment = array_key_exists('pasteid', $data) &&
- !empty($data['pasteid']) &&
- array_key_exists('parentid', $data) &&
- !empty($data['parentid']);
- if (!FormatV2::isValid($data, $isComment)) {
- $this->_return_message(1, I18n::_('Invalid data.'));
- return;
- }
- $sizelimit = $this->_conf->getKey('sizelimit');
- // Ensure content is not too big.
- if (strlen($data['ct']) > $sizelimit) {
- $this->_return_message(
- 1,
- I18n::_(
- 'Document is limited to %s of encrypted data.',
- Filter::formatHumanReadableSize($sizelimit)
- )
- );
- return;
- }
- // The user posts a comment.
- if ($isComment) {
- $paste = $this->_model->getPaste($data['pasteid']);
- if ($paste->exists()) {
- try {
- $comment = $paste->getComment($data['parentid']);
- $comment->setData($data);
- $comment->store();
- } catch (Exception $e) {
- $this->_return_message(1, $e->getMessage());
- return;
- }
- $this->_return_message(0, $comment->getId());
- } else {
- $this->_return_message(1, I18n::_('Invalid data.'));
- }
- }
- // The user posts a standard paste.
- else {
- try {
- $this->_model->purge();
- } catch (Exception $e) {
- error_log('Error purging documents: ' . $e->getMessage() . PHP_EOL .
- 'Use the administration scripts statistics to find ' .
- 'damaged paste IDs and either delete them or restore them ' .
- 'from backup.');
- }
- $paste = $this->_model->getPaste();
- try {
- $paste->setData($data);
- $paste->store();
- } catch (Exception $e) {
- $this->_return_message(1, $e->getMessage());
- return;
- }
- $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
- }
- }
- /**
- * Delete an existing document
- *
- * @access private
- * @param string $dataid
- * @param string $deletetoken
- */
- private function _delete($dataid, $deletetoken)
- {
- try {
- $paste = $this->_model->getPaste($dataid);
- if ($paste->exists()) {
- // accessing this method ensures that the document would be
- // deleted if it has already expired
- $paste->get();
- if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
- // Document exists and deletion token is valid: Delete the it.
- $paste->delete();
- $this->_status = 'Document was properly deleted.';
- $this->_is_deleted = true;
- } else {
- $this->_error = 'Wrong deletion token. Document was not deleted.';
- }
- } else {
- $this->_error = self::GENERIC_ERROR;
- }
- } catch (Exception $e) {
- $this->_error = $e->getMessage();
- }
- if ($this->_request->isJsonApiCall()) {
- if (empty($this->_error)) {
- $this->_return_message(0, $dataid);
- } else {
- $this->_return_message(1, $this->_error);
- }
- }
- }
- /**
- * Read an existing document, only allowed via a JSON API call
- *
- * @access private
- * @param string $dataid
- */
- private function _read($dataid)
- {
- if (!$this->_request->isJsonApiCall()) {
- return;
- }
- try {
- $paste = $this->_model->getPaste($dataid);
- if ($paste->exists()) {
- $data = $paste->get();
- if (array_key_exists('salt', $data['meta'])) {
- unset($data['meta']['salt']);
- }
- $this->_return_message(0, $dataid, (array) $data);
- } else {
- $this->_return_message(1, self::GENERIC_ERROR);
- }
- } catch (Exception $e) {
- $this->_return_message(1, $e->getMessage());
- }
- }
- /**
- * Display frontend.
- *
- * @access private
- */
- private function _view()
- {
- header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
- header('Cross-Origin-Resource-Policy: same-origin');
- header('Cross-Origin-Embedder-Policy: require-corp');
- // disabled, because it prevents links from a document to the same site to
- // be opened. Didn't work with `same-origin-allow-popups` either.
- // See issue https://github.com/PrivateBin/PrivateBin/issues/970 for details.
- // header('Cross-Origin-Opener-Policy: same-origin');
- header('Permissions-Policy: browsing-topics=()');
- header('Referrer-Policy: no-referrer');
- header('X-Content-Type-Options: nosniff');
- header('X-Frame-Options: deny');
- header('X-XSS-Protection: 1; mode=block');
- // label all the expiration options
- $expire = array();
- foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
- $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
- }
- // translate all the formatter options
- $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
- // set language cookie if that functionality was enabled
- $languageselection = '';
- if ($this->_conf->getKey('languageselection')) {
- $languageselection = I18n::getLanguage();
- setcookie('lang', $languageselection, array('SameSite' => 'Lax', 'Secure' => true));
- }
- // set template cookie if that functionality was enabled
- $templateselection = '';
- if ($this->_conf->getKey('templateselection')) {
- $templateselection = TemplateSwitcher::getTemplate();
- setcookie('template', $templateselection, array('SameSite' => 'Lax', 'Secure' => true));
- }
- // strip policies that are unsupported in meta tag
- $metacspheader = str_replace(
- array(
- 'frame-ancestors \'none\'; ',
- '; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
- ),
- '',
- $this->_conf->getKey('cspheader')
- );
- $page = new View;
- $page->assign('CSPHEADER', $metacspheader);
- $page->assign('ERROR', I18n::_($this->_error));
- $page->assign('NAME', $this->_conf->getKey('name'));
- if (in_array($this->_request->getOperation(), array('shlinkproxy', 'yourlsproxy'), true)) {
- $page->assign('SHORTURL', $this->_status);
- $page->draw('shortenerproxy');
- return;
- }
- $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
- $page->assign('STATUS', I18n::_($this->_status));
- $page->assign('ISDELETED', I18n::_(json_encode($this->_is_deleted)));
- $page->assign('VERSION', self::VERSION);
- $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
- $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
- $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
- $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
- $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
- $page->assign('FORMATTER', $formatters);
- $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
- $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
- $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
- $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
- $page->assign('PASSWORD', $this->_conf->getKey('password'));
- $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
- $page->assign('LANGUAGESELECTION', $languageselection);
- $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
- $page->assign('TEMPLATESELECTION', $templateselection);
- $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
- $page->assign('EXPIRE', $expire);
- $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
- $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
- $page->assign('SHORTENBYDEFAULT', $this->_conf->getKey('shortenbydefault'));
- $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
- $page->assign('EMAIL', $this->_conf->getKey('email'));
- $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
- $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
- $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
- $page->assign('SRI', $this->_conf->getSection('sri'));
- $page->draw(TemplateSwitcher::getTemplate());
- }
- /**
- * outputs requested JSON-LD context
- *
- * @access private
- * @param string $type
- */
- private function _jsonld($type)
- {
- if (!in_array($type, array(
- 'comment',
- 'commentmeta',
- 'paste',
- 'pastemeta',
- 'types',
- ))) {
- $type = '';
- }
- $content = '{}';
- $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
- if (is_readable($file)) {
- $content = str_replace(
- '?jsonld=',
- $this->_urlBase . '?jsonld=',
- file_get_contents($file)
- );
- }
- if ($type === 'types') {
- $content = str_replace(
- implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
- implode('", "', array_keys($this->_conf->getSection('expire_options'))),
- $content
- );
- }
- header('Content-type: application/ld+json');
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Methods: GET');
- echo $content;
- }
- /**
- * Proxies a link using the specified proxy class, and updates the status or error with the response.
- *
- * @access private
- * @param AbstractProxy $proxy The instance of the proxy class.
- */
- private function _shortenerproxy(AbstractProxy $proxy)
- {
- if ($proxy->isError()) {
- $this->_error = $proxy->getError();
- } else {
- $this->_status = $proxy->getUrl();
- }
- }
- /**
- * prepares JSON encoded status message
- *
- * @access private
- * @param int $status
- * @param string $message
- * @param array $other
- */
- private function _return_message($status, $message, $other = array())
- {
- $result = array('status' => $status);
- if ($status) {
- $result['message'] = I18n::_($message);
- } else {
- $result['id'] = $message;
- $result['url'] = $this->_urlBase . '?' . $message;
- }
- $result += $other;
- $this->_json = Json::encode($result);
- }
- }
|