privatebin.php 16 KB

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