1
0

Controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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.1.0';
  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, '<')) {
  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. $data = [];
  259. try {
  260. TrafficLimiter::canPass();
  261. $data = $this->_request->getData($this->_conf->getKey('sizelimit'));
  262. } catch (TranslatedException $e) {
  263. $this->_json_error($e->getMessage());
  264. return;
  265. }
  266. $isComment = array_key_exists('pasteid', $data) &&
  267. !empty($data['pasteid']) &&
  268. array_key_exists('parentid', $data) &&
  269. !empty($data['parentid']);
  270. if (!FormatV2::isValid($data, $isComment)) {
  271. $this->_json_error(I18n::_('Invalid data.'));
  272. return;
  273. }
  274. // The user posts a comment.
  275. if ($isComment) {
  276. $paste = $this->_model->getPaste($data['pasteid']);
  277. if ($paste->exists()) {
  278. try {
  279. $comment = $paste->getComment($data['parentid']);
  280. $comment->setData($data);
  281. $comment->store();
  282. $this->_json_result($comment->getId());
  283. } catch (Exception $e) {
  284. $this->_json_error($e->getMessage());
  285. }
  286. } else {
  287. $this->_json_error(I18n::_('Invalid data.'));
  288. }
  289. }
  290. // The user posts a standard paste.
  291. else {
  292. try {
  293. $this->_model->purge();
  294. $paste = $this->_model->getPaste();
  295. $paste->setData($data);
  296. $paste->store();
  297. $this->_json_result($paste->getId(), ['deletetoken' => $paste->getDeleteToken()]);
  298. } catch (Exception $e) {
  299. $this->_json_error($e->getMessage());
  300. }
  301. }
  302. }
  303. /**
  304. * Delete an existing document
  305. *
  306. * @access private
  307. * @param string $dataid
  308. * @param string $deletetoken
  309. */
  310. private function _delete($dataid, $deletetoken)
  311. {
  312. try {
  313. $paste = $this->_model->getPaste($dataid);
  314. if ($paste->exists()) {
  315. // accessing this method ensures that the document would be
  316. // deleted if it has already expired
  317. $paste->get();
  318. if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
  319. // Document exists and deletion token is valid: Delete the it.
  320. $paste->delete();
  321. $this->_status = 'Document was properly deleted.';
  322. $this->_is_deleted = true;
  323. } else {
  324. $this->_error = 'Wrong deletion token. Document was not deleted.';
  325. }
  326. } else {
  327. $this->_error = self::GENERIC_ERROR;
  328. }
  329. } catch (TranslatedException $e) {
  330. $this->_error = $e->getMessage();
  331. }
  332. if ($this->_request->isJsonApiCall()) {
  333. if (empty($this->_error)) {
  334. $this->_json_result($dataid);
  335. } else {
  336. $this->_json_error(I18n::_($this->_error));
  337. }
  338. }
  339. }
  340. /**
  341. * Read an existing document, only allowed via a JSON API call
  342. *
  343. * @access private
  344. * @param string $dataid
  345. */
  346. private function _read($dataid)
  347. {
  348. if (!$this->_request->isJsonApiCall()) {
  349. return;
  350. }
  351. try {
  352. $paste = $this->_model->getPaste($dataid);
  353. if ($paste->exists()) {
  354. $data = $paste->get();
  355. if (array_key_exists('salt', $data['meta'])) {
  356. unset($data['meta']['salt']);
  357. }
  358. $this->_json_result($dataid, (array) $data);
  359. } else {
  360. $this->_json_error(I18n::_(self::GENERIC_ERROR));
  361. }
  362. } catch (TranslatedException $e) {
  363. $this->_json_error($e->getMessage());
  364. }
  365. }
  366. /**
  367. * Display frontend.
  368. *
  369. * @access private
  370. * @throws Exception
  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. // label all the expiration options
  386. $expire = [];
  387. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  388. $expire[$time] = ($seconds === 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  389. }
  390. // translate all the formatter options
  391. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  392. // set language cookie if that functionality was enabled
  393. $languageselection = '';
  394. if ($this->_conf->getKey('languageselection')) {
  395. $languageselection = I18n::getLanguage();
  396. setcookie('lang', $languageselection, ['SameSite' => 'Lax', 'Secure' => true]);
  397. }
  398. // set template cookie if that functionality was enabled
  399. $templateselection = '';
  400. if ($this->_conf->getKey('templateselection')) {
  401. $templateselection = TemplateSwitcher::getTemplate();
  402. setcookie('template', $templateselection, ['SameSite' => 'Lax', 'Secure' => true]);
  403. }
  404. // strip policies that are unsupported in meta tag
  405. $metacspheader = str_replace(
  406. [
  407. 'frame-ancestors \'none\'; ',
  408. '; sandbox allow-same-origin allow-scripts allow-forms allow-modals allow-downloads',
  409. ],
  410. '',
  411. $this->_conf->getKey('cspheader')
  412. );
  413. $page = new View;
  414. $page->assign('CSPHEADER', $metacspheader);
  415. $page->assign('ERROR', I18n::_($this->_error));
  416. $page->assign('NAME', $this->_conf->getKey('name'));
  417. if (in_array($this->_request->getOperation(), ['shlinkproxy', 'yourlsproxy', 'chhotoproxy'], true)) {
  418. $page->assign('SHORTURL', $this->_status);
  419. $page->draw('shortenerproxy');
  420. return;
  421. }
  422. $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
  423. $page->assign('STATUS', I18n::_($this->_status));
  424. $page->assign('ISDELETED', $this->_is_deleted);
  425. $page->assign('VERSION', self::VERSION);
  426. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  427. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  428. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  429. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  430. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  431. $page->assign('FORMATTER', $formatters);
  432. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  433. $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
  434. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  435. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  436. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  437. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  438. $page->assign('LANGUAGESELECTION', $languageselection);
  439. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  440. $page->assign('TEMPLATESELECTION', $templateselection);
  441. $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
  442. $page->assign('EXPIRE', $expire);
  443. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  444. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  445. $page->assign('SHORTENBYDEFAULT', $this->_conf->getKey('shortenbydefault'));
  446. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  447. $page->assign('EMAIL', $this->_conf->getKey('email'));
  448. $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
  449. $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
  450. $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
  451. $page->assign('SRI', $this->_conf->getSection('sri'));
  452. $page->draw(TemplateSwitcher::getTemplate());
  453. }
  454. /**
  455. * outputs requested JSON-LD context
  456. *
  457. * @access private
  458. * @param string $type
  459. */
  460. private function _jsonld($type)
  461. {
  462. if (!in_array($type, [
  463. 'comment',
  464. 'commentmeta',
  465. 'paste',
  466. 'pastemeta',
  467. 'types',
  468. ])) {
  469. $type = '';
  470. }
  471. $content = '{}';
  472. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  473. if (is_readable($file)) {
  474. $content = str_replace(
  475. '?jsonld=',
  476. trim(Json::encode($this->_urlBase), '"') . '?jsonld=',
  477. file_get_contents($file)
  478. );
  479. }
  480. if ($type === 'types') {
  481. $content = str_replace(
  482. implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
  483. implode('", "', array_keys($this->_conf->getSection('expire_options'))),
  484. $content
  485. );
  486. }
  487. header('Content-type: application/ld+json');
  488. header('Access-Control-Allow-Origin: *');
  489. header('Access-Control-Allow-Methods: GET');
  490. header('X-Content-Type-Options: nosniff');
  491. echo $content;
  492. }
  493. /**
  494. * prepares JSON encoded error message
  495. *
  496. * @access private
  497. * @param string $error
  498. * @throws JsonException
  499. */
  500. private function _json_error($error)
  501. {
  502. $result = [
  503. 'status' => 1,
  504. 'message' => $error,
  505. ];
  506. $this->_json = Json::encode($result);
  507. }
  508. /**
  509. * prepares JSON encoded result message
  510. *
  511. * @access private
  512. * @param string $dataid
  513. * @param array $other
  514. * @throws JsonException
  515. */
  516. private function _json_result($dataid, $other = [])
  517. {
  518. $result = [
  519. 'status' => 0,
  520. 'id' => $dataid,
  521. 'url' => $this->_urlBase . '?' . $dataid,
  522. ] + $other;
  523. $this->_json = Json::encode($result);
  524. }
  525. /**
  526. * Proxies a link using the specified proxy class, and updates the status or error with the response.
  527. *
  528. * @access private
  529. * @param AbstractProxy $proxy The instance of the proxy class.
  530. */
  531. private function _shortenerproxy(AbstractProxy $proxy)
  532. {
  533. if ($proxy->isError()) {
  534. $this->_error = $proxy->getError();
  535. } else {
  536. $this->_status = $proxy->getUrl();
  537. }
  538. }
  539. }