Controller.php 19 KB

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