1
0

Controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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.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. 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') && strlen($lang) === 2) {
  191. $_COOKIE['lang'] = $lang;
  192. setcookie('lang', $lang, ['SameSite' => 'Lax', 'Secure' => true]);
  193. }
  194. }
  195. /**
  196. * Set default template
  197. *
  198. * @access private
  199. * @throws Exception
  200. */
  201. private function _setDefaultTemplate()
  202. {
  203. $templates = $this->_conf->getKey('availabletemplates');
  204. $template = $this->_conf->getKey('template');
  205. if (!in_array($template, $templates, true)) {
  206. $templates[] = $template;
  207. }
  208. TemplateSwitcher::setAvailableTemplates($templates);
  209. TemplateSwitcher::setTemplateFallback($template);
  210. // force default template, if template selection is disabled
  211. if (!$this->_conf->getKey('templateselection') && array_key_exists('template', $_COOKIE)) {
  212. unset($_COOKIE['template']); // ensure value is not re-used in template switcher
  213. $expiredInAllTimezones = time() - 86400;
  214. setcookie('template', '', ['expires' => $expiredInAllTimezones, 'SameSite' => 'Lax', 'Secure' => true]);
  215. }
  216. }
  217. /**
  218. * Turn off browser caching
  219. *
  220. * @access private
  221. */
  222. private function _setCacheHeaders()
  223. {
  224. // set headers to disable caching
  225. $time = gmdate('D, d M Y H:i:s \G\M\T');
  226. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  227. header('Pragma: no-cache');
  228. header('Expires: ' . $time);
  229. header('Last-Modified: ' . $time);
  230. header('Vary: Accept');
  231. }
  232. /**
  233. * Store new paste or comment
  234. *
  235. * POST contains:
  236. * JSON encoded object with mandatory keys:
  237. * v = 2 (version)
  238. * adata (array)
  239. * ct (base64 encoded, encrypted text)
  240. * meta (optional):
  241. * expire = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:1week)
  242. * parentid (optional) = in discussions, which comment this comment replies to.
  243. * pasteid (optional) = in discussions, which paste this comment belongs to.
  244. *
  245. * @access private
  246. * @throws Exception
  247. * @return string
  248. */
  249. private function _create()
  250. {
  251. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  252. ServerSalt::setStore($this->_model->getStore());
  253. TrafficLimiter::setConfiguration($this->_conf);
  254. TrafficLimiter::setStore($this->_model->getStore());
  255. try {
  256. TrafficLimiter::canPass();
  257. } catch (TranslatedException $e) {
  258. $this->_json_error($e->getMessage());
  259. return;
  260. }
  261. $data = $this->_request->getData();
  262. $isComment = array_key_exists('pasteid', $data) &&
  263. !empty($data['pasteid']) &&
  264. array_key_exists('parentid', $data) &&
  265. !empty($data['parentid']);
  266. if (!FormatV2::isValid($data, $isComment)) {
  267. $this->_json_error(I18n::_('Invalid data.'));
  268. return;
  269. }
  270. $sizelimit = $this->_conf->getKey('sizelimit');
  271. // Ensure content is not too big.
  272. if (strlen($data['ct']) > $sizelimit) {
  273. $this->_json_error(
  274. I18n::_(
  275. 'Document is limited to %s of encrypted data.',
  276. Filter::formatHumanReadableSize($sizelimit)
  277. )
  278. );
  279. return;
  280. }
  281. // The user posts a comment.
  282. if ($isComment) {
  283. $paste = $this->_model->getPaste($data['pasteid']);
  284. if ($paste->exists()) {
  285. try {
  286. $comment = $paste->getComment($data['parentid']);
  287. $comment->setData($data);
  288. $comment->store();
  289. $this->_json_result($comment->getId());
  290. } catch (Exception $e) {
  291. $this->_json_error($e->getMessage());
  292. }
  293. } else {
  294. $this->_json_error(I18n::_('Invalid data.'));
  295. }
  296. }
  297. // The user posts a standard paste.
  298. else {
  299. try {
  300. $this->_model->purge();
  301. $paste = $this->_model->getPaste();
  302. $paste->setData($data);
  303. $paste->store();
  304. $this->_json_result($paste->getId(), ['deletetoken' => $paste->getDeleteToken()]);
  305. } catch (Exception $e) {
  306. $this->_json_error($e->getMessage());
  307. }
  308. }
  309. }
  310. /**
  311. * Delete an existing document
  312. *
  313. * @access private
  314. * @param string $dataid
  315. * @param string $deletetoken
  316. */
  317. private function _delete($dataid, $deletetoken)
  318. {
  319. try {
  320. $paste = $this->_model->getPaste($dataid);
  321. if ($paste->exists()) {
  322. // accessing this method ensures that the document would be
  323. // deleted if it has already expired
  324. $paste->get();
  325. if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
  326. // Document exists and deletion token is valid: Delete the it.
  327. $paste->delete();
  328. $this->_status = 'Document was properly deleted.';
  329. $this->_is_deleted = true;
  330. } else {
  331. $this->_error = 'Wrong deletion token. Document was not deleted.';
  332. }
  333. } else {
  334. $this->_error = self::GENERIC_ERROR;
  335. }
  336. } catch (TranslatedException $e) {
  337. $this->_error = $e->getMessage();
  338. }
  339. if ($this->_request->isJsonApiCall()) {
  340. if (empty($this->_error)) {
  341. $this->_json_result($dataid);
  342. } else {
  343. $this->_json_error(I18n::_($this->_error));
  344. }
  345. }
  346. }
  347. /**
  348. * Read an existing document, only allowed via a JSON API call
  349. *
  350. * @access private
  351. * @param string $dataid
  352. */
  353. private function _read($dataid)
  354. {
  355. if (!$this->_request->isJsonApiCall()) {
  356. return;
  357. }
  358. try {
  359. $paste = $this->_model->getPaste($dataid);
  360. if ($paste->exists()) {
  361. $data = $paste->get();
  362. if (array_key_exists('salt', $data['meta'])) {
  363. unset($data['meta']['salt']);
  364. }
  365. $this->_json_result($dataid, (array) $data);
  366. } else {
  367. $this->_json_error(I18n::_(self::GENERIC_ERROR));
  368. }
  369. } catch (TranslatedException $e) {
  370. $this->_json_error($e->getMessage());
  371. }
  372. }
  373. /**
  374. * Display frontend.
  375. *
  376. * @access private
  377. * @throws Exception
  378. */
  379. private function _view()
  380. {
  381. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  382. header('Cross-Origin-Resource-Policy: same-origin');
  383. header('Cross-Origin-Embedder-Policy: require-corp');
  384. // disabled, because it prevents links from a document to the same site to
  385. // be opened. Didn't work with `same-origin-allow-popups` either.
  386. // See issue https://github.com/PrivateBin/PrivateBin/issues/970 for details.
  387. // header('Cross-Origin-Opener-Policy: same-origin');
  388. header('Permissions-Policy: browsing-topics=()');
  389. header('Referrer-Policy: no-referrer');
  390. header('X-Content-Type-Options: nosniff');
  391. header('X-Frame-Options: deny');
  392. // label all the expiration options
  393. $expire = [];
  394. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  395. $expire[$time] = ($seconds === 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  396. }
  397. // translate all the formatter options
  398. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  399. // set language cookie if that functionality was enabled
  400. $languageselection = '';
  401. if ($this->_conf->getKey('languageselection')) {
  402. $languageselection = I18n::getLanguage();
  403. setcookie('lang', $languageselection, ['SameSite' => 'Lax', 'Secure' => true]);
  404. }
  405. // set template cookie if that functionality was enabled
  406. $templateselection = '';
  407. if ($this->_conf->getKey('templateselection')) {
  408. $templateselection = TemplateSwitcher::getTemplate();
  409. setcookie('template', $templateselection, ['SameSite' => 'Lax', 'Secure' => true]);
  410. }
  411. // strip policies that are unsupported in meta tag
  412. $metacspheader = str_replace(
  413. [
  414. 'frame-ancestors \'none\'; ',
  415. '; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
  416. ],
  417. '',
  418. $this->_conf->getKey('cspheader')
  419. );
  420. $page = new View;
  421. $page->assign('CSPHEADER', $metacspheader);
  422. $page->assign('ERROR', I18n::_($this->_error));
  423. $page->assign('NAME', $this->_conf->getKey('name'));
  424. if (in_array($this->_request->getOperation(), ['shlinkproxy', 'yourlsproxy', 'chhotoproxy'], true)) {
  425. $page->assign('SHORTURL', $this->_status);
  426. $page->draw('shortenerproxy');
  427. return;
  428. }
  429. $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
  430. $page->assign('STATUS', I18n::_($this->_status));
  431. $page->assign('ISDELETED', $this->_is_deleted);
  432. $page->assign('VERSION', self::VERSION);
  433. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  434. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  435. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  436. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  437. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  438. $page->assign('FORMATTER', $formatters);
  439. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  440. $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
  441. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  442. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  443. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  444. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  445. $page->assign('LANGUAGESELECTION', $languageselection);
  446. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  447. $page->assign('TEMPLATESELECTION', $templateselection);
  448. $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
  449. $page->assign('EXPIRE', $expire);
  450. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  451. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  452. $page->assign('SHORTENBYDEFAULT', $this->_conf->getKey('shortenbydefault'));
  453. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  454. $page->assign('EMAIL', $this->_conf->getKey('email'));
  455. $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
  456. $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
  457. $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
  458. $page->assign('SRI', $this->_conf->getSection('sri'));
  459. $page->draw(TemplateSwitcher::getTemplate());
  460. }
  461. /**
  462. * outputs requested JSON-LD context
  463. *
  464. * @access private
  465. * @param string $type
  466. */
  467. private function _jsonld($type)
  468. {
  469. if (!in_array($type, [
  470. 'comment',
  471. 'commentmeta',
  472. 'paste',
  473. 'pastemeta',
  474. 'types',
  475. ])) {
  476. $type = '';
  477. }
  478. $content = '{}';
  479. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  480. if (is_readable($file)) {
  481. $content = str_replace(
  482. '?jsonld=',
  483. trim(Json::encode($this->_urlBase), '"') . '?jsonld=',
  484. file_get_contents($file)
  485. );
  486. }
  487. if ($type === 'types') {
  488. $content = str_replace(
  489. implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
  490. implode('", "', array_keys($this->_conf->getSection('expire_options'))),
  491. $content
  492. );
  493. }
  494. header('Content-type: application/ld+json');
  495. header('Access-Control-Allow-Origin: *');
  496. header('Access-Control-Allow-Methods: GET');
  497. header('X-Content-Type-Options: nosniff');
  498. echo $content;
  499. }
  500. /**
  501. * prepares JSON encoded error message
  502. *
  503. * @access private
  504. * @param string $error
  505. * @throws JsonException
  506. */
  507. private function _json_error($error)
  508. {
  509. $result = [
  510. 'status' => 1,
  511. 'message' => $error,
  512. ];
  513. $this->_json = Json::encode($result);
  514. }
  515. /**
  516. * prepares JSON encoded result message
  517. *
  518. * @access private
  519. * @param string $dataid
  520. * @param array $other
  521. * @throws JsonException
  522. */
  523. private function _json_result($dataid, $other = [])
  524. {
  525. $result = [
  526. 'status' => 0,
  527. 'id' => $dataid,
  528. 'url' => $this->_urlBase . '?' . $dataid,
  529. ] + $other;
  530. $this->_json = Json::encode($result);
  531. }
  532. /**
  533. * Proxies a link using the specified proxy class, and updates the status or error with the response.
  534. *
  535. * @access private
  536. * @param AbstractProxy $proxy The instance of the proxy class.
  537. */
  538. private function _shortenerproxy(AbstractProxy $proxy)
  539. {
  540. if ($proxy->isError()) {
  541. $this->_error = $proxy->getError();
  542. } else {
  543. $this->_status = $proxy->getUrl();
  544. }
  545. }
  546. }