zerobin.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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.21.1
  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.21.1';
  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. * formatter
  47. *
  48. * @access private
  49. * @var string
  50. */
  51. private $_formatter = 'plaintext';
  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. * constructor
  89. *
  90. * initializes and runs ZeroBin
  91. *
  92. * @access public
  93. * @return void
  94. */
  95. public function __construct()
  96. {
  97. if (version_compare(PHP_VERSION, '5.2.6') < 0)
  98. {
  99. throw new Exception(i18n::_('ZeroBin requires php 5.2.6 or above to work. Sorry.'), 1);
  100. }
  101. // load config from ini file
  102. $this->_init();
  103. switch ($this->_request->getOperation())
  104. {
  105. case 'create':
  106. $this->_create();
  107. break;
  108. case 'delete':
  109. $this->_delete(
  110. $this->_request->getParam('pasteid'),
  111. $this->_request->getParam('deletetoken')
  112. );
  113. break;
  114. case 'read':
  115. $this->_read($this->_request->getParam('pasteid'));
  116. break;
  117. }
  118. // output JSON or HTML
  119. if ($this->_request->isJsonApiCall())
  120. {
  121. header('Content-type: application/json');
  122. echo $this->_json;
  123. }
  124. else
  125. {
  126. $this->_view();
  127. }
  128. }
  129. /**
  130. * initialize zerobin
  131. *
  132. * @access private
  133. * @return void
  134. */
  135. private function _init()
  136. {
  137. foreach (array('cfg', 'lib') as $dir)
  138. {
  139. if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) file_put_contents(
  140. PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
  141. 'Allow from none' . PHP_EOL .
  142. 'Deny from all'. PHP_EOL,
  143. LOCK_EX
  144. );
  145. }
  146. $this->_conf = new configuration;
  147. $this->_model = new model($this->_conf);
  148. $this->_request = new request;
  149. }
  150. /**
  151. * Store new paste or comment
  152. *
  153. * POST contains one or both:
  154. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  155. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  156. *
  157. * All optional data will go to meta information:
  158. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  159. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  160. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  161. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  162. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  163. * 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)
  164. * parentid (optional) = in discussion, which comment this comment replies to.
  165. * pasteid (optional) = in discussion, which paste this comment belongs to.
  166. *
  167. * @access private
  168. * @return string
  169. */
  170. private function _create()
  171. {
  172. $error = false;
  173. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  174. trafficlimiter::setConfiguration($this->_conf);
  175. if (!trafficlimiter::canPass()) return $this->_return_message(
  176. 1, i18n::_(
  177. 'Please wait %d seconds between each post.',
  178. $this->_conf->getKey('limit', 'traffic')
  179. )
  180. );
  181. $data = $this->_request->getParam('data');
  182. $attachment = $this->_request->getParam('attachment');
  183. $attachmentname = $this->_request->getParam('attachmentname');
  184. // Ensure content is not too big.
  185. $sizelimit = $this->_conf->getKey('sizelimit');
  186. if (
  187. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  188. ) return $this->_return_message(
  189. 1,
  190. i18n::_(
  191. 'Paste is limited to %s of encrypted data.',
  192. filter::size_humanreadable($sizelimit)
  193. )
  194. );
  195. // The user posts a comment.
  196. $pasteid = $this->_request->getParam('pasteid');
  197. $parentid = $this->_request->getParam('parentid');
  198. if (!empty($pasteid) && !empty($parentid))
  199. {
  200. $paste = $this->_model->getPaste($pasteid);
  201. if ($paste->exists()) {
  202. try {
  203. $comment = $paste->getComment($parentid);
  204. $nickname = $this->_request->getParam('nickname');
  205. if (!empty($nickname)) $comment->setNickname($nickname);
  206. $comment->setData($data);
  207. $comment->store();
  208. } catch(Exception $e) {
  209. return $this->_return_message(1, $e->getMessage());
  210. }
  211. $this->_return_message(0, $comment->getId());
  212. }
  213. else
  214. {
  215. $this->_return_message(1, 'Invalid data.');
  216. }
  217. }
  218. // The user posts a standard paste.
  219. else
  220. {
  221. $paste = $this->_model->getPaste();
  222. try {
  223. $paste->setData($data);
  224. if (!empty($attachment))
  225. {
  226. $paste->setAttachment($attachment);
  227. if (!empty($attachmentname))
  228. $paste->setAttachmentName($attachmentname);
  229. }
  230. $expire = $this->_request->getParam('expire');
  231. if (!empty($expire)) $paste->setExpiration($expire);
  232. $burnafterreading = $this->_request->getParam('burnafterreading');
  233. if (!empty($burnafterreading)) $paste->setBurnafterreading($burnafterreading);
  234. $opendiscussion = $this->_request->getParam('opendiscussion');
  235. if (!empty($opendiscussion)) $paste->setOpendiscussion($opendiscussion);
  236. $formatter = $this->_request->getParam('formatter');
  237. if (!empty($formatter)) $paste->setFormatter($formatter);
  238. $paste->store();
  239. } catch (Exception $e) {
  240. return $this->_return_message(1, $e->getMessage());
  241. }
  242. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  243. }
  244. }
  245. /**
  246. * Delete an existing paste
  247. *
  248. * @access private
  249. * @param string $dataid
  250. * @param string $deletetoken
  251. * @return void
  252. */
  253. private function _delete($dataid, $deletetoken)
  254. {
  255. try {
  256. $paste = $this->_model->getPaste($dataid);
  257. if ($paste->exists())
  258. {
  259. // accessing this property ensures that the paste would be
  260. // deleted if it has already expired
  261. $burnafterreading = $paste->isBurnafterreading();
  262. if ($deletetoken == 'burnafterreading')
  263. {
  264. if ($burnafterreading)
  265. {
  266. $paste->delete();
  267. $this->_return_message(0, $dataid);
  268. }
  269. else
  270. {
  271. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  272. }
  273. }
  274. else
  275. {
  276. // Make sure the token is valid.
  277. serversalt::setPath($this->_conf->getKey('dir', 'traffic'));
  278. if (filter::slow_equals($deletetoken, $paste->getDeleteToken()))
  279. {
  280. // Paste exists and deletion token is valid: Delete the paste.
  281. $paste->delete();
  282. $this->_status = 'Paste was properly deleted.';
  283. }
  284. else
  285. {
  286. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  287. }
  288. }
  289. }
  290. else
  291. {
  292. $this->_error = self::GENERIC_ERROR;
  293. }
  294. } catch (Exception $e) {
  295. $this->_error = $e->getMessage();
  296. }
  297. }
  298. /**
  299. * Read an existing paste or comment
  300. *
  301. * @access private
  302. * @param string $dataid
  303. * @return void
  304. */
  305. private function _read($dataid)
  306. {
  307. try {
  308. $paste = $this->_model->getPaste($dataid);
  309. if ($paste->exists())
  310. {
  311. // The paste itself is the first in the list of encrypted messages.
  312. $messages = array_merge(
  313. array($paste->get()),
  314. $paste->getComments()
  315. );
  316. $this->_data = json_encode($messages);
  317. }
  318. else
  319. {
  320. $this->_error = self::GENERIC_ERROR;
  321. }
  322. } catch (Exception $e) {
  323. $this->_error = $e->getMessage();
  324. }
  325. if ($this->_request->isJsonApiCall())
  326. {
  327. if (strlen($this->_error))
  328. {
  329. $this->_return_message(1, $this->_error);
  330. }
  331. else
  332. {
  333. $this->_return_message(0, $dataid, array('messages' => $messages));
  334. }
  335. }
  336. }
  337. /**
  338. * Display ZeroBin frontend.
  339. *
  340. * @access private
  341. * @return void
  342. */
  343. private function _view()
  344. {
  345. // set headers to disable caching
  346. $time = gmdate('D, d M Y H:i:s \G\M\T');
  347. header('Cache-Control: no-store, no-cache, must-revalidate');
  348. header('Pragma: no-cache');
  349. header('Expires: ' . $time);
  350. header('Last-Modified: ' . $time);
  351. header('Vary: Accept');
  352. // label all the expiration options
  353. $expire = array();
  354. foreach ($this->_conf->getSection('expire_options') as $time => $seconds)
  355. {
  356. $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
  357. }
  358. // translate all the formatter options
  359. $formatters = array_map(array('i18n', 'translate'), $this->_conf->getSection('formatter_options'));
  360. // set language cookie if that functionality was enabled
  361. $languageselection = '';
  362. if ($this->_conf->getKey('languageselection'))
  363. {
  364. $languageselection = i18n::getLanguage();
  365. setcookie('lang', $languageselection);
  366. }
  367. $page = new RainTPL;
  368. $page::$path_replace = false;
  369. // we escape it here because ENT_NOQUOTES can't be used in RainTPL templates
  370. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  371. $page->assign('ERROR', i18n::_($this->_error));
  372. $page->assign('STATUS', i18n::_($this->_status));
  373. $page->assign('VERSION', self::VERSION);
  374. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  375. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  376. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  377. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  378. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  379. $page->assign('FORMATTER', $formatters);
  380. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  381. $page->assign('NOTICE', i18n::_($this->_conf->getKey('notice')));
  382. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  383. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  384. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  385. $page->assign('BASE64JSVERSION', $this->_conf->getKey('base64version'));
  386. $page->assign('LANGUAGESELECTION', $languageselection);
  387. $page->assign('LANGUAGES', i18n::getLanguageLabels(i18n::getAvailableLanguages()));
  388. $page->assign('EXPIRE', $expire);
  389. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  390. $page->draw($this->_conf->getKey('template'));
  391. }
  392. /**
  393. * return JSON encoded message and exit
  394. *
  395. * @access private
  396. * @param bool $status
  397. * @param string $message
  398. * @param array $other
  399. * @return void
  400. */
  401. private function _return_message($status, $message, $other = array())
  402. {
  403. $result = array('status' => $status);
  404. if ($status)
  405. {
  406. $result['message'] = i18n::_($message);
  407. }
  408. else
  409. {
  410. $result['id'] = $message;
  411. $result['url'] = (
  412. array_key_exists('REQUEST_URI', $_SERVER) ? $_SERVER['REQUEST_URI'] : '/'
  413. ) . '?' . $message;
  414. $result['@context'] = 'js/paste.jsonld';
  415. }
  416. $result += $other;
  417. $this->_json = json_encode($result);
  418. }
  419. }