1
0

Controller.php 19 KB

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