Controller.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <?php
  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. * @version 1.3.4
  11. */
  12. namespace PrivateBin;
  13. use Exception;
  14. use PrivateBin\Persistence\ServerSalt;
  15. use PrivateBin\Persistence\TrafficLimiter;
  16. /**
  17. * Controller
  18. *
  19. * Puts it all together.
  20. */
  21. class Controller
  22. {
  23. /**
  24. * version
  25. *
  26. * @const string
  27. */
  28. const VERSION = '1.3.4';
  29. /**
  30. * minimal required PHP version
  31. *
  32. * @const string
  33. */
  34. const MIN_PHP_VERSION = '5.6.0';
  35. /**
  36. * show the same error message if the paste expired or does not exist
  37. *
  38. * @const string
  39. */
  40. const GENERIC_ERROR = 'Paste does not exist, has expired or has been deleted.';
  41. /**
  42. * configuration
  43. *
  44. * @access private
  45. * @var Configuration
  46. */
  47. private $_conf;
  48. /**
  49. * error message
  50. *
  51. * @access private
  52. * @var string
  53. */
  54. private $_error = '';
  55. /**
  56. * status message
  57. *
  58. * @access private
  59. * @var string
  60. */
  61. private $_status = '';
  62. /**
  63. * JSON message
  64. *
  65. * @access private
  66. * @var string
  67. */
  68. private $_json = '';
  69. /**
  70. * Factory of instance models
  71. *
  72. * @access private
  73. * @var model
  74. */
  75. private $_model;
  76. /**
  77. * request
  78. *
  79. * @access private
  80. * @var request
  81. */
  82. private $_request;
  83. /**
  84. * URL base
  85. *
  86. * @access private
  87. * @var string
  88. */
  89. private $_urlBase;
  90. /**
  91. * constructor
  92. *
  93. * initializes and runs PrivateBin
  94. *
  95. * @access public
  96. * @throws Exception
  97. */
  98. public function __construct()
  99. {
  100. if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
  101. throw new Exception(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION), 1);
  102. }
  103. if (strlen(PATH) < 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
  104. throw new Exception(I18n::_('%s requires the PATH to end in a "%s". Please update the PATH in your index.php.', I18n::_('PrivateBin'), DIRECTORY_SEPARATOR), 5);
  105. }
  106. // load config from ini file, initialize required classes
  107. $this->_init();
  108. switch ($this->_request->getOperation()) {
  109. case 'create':
  110. $this->_create();
  111. break;
  112. case 'delete':
  113. $this->_delete(
  114. $this->_request->getParam('pasteid'),
  115. $this->_request->getParam('deletetoken')
  116. );
  117. break;
  118. case 'read':
  119. $this->_read($this->_request->getParam('pasteid'));
  120. break;
  121. case 'jsonld':
  122. $this->_jsonld($this->_request->getParam('jsonld'));
  123. return;
  124. }
  125. // output JSON or HTML
  126. if ($this->_request->isJsonApiCall()) {
  127. header('Content-type: ' . Request::MIME_JSON);
  128. header('Access-Control-Allow-Origin: *');
  129. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  130. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  131. echo $this->_json;
  132. } else {
  133. $this->_view();
  134. }
  135. }
  136. /**
  137. * initialize PrivateBin
  138. *
  139. * @access private
  140. * @throws Exception
  141. */
  142. private function _init()
  143. {
  144. $this->_conf = new Configuration;
  145. $this->_model = new Model($this->_conf);
  146. $this->_request = new Request;
  147. $this->_urlBase = $this->_request->getRequestUri();
  148. ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
  149. // set default language
  150. $lang = $this->_conf->getKey('languagedefault');
  151. I18n::setLanguageFallback($lang);
  152. // force default language, if language selection is disabled and a default is set
  153. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
  154. $_COOKIE['lang'] = $lang;
  155. setcookie('lang', $lang);
  156. }
  157. }
  158. /**
  159. * Store new paste or comment
  160. *
  161. * POST contains one or both:
  162. * data = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  163. * attachment = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  164. *
  165. * All optional data will go to meta information:
  166. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  167. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  168. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  169. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  170. * attachmentname = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  171. * nickname (optional) = in discussion, encoded FormatV2 encrypted text nickname of author of comment (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  172. * parentid (optional) = in discussion, which comment this comment replies to.
  173. * pasteid (optional) = in discussion, which paste this comment belongs to.
  174. *
  175. * @access private
  176. * @return string
  177. */
  178. private function _create()
  179. {
  180. try {
  181. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  182. TrafficLimiter::setConfiguration($this->_conf);
  183. if (!TrafficLimiter::canPass()) {
  184. $this->_return_message(
  185. 1, I18n::_(
  186. 'Please wait %d seconds between each post.',
  187. $this->_conf->getKey('limit', 'traffic')
  188. )
  189. );
  190. return;
  191. }
  192. } catch (Exception $e) {
  193. $this->_return_message(1, I18n::_($e->getMessage()));
  194. return;
  195. }
  196. $data = $this->_request->getData();
  197. $isComment = array_key_exists('pasteid', $data) &&
  198. !empty($data['pasteid']) &&
  199. array_key_exists('parentid', $data) &&
  200. !empty($data['parentid']);
  201. if (!FormatV2::isValid($data, $isComment)) {
  202. $this->_return_message(1, I18n::_('Invalid data.'));
  203. return;
  204. }
  205. $sizelimit = $this->_conf->getKey('sizelimit');
  206. // Ensure content is not too big.
  207. if (strlen($data['ct']) > $sizelimit) {
  208. $this->_return_message(
  209. 1,
  210. I18n::_(
  211. 'Paste is limited to %s of encrypted data.',
  212. Filter::formatHumanReadableSize($sizelimit)
  213. )
  214. );
  215. return;
  216. }
  217. // The user posts a comment.
  218. if ($isComment) {
  219. $paste = $this->_model->getPaste($data['pasteid']);
  220. if ($paste->exists()) {
  221. try {
  222. $comment = $paste->getComment($data['parentid']);
  223. $comment->setData($data);
  224. $comment->store();
  225. } catch (Exception $e) {
  226. $this->_return_message(1, $e->getMessage());
  227. return;
  228. }
  229. $this->_return_message(0, $comment->getId());
  230. } else {
  231. $this->_return_message(1, I18n::_('Invalid data.'));
  232. }
  233. }
  234. // The user posts a standard paste.
  235. else {
  236. $this->_model->purge();
  237. $paste = $this->_model->getPaste();
  238. try {
  239. $paste->setData($data);
  240. $paste->store();
  241. } catch (Exception $e) {
  242. return $this->_return_message(1, $e->getMessage());
  243. }
  244. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  245. }
  246. }
  247. /**
  248. * Delete an existing paste
  249. *
  250. * @access private
  251. * @param string $dataid
  252. * @param string $deletetoken
  253. */
  254. private function _delete($dataid, $deletetoken)
  255. {
  256. try {
  257. $paste = $this->_model->getPaste($dataid);
  258. if ($paste->exists()) {
  259. // accessing this method ensures that the paste would be
  260. // deleted if it has already expired
  261. $paste->get();
  262. if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
  263. // Paste exists and deletion token is valid: Delete the paste.
  264. $paste->delete();
  265. $this->_status = 'Paste was properly deleted.';
  266. } else {
  267. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  268. }
  269. } else {
  270. $this->_error = self::GENERIC_ERROR;
  271. }
  272. } catch (Exception $e) {
  273. $this->_error = $e->getMessage();
  274. }
  275. if ($this->_request->isJsonApiCall()) {
  276. if (strlen($this->_error)) {
  277. $this->_return_message(1, $this->_error);
  278. } else {
  279. $this->_return_message(0, $dataid);
  280. }
  281. }
  282. }
  283. /**
  284. * Read an existing paste or comment, only allowed via a JSON API call
  285. *
  286. * @access private
  287. * @param string $dataid
  288. */
  289. private function _read($dataid)
  290. {
  291. if (!$this->_request->isJsonApiCall()) {
  292. return;
  293. }
  294. try {
  295. $paste = $this->_model->getPaste($dataid);
  296. if ($paste->exists()) {
  297. $data = $paste->get();
  298. if (array_key_exists('salt', $data['meta'])) {
  299. unset($data['meta']['salt']);
  300. }
  301. $this->_return_message(0, $dataid, (array) $data);
  302. } else {
  303. $this->_return_message(1, self::GENERIC_ERROR);
  304. }
  305. } catch (Exception $e) {
  306. $this->_return_message(1, $e->getMessage());
  307. }
  308. }
  309. /**
  310. * Display frontend.
  311. *
  312. * @access private
  313. */
  314. private function _view()
  315. {
  316. // set headers to disable caching
  317. $time = gmdate('D, d M Y H:i:s \G\M\T');
  318. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  319. header('Pragma: no-cache');
  320. header('Expires: ' . $time);
  321. header('Last-Modified: ' . $time);
  322. header('Vary: Accept');
  323. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  324. header('Referrer-Policy: no-referrer');
  325. header('X-Xss-Protection: 1; mode=block');
  326. header('X-Frame-Options: DENY');
  327. header('X-Content-Type-Options: nosniff');
  328. // label all the expiration options
  329. $expire = array();
  330. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  331. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  332. }
  333. // translate all the formatter options
  334. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  335. // set language cookie if that functionality was enabled
  336. $languageselection = '';
  337. if ($this->_conf->getKey('languageselection')) {
  338. $languageselection = I18n::getLanguage();
  339. setcookie('lang', $languageselection);
  340. }
  341. $page = new View;
  342. $page->assign('NAME', $this->_conf->getKey('name'));
  343. $page->assign('PATH', I18n::_($this->_conf->getKey('path')));
  344. $page->assign('ERROR', I18n::_($this->_error));
  345. $page->assign('STATUS', I18n::_($this->_status));
  346. $page->assign('VERSION', self::VERSION);
  347. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  348. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  349. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  350. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  351. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  352. $page->assign('FORMATTER', $formatters);
  353. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  354. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  355. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  356. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  357. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  358. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  359. $page->assign('LANGUAGESELECTION', $languageselection);
  360. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  361. $page->assign('EXPIRE', $expire);
  362. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  363. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  364. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  365. $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
  366. $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
  367. $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
  368. $page->draw($this->_conf->getKey('template'));
  369. }
  370. /**
  371. * outputs requested JSON-LD context
  372. *
  373. * @access private
  374. * @param string $type
  375. */
  376. private function _jsonld($type)
  377. {
  378. if (
  379. $type !== 'paste' && $type !== 'comment' &&
  380. $type !== 'pastemeta' && $type !== 'commentmeta'
  381. ) {
  382. $type = '';
  383. }
  384. $content = '{}';
  385. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  386. if (is_readable($file)) {
  387. $content = str_replace(
  388. '?jsonld=',
  389. $this->_urlBase . '?jsonld=',
  390. file_get_contents($file)
  391. );
  392. }
  393. header('Content-type: application/ld+json');
  394. header('Access-Control-Allow-Origin: *');
  395. header('Access-Control-Allow-Methods: GET');
  396. echo $content;
  397. }
  398. /**
  399. * prepares JSON encoded status message
  400. *
  401. * @access private
  402. * @param int $status
  403. * @param string $message
  404. * @param array $other
  405. */
  406. private function _return_message($status, $message, $other = array())
  407. {
  408. $result = array('status' => $status);
  409. if ($status) {
  410. $result['message'] = I18n::_($message);
  411. } else {
  412. $result['id'] = $message;
  413. $result['url'] = $this->_urlBase . '?' . $message;
  414. }
  415. $result += $other;
  416. $this->_json = Json::encode($result);
  417. }
  418. }