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