zerobin.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. * URL base
  89. *
  90. * @access private
  91. * @var string
  92. */
  93. private $_urlbase;
  94. /**
  95. * constructor
  96. *
  97. * initializes and runs ZeroBin
  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::_('ZeroBin 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: application/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 zerobin
  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) ? $_SERVER['REQUEST_URI'] : '/';
  163. }
  164. /**
  165. * Store new paste or comment
  166. *
  167. * POST contains one or both:
  168. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  169. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  170. *
  171. * All optional data will go to meta information:
  172. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  173. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  174. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  175. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  176. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  177. * 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)
  178. * parentid (optional) = in discussion, which comment this comment replies to.
  179. * pasteid (optional) = in discussion, which paste this comment belongs to.
  180. *
  181. * @access private
  182. * @return string
  183. */
  184. private function _create()
  185. {
  186. $error = false;
  187. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  188. trafficlimiter::setConfiguration($this->_conf);
  189. if (!trafficlimiter::canPass()) return $this->_return_message(
  190. 1, i18n::_(
  191. 'Please wait %d seconds between each post.',
  192. $this->_conf->getKey('limit', 'traffic')
  193. )
  194. );
  195. $data = $this->_request->getParam('data');
  196. $attachment = $this->_request->getParam('attachment');
  197. $attachmentname = $this->_request->getParam('attachmentname');
  198. // Ensure content is not too big.
  199. $sizelimit = $this->_conf->getKey('sizelimit');
  200. if (
  201. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  202. ) return $this->_return_message(
  203. 1,
  204. i18n::_(
  205. 'Paste is limited to %s of encrypted data.',
  206. filter::size_humanreadable($sizelimit)
  207. )
  208. );
  209. // The user posts a comment.
  210. $pasteid = $this->_request->getParam('pasteid');
  211. $parentid = $this->_request->getParam('parentid');
  212. if (!empty($pasteid) && !empty($parentid))
  213. {
  214. $paste = $this->_model->getPaste($pasteid);
  215. if ($paste->exists()) {
  216. try {
  217. $comment = $paste->getComment($parentid);
  218. $nickname = $this->_request->getParam('nickname');
  219. if (!empty($nickname)) $comment->setNickname($nickname);
  220. $comment->setData($data);
  221. $comment->store();
  222. } catch(Exception $e) {
  223. return $this->_return_message(1, $e->getMessage());
  224. }
  225. $this->_return_message(0, $comment->getId());
  226. }
  227. else
  228. {
  229. $this->_return_message(1, 'Invalid data.');
  230. }
  231. }
  232. // The user posts a standard paste.
  233. else
  234. {
  235. $paste = $this->_model->getPaste();
  236. try {
  237. $paste->setData($data);
  238. if (!empty($attachment))
  239. {
  240. $paste->setAttachment($attachment);
  241. if (!empty($attachmentname))
  242. $paste->setAttachmentName($attachmentname);
  243. }
  244. $expire = $this->_request->getParam('expire');
  245. if (!empty($expire)) $paste->setExpiration($expire);
  246. $burnafterreading = $this->_request->getParam('burnafterreading');
  247. if (!empty($burnafterreading)) $paste->setBurnafterreading($burnafterreading);
  248. $opendiscussion = $this->_request->getParam('opendiscussion');
  249. if (!empty($opendiscussion)) $paste->setOpendiscussion($opendiscussion);
  250. $formatter = $this->_request->getParam('formatter');
  251. if (!empty($formatter)) $paste->setFormatter($formatter);
  252. $paste->store();
  253. } catch (Exception $e) {
  254. return $this->_return_message(1, $e->getMessage());
  255. }
  256. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  257. }
  258. }
  259. /**
  260. * Delete an existing paste
  261. *
  262. * @access private
  263. * @param string $dataid
  264. * @param string $deletetoken
  265. * @return void
  266. */
  267. private function _delete($dataid, $deletetoken)
  268. {
  269. try {
  270. $paste = $this->_model->getPaste($dataid);
  271. if ($paste->exists())
  272. {
  273. // accessing this property ensures that the paste would be
  274. // deleted if it has already expired
  275. $burnafterreading = $paste->isBurnafterreading();
  276. if ($deletetoken == 'burnafterreading')
  277. {
  278. if ($burnafterreading)
  279. {
  280. $paste->delete();
  281. $this->_return_message(0, $dataid);
  282. }
  283. else
  284. {
  285. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  286. }
  287. }
  288. else
  289. {
  290. // Make sure the token is valid.
  291. serversalt::setPath($this->_conf->getKey('dir', 'traffic'));
  292. if (filter::slow_equals($deletetoken, $paste->getDeleteToken()))
  293. {
  294. // Paste exists and deletion token is valid: Delete the paste.
  295. $paste->delete();
  296. $this->_status = 'Paste was properly deleted.';
  297. }
  298. else
  299. {
  300. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  301. }
  302. }
  303. }
  304. else
  305. {
  306. $this->_error = self::GENERIC_ERROR;
  307. }
  308. } catch (Exception $e) {
  309. $this->_error = $e->getMessage();
  310. }
  311. }
  312. /**
  313. * Read an existing paste or comment
  314. *
  315. * @access private
  316. * @param string $dataid
  317. * @return void
  318. */
  319. private function _read($dataid)
  320. {
  321. try {
  322. $paste = $this->_model->getPaste($dataid);
  323. if ($paste->exists())
  324. {
  325. $this->_data = json_encode($paste->get());
  326. }
  327. else
  328. {
  329. $this->_error = self::GENERIC_ERROR;
  330. }
  331. } catch (Exception $e) {
  332. $this->_error = $e->getMessage();
  333. }
  334. if ($this->_request->isJsonApiCall())
  335. {
  336. if (strlen($this->_error))
  337. {
  338. $this->_return_message(1, $this->_error);
  339. }
  340. else
  341. {
  342. $this->_return_message(0, $dataid, json_decode($this->_data, true));
  343. }
  344. }
  345. }
  346. /**
  347. * Display ZeroBin frontend.
  348. *
  349. * @access private
  350. * @return void
  351. */
  352. private function _view()
  353. {
  354. // set headers to disable caching
  355. $time = gmdate('D, d M Y H:i:s \G\M\T');
  356. header('Cache-Control: no-store, no-cache, must-revalidate');
  357. header('Pragma: no-cache');
  358. header('Expires: ' . $time);
  359. header('Last-Modified: ' . $time);
  360. header('Vary: Accept');
  361. // label all the expiration options
  362. $expire = array();
  363. foreach ($this->_conf->getSection('expire_options') as $time => $seconds)
  364. {
  365. $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
  366. }
  367. // translate all the formatter options
  368. $formatters = array_map(array('i18n', 'translate'), $this->_conf->getSection('formatter_options'));
  369. // set language cookie if that functionality was enabled
  370. $languageselection = '';
  371. if ($this->_conf->getKey('languageselection'))
  372. {
  373. $languageselection = i18n::getLanguage();
  374. setcookie('lang', $languageselection);
  375. }
  376. $page = new RainTPL;
  377. $page::$path_replace = false;
  378. // we escape it here because ENT_NOQUOTES can't be used in RainTPL templates
  379. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  380. $page->assign('ERROR', i18n::_($this->_error));
  381. $page->assign('STATUS', i18n::_($this->_status));
  382. $page->assign('VERSION', self::VERSION);
  383. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  384. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  385. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  386. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  387. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  388. $page->assign('FORMATTER', $formatters);
  389. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  390. $page->assign('NOTICE', i18n::_($this->_conf->getKey('notice')));
  391. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  392. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  393. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  394. $page->assign('BASE64JSVERSION', $this->_conf->getKey('base64version'));
  395. $page->assign('LANGUAGESELECTION', $languageselection);
  396. $page->assign('LANGUAGES', i18n::getLanguageLabels(i18n::getAvailableLanguages()));
  397. $page->assign('EXPIRE', $expire);
  398. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  399. $page->draw($this->_conf->getKey('template'));
  400. }
  401. private function _jsonld($type)
  402. {
  403. if (
  404. $type !== 'paste' && $type !== 'comment' &&
  405. $type !== 'pastemeta' && $type !== 'commentmeta'
  406. )
  407. {
  408. $type = '';
  409. }
  410. $content = '{}';
  411. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  412. if (is_readable($file))
  413. {
  414. $content = str_replace(
  415. '?jsonld=',
  416. $this->_urlbase . '?jsonld=',
  417. file_get_contents($file)
  418. );
  419. }
  420. header('Content-type: application/ld+json');
  421. header('Access-Control-Allow-Origin: *');
  422. header('Access-Control-Allow-Methods: GET');
  423. echo $content;
  424. }
  425. /**
  426. * return JSON encoded message and exit
  427. *
  428. * @access private
  429. * @param bool $status
  430. * @param string $message
  431. * @param array $other
  432. * @return void
  433. */
  434. private function _return_message($status, $message, $other = array())
  435. {
  436. $result = array('status' => $status);
  437. if ($status)
  438. {
  439. $result['message'] = i18n::_($message);
  440. }
  441. else
  442. {
  443. $result['id'] = $message;
  444. $result['url'] = $this->_urlbase . '?' . $message;
  445. }
  446. $result += $other;
  447. $this->_json = json_encode($result);
  448. }
  449. }