zerobin.php 15 KB

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