privatebin.php 16 KB

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