zerobin.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.22
  11. */
  12. /**
  13. * zerobin
  14. *
  15. * Controller, puts it all together.
  16. */
  17. class zerobin
  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. * formatter
  54. *
  55. * @access private
  56. * @var string
  57. */
  58. private $_formatter = 'plaintext';
  59. /**
  60. * error message
  61. *
  62. * @access private
  63. * @var string
  64. */
  65. private $_error = '';
  66. /**
  67. * status message
  68. *
  69. * @access private
  70. * @var string
  71. */
  72. private $_status = '';
  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 ZeroBin
  105. *
  106. * @access public
  107. * @return void
  108. */
  109. public function __construct()
  110. {
  111. if (version_compare(PHP_VERSION, '5.2.6') < 0)
  112. {
  113. throw new Exception(i18n::_('ZeroBin requires php 5.2.6 or above to work. Sorry.'), 1);
  114. }
  115. // load config from ini file
  116. $this->_init();
  117. switch ($this->_request->getOperation())
  118. {
  119. case 'create':
  120. $this->_create();
  121. break;
  122. case 'delete':
  123. $this->_delete(
  124. $this->_request->getParam('pasteid'),
  125. $this->_request->getParam('deletetoken')
  126. );
  127. break;
  128. case 'read':
  129. $this->_read($this->_request->getParam('pasteid'));
  130. break;
  131. case 'jsonld':
  132. $this->_jsonld($this->_request->getParam('jsonld'));
  133. return;
  134. }
  135. // output JSON or HTML
  136. if ($this->_request->isJsonApiCall())
  137. {
  138. header('Content-type: application/json');
  139. header('Access-Control-Allow-Origin: *');
  140. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  141. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  142. echo $this->_json;
  143. }
  144. else
  145. {
  146. $this->_view();
  147. }
  148. }
  149. /**
  150. * initialize zerobin
  151. *
  152. * @access private
  153. * @return void
  154. */
  155. private function _init()
  156. {
  157. foreach (array('cfg', 'lib') as $dir)
  158. {
  159. if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) file_put_contents(
  160. PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
  161. 'Allow from none' . PHP_EOL .
  162. 'Deny from all'. PHP_EOL,
  163. LOCK_EX
  164. );
  165. }
  166. $this->_conf = new configuration;
  167. $this->_model = new model($this->_conf);
  168. $this->_request = new request;
  169. $this->_urlbase = array_key_exists('REQUEST_URI', $_SERVER) ? $_SERVER['REQUEST_URI'] : '/';
  170. // set default language
  171. $lang = $this->_conf->getKey('languagedefault');
  172. i18n::setLanguageFallback($lang);
  173. // force default language, if language selection is disabled and a default is set
  174. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2)
  175. {
  176. $_COOKIE['lang'] = $lang;
  177. setcookie('lang', $lang);
  178. }
  179. }
  180. /**
  181. * Store new paste or comment
  182. *
  183. * POST contains one or both:
  184. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  185. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  186. *
  187. * All optional data will go to meta information:
  188. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  189. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  190. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  191. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  192. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  193. * 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)
  194. * parentid (optional) = in discussion, which comment this comment replies to.
  195. * pasteid (optional) = in discussion, which paste this comment belongs to.
  196. *
  197. * @access private
  198. * @return string
  199. */
  200. private function _create()
  201. {
  202. $error = false;
  203. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  204. trafficlimiter::setConfiguration($this->_conf);
  205. if (!trafficlimiter::canPass()) return $this->_return_message(
  206. 1, i18n::_(
  207. 'Please wait %d seconds between each post.',
  208. $this->_conf->getKey('limit', 'traffic')
  209. )
  210. );
  211. $data = $this->_request->getParam('data');
  212. $attachment = $this->_request->getParam('attachment');
  213. $attachmentname = $this->_request->getParam('attachmentname');
  214. // Ensure content is not too big.
  215. $sizelimit = $this->_conf->getKey('sizelimit');
  216. if (
  217. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  218. ) return $this->_return_message(
  219. 1,
  220. i18n::_(
  221. 'Paste is limited to %s of encrypted data.',
  222. filter::size_humanreadable($sizelimit)
  223. )
  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. $paste = $this->_model->getPaste();
  252. try {
  253. $paste->setData($data);
  254. if (!empty($attachment))
  255. {
  256. $paste->setAttachment($attachment);
  257. if (!empty($attachmentname))
  258. $paste->setAttachmentName($attachmentname);
  259. }
  260. $expire = $this->_request->getParam('expire');
  261. if (!empty($expire)) $paste->setExpiration($expire);
  262. $burnafterreading = $this->_request->getParam('burnafterreading');
  263. if (!empty($burnafterreading)) $paste->setBurnafterreading($burnafterreading);
  264. $opendiscussion = $this->_request->getParam('opendiscussion');
  265. if (!empty($opendiscussion)) $paste->setOpendiscussion($opendiscussion);
  266. $formatter = $this->_request->getParam('formatter');
  267. if (!empty($formatter)) $paste->setFormatter($formatter);
  268. $paste->store();
  269. } catch (Exception $e) {
  270. return $this->_return_message(1, $e->getMessage());
  271. }
  272. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  273. }
  274. }
  275. /**
  276. * Delete an existing paste
  277. *
  278. * @access private
  279. * @param string $dataid
  280. * @param string $deletetoken
  281. * @return void
  282. */
  283. private function _delete($dataid, $deletetoken)
  284. {
  285. try {
  286. $paste = $this->_model->getPaste($dataid);
  287. if ($paste->exists())
  288. {
  289. // accessing this property ensures that the paste would be
  290. // deleted if it has already expired
  291. $burnafterreading = $paste->isBurnafterreading();
  292. if ($deletetoken == 'burnafterreading')
  293. {
  294. if ($burnafterreading)
  295. {
  296. $paste->delete();
  297. $this->_return_message(0, $dataid);
  298. }
  299. else
  300. {
  301. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  302. }
  303. }
  304. else
  305. {
  306. // Make sure the token is valid.
  307. serversalt::setPath($this->_conf->getKey('dir', 'traffic'));
  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. $this->_data = json_encode($data);
  344. }
  345. else
  346. {
  347. $this->_error = self::GENERIC_ERROR;
  348. }
  349. } catch (Exception $e) {
  350. $this->_error = $e->getMessage();
  351. }
  352. if ($this->_request->isJsonApiCall())
  353. {
  354. if (strlen($this->_error))
  355. {
  356. $this->_return_message(1, $this->_error);
  357. }
  358. else
  359. {
  360. $this->_return_message(0, $dataid, json_decode($this->_data, true));
  361. }
  362. }
  363. }
  364. /**
  365. * Display ZeroBin frontend.
  366. *
  367. * @access private
  368. * @return void
  369. */
  370. private function _view()
  371. {
  372. // set headers to disable caching
  373. $time = gmdate('D, d M Y H:i:s \G\M\T');
  374. header('Cache-Control: no-store, no-cache, must-revalidate');
  375. header('Pragma: no-cache');
  376. header('Expires: ' . $time);
  377. header('Last-Modified: ' . $time);
  378. header('Vary: Accept');
  379. // label all the expiration options
  380. $expire = array();
  381. foreach ($this->_conf->getSection('expire_options') as $time => $seconds)
  382. {
  383. $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
  384. }
  385. // translate all the formatter options
  386. $formatters = array_map(array('i18n', 'translate'), $this->_conf->getSection('formatter_options'));
  387. // set language cookie if that functionality was enabled
  388. $languageselection = '';
  389. if ($this->_conf->getKey('languageselection'))
  390. {
  391. $languageselection = i18n::getLanguage();
  392. setcookie('lang', $languageselection);
  393. }
  394. $page = new RainTPL;
  395. $page::$path_replace = false;
  396. // we escape it here because ENT_NOQUOTES can't be used in RainTPL templates
  397. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  398. $page->assign('ERROR', i18n::_($this->_error));
  399. $page->assign('STATUS', i18n::_($this->_status));
  400. $page->assign('VERSION', self::VERSION);
  401. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  402. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  403. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  404. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  405. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  406. $page->assign('FORMATTER', $formatters);
  407. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  408. $page->assign('NOTICE', i18n::_($this->_conf->getKey('notice')));
  409. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  410. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  411. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  412. $page->assign('BASE64JSVERSION', $this->_conf->getKey('base64version'));
  413. $page->assign('LANGUAGESELECTION', $languageselection);
  414. $page->assign('LANGUAGES', i18n::getLanguageLabels(i18n::getAvailableLanguages()));
  415. $page->assign('EXPIRE', $expire);
  416. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  417. $page->assign('EXPIRECLONE', !$this->_doesExpire || ($this->_doesExpire && $this->_conf->getKey('clone', 'expire')));
  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 bool $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. }