Controller.php 19 KB

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