Controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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\TranslatedException;
  14. use PrivateBin\Persistence\ServerSalt;
  15. use PrivateBin\Persistence\TrafficLimiter;
  16. use PrivateBin\Proxy\AbstractProxy;
  17. use PrivateBin\Proxy\ChhotoProxy;
  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.6';
  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. case 'chhotoproxy':
  147. $this->_shortenerproxy(new ChhotoProxy($this->_conf, $this->_request->getParam('link')));
  148. break;
  149. }
  150. $this->_setCacheHeaders();
  151. // output JSON or HTML
  152. if ($this->_request->isJsonApiCall()) {
  153. header('Content-type: ' . Request::MIME_JSON);
  154. header('Access-Control-Allow-Origin: *');
  155. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  156. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  157. header('X-Content-Type-Options: nosniff');
  158. header('X-Uncompressed-Content-Length: ' . strlen($this->_json));
  159. header('Access-Control-Expose-Headers: X-Uncompressed-Content-Length');
  160. echo $this->_json;
  161. } else {
  162. $this->_view();
  163. }
  164. }
  165. /**
  166. * initialize PrivateBin
  167. *
  168. * @access private
  169. * @throws Exception
  170. */
  171. private function _init()
  172. {
  173. $this->_model = new Model($this->_conf);
  174. $this->_request = new Request;
  175. $this->_urlBase = $this->_request->getRequestUri();
  176. $this->_setDefaultLanguage();
  177. $this->_setDefaultTemplate();
  178. }
  179. /**
  180. * Set default language
  181. *
  182. * @access private
  183. * @throws Exception
  184. */
  185. private function _setDefaultLanguage()
  186. {
  187. $lang = $this->_conf->getKey('languagedefault');
  188. I18n::setLanguageFallback($lang);
  189. // force default language, if language selection is disabled and a default is set
  190. if (!$this->_conf->getKey('languageselection') && (
  191. in_array($lang, I18n::getAvailableLanguages(), true) ||
  192. $lang === 'en'
  193. )) {
  194. $_COOKIE['lang'] = $lang;
  195. setcookie('lang', $lang, ['SameSite' => 'Lax', 'Secure' => true]);
  196. }
  197. }
  198. /**
  199. * Set default template
  200. *
  201. * @access private
  202. * @throws Exception
  203. */
  204. private function _setDefaultTemplate()
  205. {
  206. $templates = $this->_conf->getKey('availabletemplates');
  207. $template = $this->_conf->getKey('template');
  208. if (!in_array($template, $templates, true)) {
  209. $templates[] = $template;
  210. }
  211. TemplateSwitcher::setAvailableTemplates($templates);
  212. TemplateSwitcher::setTemplateFallback($template);
  213. // force default template, if template selection is disabled
  214. if (!$this->_conf->getKey('templateselection') && array_key_exists('template', $_COOKIE)) {
  215. unset($_COOKIE['template']); // ensure value is not re-used in template switcher
  216. $expiredInAllTimezones = time() - 86400;
  217. setcookie('template', '', ['expires' => $expiredInAllTimezones, 'SameSite' => 'Lax', 'Secure' => true]);
  218. }
  219. }
  220. /**
  221. * Turn off browser caching
  222. *
  223. * @access private
  224. */
  225. private function _setCacheHeaders()
  226. {
  227. // set headers to disable caching
  228. $time = gmdate('D, d M Y H:i:s \G\M\T');
  229. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  230. header('Pragma: no-cache');
  231. header('Expires: ' . $time);
  232. header('Last-Modified: ' . $time);
  233. header('Vary: Accept');
  234. }
  235. /**
  236. * Store new paste or comment
  237. *
  238. * POST contains:
  239. * JSON encoded object with mandatory keys:
  240. * v = 2 (version)
  241. * adata (array)
  242. * ct (base64 encoded, encrypted text)
  243. * meta (optional):
  244. * expire = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:1week)
  245. * parentid (optional) = in discussions, which comment this comment replies to.
  246. * pasteid (optional) = in discussions, which paste this comment belongs to.
  247. *
  248. * @access private
  249. * @throws Exception
  250. * @return string
  251. */
  252. private function _create()
  253. {
  254. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  255. ServerSalt::setStore($this->_model->getStore());
  256. TrafficLimiter::setConfiguration($this->_conf);
  257. TrafficLimiter::setStore($this->_model->getStore());
  258. try {
  259. TrafficLimiter::canPass();
  260. } catch (TranslatedException $e) {
  261. $this->_json_error($e->getMessage());
  262. return;
  263. }
  264. $data = $this->_request->getData();
  265. $isComment = array_key_exists('pasteid', $data) &&
  266. !empty($data['pasteid']) &&
  267. array_key_exists('parentid', $data) &&
  268. !empty($data['parentid']);
  269. if (!FormatV2::isValid($data, $isComment)) {
  270. $this->_json_error(I18n::_('Invalid data.'));
  271. return;
  272. }
  273. $sizelimit = $this->_conf->getKey('sizelimit');
  274. // Ensure content is not too big.
  275. if (strlen($data['ct']) > $sizelimit) {
  276. $this->_json_error(
  277. I18n::_(
  278. 'Document is limited to %s of encrypted data.',
  279. Filter::formatHumanReadableSize($sizelimit)
  280. )
  281. );
  282. return;
  283. }
  284. // The user posts a comment.
  285. if ($isComment) {
  286. $paste = $this->_model->getPaste($data['pasteid']);
  287. if ($paste->exists()) {
  288. try {
  289. $comment = $paste->getComment($data['parentid']);
  290. $comment->setData($data);
  291. $comment->store();
  292. $this->_json_result($comment->getId());
  293. } catch (Exception $e) {
  294. $this->_json_error($e->getMessage());
  295. }
  296. } else {
  297. $this->_json_error(I18n::_('Invalid data.'));
  298. }
  299. }
  300. // The user posts a standard paste.
  301. else {
  302. try {
  303. $this->_model->purge();
  304. $paste = $this->_model->getPaste();
  305. $paste->setData($data);
  306. $paste->store();
  307. $this->_json_result($paste->getId(), ['deletetoken' => $paste->getDeleteToken()]);
  308. } catch (Exception $e) {
  309. $this->_json_error($e->getMessage());
  310. }
  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 (TranslatedException $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 (TranslatedException $e) {
  373. $this->_json_error($e->getMessage());
  374. }
  375. }
  376. /**
  377. * Display frontend.
  378. *
  379. * @access private
  380. * @throws Exception
  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. // label all the expiration options
  396. $expire = [];
  397. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  398. $expire[$time] = ($seconds === 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  399. }
  400. // translate all the formatter options
  401. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  402. // set language cookie if that functionality was enabled
  403. $languageselection = '';
  404. if ($this->_conf->getKey('languageselection')) {
  405. $languageselection = I18n::getLanguage();
  406. setcookie('lang', $languageselection, ['SameSite' => 'Lax', 'Secure' => true]);
  407. }
  408. // set template cookie if that functionality was enabled
  409. $templateselection = '';
  410. if ($this->_conf->getKey('templateselection')) {
  411. $templateselection = TemplateSwitcher::getTemplate();
  412. setcookie('template', $templateselection, ['SameSite' => 'Lax', 'Secure' => true]);
  413. }
  414. // strip policies that are unsupported in meta tag
  415. $metacspheader = str_replace(
  416. [
  417. 'frame-ancestors \'none\'; ',
  418. '; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
  419. ],
  420. '',
  421. $this->_conf->getKey('cspheader')
  422. );
  423. $page = new View;
  424. $page->assign('CSPHEADER', $metacspheader);
  425. $page->assign('ERROR', I18n::_($this->_error));
  426. $page->assign('NAME', $this->_conf->getKey('name'));
  427. if (in_array($this->_request->getOperation(), ['shlinkproxy', 'yourlsproxy', 'chhotoproxy'], true)) {
  428. $page->assign('SHORTURL', $this->_status);
  429. $page->draw('shortenerproxy');
  430. return;
  431. }
  432. $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
  433. $page->assign('STATUS', I18n::_($this->_status));
  434. $page->assign('ISDELETED', $this->_is_deleted);
  435. $page->assign('VERSION', self::VERSION);
  436. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  437. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  438. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  439. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  440. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  441. $page->assign('FORMATTER', $formatters);
  442. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  443. $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
  444. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  445. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  446. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  447. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  448. $page->assign('LANGUAGESELECTION', $languageselection);
  449. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  450. $page->assign('TEMPLATESELECTION', $templateselection);
  451. $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
  452. $page->assign('EXPIRE', $expire);
  453. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  454. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  455. $page->assign('SHORTENBYDEFAULT', $this->_conf->getKey('shortenbydefault'));
  456. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  457. $page->assign('EMAIL', $this->_conf->getKey('email'));
  458. $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
  459. $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
  460. $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
  461. $page->assign('SRI', $this->_conf->getSection('sri'));
  462. $page->draw(TemplateSwitcher::getTemplate());
  463. }
  464. /**
  465. * outputs requested JSON-LD context
  466. *
  467. * @access private
  468. * @param string $type
  469. */
  470. private function _jsonld($type)
  471. {
  472. if (!in_array($type, [
  473. 'comment',
  474. 'commentmeta',
  475. 'paste',
  476. 'pastemeta',
  477. 'types',
  478. ])) {
  479. $type = '';
  480. }
  481. $content = '{}';
  482. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  483. if (is_readable($file)) {
  484. $content = str_replace(
  485. '?jsonld=',
  486. trim(Json::encode($this->_urlBase), '"') . '?jsonld=',
  487. file_get_contents($file)
  488. );
  489. }
  490. if ($type === 'types') {
  491. $content = str_replace(
  492. implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
  493. implode('", "', array_keys($this->_conf->getSection('expire_options'))),
  494. $content
  495. );
  496. }
  497. header('Content-type: application/ld+json');
  498. header('Access-Control-Allow-Origin: *');
  499. header('Access-Control-Allow-Methods: GET');
  500. header('X-Content-Type-Options: nosniff');
  501. echo $content;
  502. }
  503. /**
  504. * prepares JSON encoded error message
  505. *
  506. * @access private
  507. * @param string $error
  508. * @throws JsonException
  509. */
  510. private function _json_error($error)
  511. {
  512. $result = [
  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. * @throws JsonException
  525. */
  526. private function _json_result($dataid, $other = [])
  527. {
  528. $result = [
  529. 'status' => 0,
  530. 'id' => $dataid,
  531. 'url' => $this->_urlBase . '?' . $dataid,
  532. ] + $other;
  533. $this->_json = Json::encode($result);
  534. }
  535. /**
  536. * Proxies a link using the specified proxy class, and updates the status or error with the response.
  537. *
  538. * @access private
  539. * @param AbstractProxy $proxy The instance of the proxy class.
  540. */
  541. private function _shortenerproxy(AbstractProxy $proxy)
  542. {
  543. if ($proxy->isError()) {
  544. $this->_error = $proxy->getError();
  545. } else {
  546. $this->_status = $proxy->getUrl();
  547. }
  548. }
  549. }