Controller.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.2.2
  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.2.2';
  29. /**
  30. * minimal required PHP version
  31. *
  32. * @const string
  33. */
  34. const MIN_PHP_VERSION = '5.4.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. */
  141. private function _init()
  142. {
  143. $this->_conf = new Configuration;
  144. $this->_model = new Model($this->_conf);
  145. $this->_request = new Request;
  146. $this->_urlBase = $this->_request->getRequestUri();
  147. ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
  148. // set default language
  149. $lang = $this->_conf->getKey('languagedefault');
  150. I18n::setLanguageFallback($lang);
  151. // force default language, if language selection is disabled and a default is set
  152. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
  153. $_COOKIE['lang'] = $lang;
  154. setcookie('lang', $lang);
  155. }
  156. }
  157. /**
  158. * Store new paste or comment
  159. *
  160. * POST contains one or both:
  161. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  162. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  163. *
  164. * All optional data will go to meta information:
  165. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  166. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  167. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  168. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  169. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  170. * nickname (optional) = in discussion, encoded SJCL encrypted text nickname of author of comment (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  171. * parentid (optional) = in discussion, which comment this comment replies to.
  172. * pasteid (optional) = in discussion, which paste this comment belongs to.
  173. *
  174. * @access private
  175. * @return string
  176. */
  177. private function _create()
  178. {
  179. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  180. TrafficLimiter::setConfiguration($this->_conf);
  181. if (!TrafficLimiter::canPass()) {
  182. return $this->_return_message(
  183. 1, I18n::_(
  184. 'Please wait %d seconds between each post.',
  185. $this->_conf->getKey('limit', 'traffic')
  186. )
  187. );
  188. }
  189. $data = $this->_request->getParam('data');
  190. $attachment = $this->_request->getParam('attachment');
  191. $attachmentname = $this->_request->getParam('attachmentname');
  192. // Ensure content is not too big.
  193. $sizelimit = $this->_conf->getKey('sizelimit');
  194. if (
  195. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  196. ) {
  197. return $this->_return_message(
  198. 1,
  199. I18n::_(
  200. 'Paste is limited to %s of encrypted data.',
  201. Filter::formatHumanReadableSize($sizelimit)
  202. )
  203. );
  204. }
  205. // Ensure attachment did not get lost due to webserver limits or Suhosin
  206. if (strlen($attachmentname) > 0 && strlen($attachment) == 0) {
  207. return $this->_return_message(1, 'Attachment missing in data received by server. Please check your webserver or suhosin configuration for maximum POST parameter limitations.');
  208. }
  209. // The user posts a comment.
  210. $pasteid = $this->_request->getParam('pasteid');
  211. $parentid = $this->_request->getParam('parentid');
  212. if (!empty($pasteid) && !empty($parentid)) {
  213. $paste = $this->_model->getPaste($pasteid);
  214. if ($paste->exists()) {
  215. try {
  216. $comment = $paste->getComment($parentid);
  217. $nickname = $this->_request->getParam('nickname');
  218. if (!empty($nickname)) {
  219. $comment->setNickname($nickname);
  220. }
  221. $comment->setData($data);
  222. $comment->store();
  223. } catch (Exception $e) {
  224. return $this->_return_message(1, $e->getMessage());
  225. }
  226. $this->_return_message(0, $comment->getId());
  227. } else {
  228. $this->_return_message(1, 'Invalid data.');
  229. }
  230. }
  231. // The user posts a standard paste.
  232. else {
  233. $this->_model->purge();
  234. $paste = $this->_model->getPaste();
  235. try {
  236. $paste->setData($data);
  237. if (!empty($attachment)) {
  238. $paste->setAttachment($attachment);
  239. if (!empty($attachmentname)) {
  240. $paste->setAttachmentName($attachmentname);
  241. }
  242. }
  243. $expire = $this->_request->getParam('expire');
  244. if (!empty($expire)) {
  245. $paste->setExpiration($expire);
  246. }
  247. $burnafterreading = $this->_request->getParam('burnafterreading');
  248. if (!empty($burnafterreading)) {
  249. $paste->setBurnafterreading($burnafterreading);
  250. }
  251. $opendiscussion = $this->_request->getParam('opendiscussion');
  252. if (!empty($opendiscussion)) {
  253. $paste->setOpendiscussion($opendiscussion);
  254. }
  255. $formatter = $this->_request->getParam('formatter');
  256. if (!empty($formatter)) {
  257. $paste->setFormatter($formatter);
  258. }
  259. $paste->store();
  260. } catch (Exception $e) {
  261. return $this->_return_message(1, $e->getMessage());
  262. }
  263. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  264. }
  265. }
  266. /**
  267. * Delete an existing paste
  268. *
  269. * @access private
  270. * @param string $dataid
  271. * @param string $deletetoken
  272. */
  273. private function _delete($dataid, $deletetoken)
  274. {
  275. try {
  276. $paste = $this->_model->getPaste($dataid);
  277. if ($paste->exists()) {
  278. // accessing this property ensures that the paste would be
  279. // deleted if it has already expired
  280. $burnafterreading = $paste->isBurnafterreading();
  281. if (
  282. ($burnafterreading && $deletetoken == 'burnafterreading') || // either we burn-after it has been read //@TODO: not needed anymore now?
  283. Filter::slowEquals($deletetoken, $paste->getDeleteToken()) // or we manually delete it with this secret token
  284. ) {
  285. // Paste exists and deletion token (if required) is valid: Delete the paste.
  286. $paste->delete();
  287. $this->_status = 'Paste was properly deleted.';
  288. } else {
  289. if (!$burnafterreading && $deletetoken == 'burnafterreading') {
  290. $this->_error = 'Paste is not of burn-after-reading type.';
  291. } else {
  292. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  293. }
  294. }
  295. } else {
  296. $this->_error = self::GENERIC_ERROR;
  297. }
  298. } catch (Exception $e) {
  299. $this->_error = $e->getMessage();
  300. }
  301. if ($this->_request->isJsonApiCall()) {
  302. if (strlen($this->_error)) {
  303. $this->_return_message(1, $this->_error);
  304. } else {
  305. $this->_return_message(0, $dataid);
  306. }
  307. }
  308. }
  309. /**
  310. * Read an existing paste or comment, only allowed via a JSON API call
  311. *
  312. * @access private
  313. * @param string $dataid
  314. */
  315. private function _read($dataid)
  316. {
  317. if (!$this->_request->isJsonApiCall()) {
  318. return;
  319. }
  320. try {
  321. $paste = $this->_model->getPaste($dataid);
  322. if ($paste->exists()) {
  323. $data = $paste->get();
  324. if (property_exists($data->meta, 'salt')) {
  325. unset($data->meta->salt);
  326. }
  327. $this->_return_message(0, $dataid, (array) $data);
  328. } else {
  329. $this->_return_message(1, self::GENERIC_ERROR);
  330. }
  331. } catch (Exception $e) {
  332. $this->_return_message(1, $e->getMessage());
  333. }
  334. }
  335. /**
  336. * Display frontend.
  337. *
  338. * @access private
  339. */
  340. private function _view()
  341. {
  342. // set headers to disable caching
  343. $time = gmdate('D, d M Y H:i:s \G\M\T');
  344. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  345. header('Pragma: no-cache');
  346. header('Expires: ' . $time);
  347. header('Last-Modified: ' . $time);
  348. header('Vary: Accept');
  349. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  350. header('X-Xss-Protection: 1; mode=block');
  351. header('X-Frame-Options: DENY');
  352. header('X-Content-Type-Options: nosniff');
  353. // label all the expiration options
  354. $expire = array();
  355. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  356. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  357. }
  358. // translate all the formatter options
  359. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  360. // set language cookie if that functionality was enabled
  361. $languageselection = '';
  362. if ($this->_conf->getKey('languageselection')) {
  363. $languageselection = I18n::getLanguage();
  364. setcookie('lang', $languageselection);
  365. }
  366. $page = new View;
  367. $page->assign('NAME', $this->_conf->getKey('name'));
  368. $page->assign('ERROR', I18n::_($this->_error));
  369. $page->assign('STATUS', I18n::_($this->_status));
  370. $page->assign('VERSION', self::VERSION);
  371. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  372. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  373. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  374. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  375. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  376. $page->assign('FORMATTER', $formatters);
  377. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  378. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  379. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  380. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  381. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  382. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  383. $page->assign('LANGUAGESELECTION', $languageselection);
  384. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  385. $page->assign('EXPIRE', $expire);
  386. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  387. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  388. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  389. $page->draw($this->_conf->getKey('template'));
  390. }
  391. /**
  392. * outputs requested JSON-LD context
  393. *
  394. * @access private
  395. * @param string $type
  396. */
  397. private function _jsonld($type)
  398. {
  399. if (
  400. $type !== 'paste' && $type !== 'comment' &&
  401. $type !== 'pastemeta' && $type !== 'commentmeta'
  402. ) {
  403. $type = '';
  404. }
  405. $content = '{}';
  406. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  407. if (is_readable($file)) {
  408. $content = str_replace(
  409. '?jsonld=',
  410. $this->_urlBase . '?jsonld=',
  411. file_get_contents($file)
  412. );
  413. }
  414. header('Content-type: application/ld+json');
  415. header('Access-Control-Allow-Origin: *');
  416. header('Access-Control-Allow-Methods: GET');
  417. echo $content;
  418. }
  419. /**
  420. * prepares JSON encoded status message
  421. *
  422. * @access private
  423. * @param int $status
  424. * @param string $message
  425. * @param array $other
  426. */
  427. private function _return_message($status, $message, $other = array())
  428. {
  429. $result = array('status' => $status);
  430. if ($status) {
  431. $result['message'] = I18n::_($message);
  432. } else {
  433. $result['id'] = $message;
  434. $result['url'] = $this->_urlBase . '?' . $message;
  435. }
  436. $result += $other;
  437. $this->_json = json_encode($result);
  438. }
  439. }