db.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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 http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.22
  11. */
  12. /**
  13. * privatebin_db
  14. *
  15. * Model for DB access, implemented as a singleton.
  16. */
  17. class privatebin_db extends privatebin_abstract
  18. {
  19. /**
  20. * cache for select queries
  21. *
  22. * @var array
  23. */
  24. private static $_cache = array();
  25. /**
  26. * instance of database connection
  27. *
  28. * @access private
  29. * @static
  30. * @var PDO
  31. */
  32. private static $_db;
  33. /**
  34. * table prefix
  35. *
  36. * @access private
  37. * @static
  38. * @var string
  39. */
  40. private static $_prefix = '';
  41. /**
  42. * database type
  43. *
  44. * @access private
  45. * @static
  46. * @var string
  47. */
  48. private static $_type = '';
  49. /**
  50. * get instance of singleton
  51. *
  52. * @access public
  53. * @static
  54. * @param array $options
  55. * @throws Exception
  56. * @return privatebin_db
  57. */
  58. public static function getInstance($options = null)
  59. {
  60. // if needed initialize the singleton
  61. if(!(self::$_instance instanceof privatebin_db)) {
  62. self::$_instance = new self;
  63. }
  64. if (is_array($options))
  65. {
  66. // set table prefix if given
  67. if (array_key_exists('tbl', $options)) self::$_prefix = $options['tbl'];
  68. // initialize the db connection with new options
  69. if (
  70. array_key_exists('dsn', $options) &&
  71. array_key_exists('usr', $options) &&
  72. array_key_exists('pwd', $options) &&
  73. array_key_exists('opt', $options)
  74. )
  75. {
  76. // set default options
  77. $options['opt'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
  78. $options['opt'][PDO::ATTR_EMULATE_PREPARES] = false;
  79. $options['opt'][PDO::ATTR_PERSISTENT] = true;
  80. $db_tables_exist = true;
  81. // setup type and dabase connection
  82. self::$_type = strtolower(
  83. substr($options['dsn'], 0, strpos($options['dsn'], ':'))
  84. );
  85. $tableQuery = self::_getTableQuery(self::$_type);
  86. self::$_db = new PDO(
  87. $options['dsn'],
  88. $options['usr'],
  89. $options['pwd'],
  90. $options['opt']
  91. );
  92. // check if the database contains the required tables
  93. $tables = self::$_db->query($tableQuery)->fetchAll(PDO::FETCH_COLUMN, 0);
  94. // create paste table if necessary
  95. if (!in_array(self::_sanitizeIdentifier('paste'), $tables))
  96. {
  97. self::_createPasteTable();
  98. $db_tables_exist = false;
  99. }
  100. // create comment table if necessary
  101. if (!in_array(self::_sanitizeIdentifier('comment'), $tables))
  102. {
  103. self::_createCommentTable();
  104. $db_tables_exist = false;
  105. }
  106. // create config table if necessary
  107. $db_version = privatebin::VERSION;
  108. if (!in_array(self::_sanitizeIdentifier('config'), $tables))
  109. {
  110. self::_createConfigTable();
  111. // if we only needed to create the config table, the DB is older then 0.22
  112. if ($db_tables_exist) $db_version = '0.21';
  113. }
  114. else
  115. {
  116. $db_version = self::_getConfig('VERSION');
  117. }
  118. // update database structure if necessary
  119. if (version_compare($db_version, privatebin::VERSION, '<'))
  120. {
  121. self::_upgradeDatabase($db_version);
  122. }
  123. }
  124. else
  125. {
  126. throw new Exception(
  127. 'Missing configuration for key dsn, usr, pwd or opt in the section model_options, please check your configuration file', 6
  128. );
  129. }
  130. }
  131. return self::$_instance;
  132. }
  133. /**
  134. * Create a paste.
  135. *
  136. * @access public
  137. * @param string $pasteid
  138. * @param array $paste
  139. * @return bool
  140. */
  141. public function create($pasteid, $paste)
  142. {
  143. if (
  144. array_key_exists($pasteid, self::$_cache)
  145. ) {
  146. if(false !== self::$_cache[$pasteid]) {
  147. return false;
  148. } else {
  149. unset(self::$_cache[$pasteid]);
  150. }
  151. }
  152. $opendiscussion = $burnafterreading = false;
  153. $attachment = $attachmentname = '';
  154. $meta = $paste['meta'];
  155. unset($meta['postdate']);
  156. $expire_date = 0;
  157. if (array_key_exists('expire_date', $paste['meta']))
  158. {
  159. $expire_date = (int) $paste['meta']['expire_date'];
  160. unset($meta['expire_date']);
  161. }
  162. if (array_key_exists('opendiscussion', $paste['meta']))
  163. {
  164. $opendiscussion = (bool) $paste['meta']['opendiscussion'];
  165. unset($meta['opendiscussion']);
  166. }
  167. if (array_key_exists('burnafterreading', $paste['meta']))
  168. {
  169. $burnafterreading = (bool) $paste['meta']['burnafterreading'];
  170. unset($meta['burnafterreading']);
  171. }
  172. if (array_key_exists('attachment', $paste['meta']))
  173. {
  174. $attachment = $paste['meta']['attachment'];
  175. unset($meta['attachment']);
  176. }
  177. if (array_key_exists('attachmentname', $paste['meta']))
  178. {
  179. $attachmentname = $paste['meta']['attachmentname'];
  180. unset($meta['attachmentname']);
  181. }
  182. return self::_exec(
  183. 'INSERT INTO ' . self::_sanitizeIdentifier('paste') .
  184. ' VALUES(?,?,?,?,?,?,?,?,?)',
  185. array(
  186. $pasteid,
  187. $paste['data'],
  188. $paste['meta']['postdate'],
  189. $expire_date,
  190. (int) $opendiscussion,
  191. (int) $burnafterreading,
  192. json_encode($meta),
  193. $attachment,
  194. $attachmentname,
  195. )
  196. );
  197. }
  198. /**
  199. * Read a paste.
  200. *
  201. * @access public
  202. * @param string $pasteid
  203. * @return stdClass|false
  204. */
  205. public function read($pasteid)
  206. {
  207. if (
  208. !array_key_exists($pasteid, self::$_cache)
  209. ) {
  210. self::$_cache[$pasteid] = false;
  211. $paste = self::_select(
  212. 'SELECT * FROM ' . self::_sanitizeIdentifier('paste') .
  213. ' WHERE dataid = ?', array($pasteid), true
  214. );
  215. if(false !== $paste) {
  216. // create object
  217. self::$_cache[$pasteid] = new stdClass;
  218. self::$_cache[$pasteid]->data = $paste['data'];
  219. $meta = json_decode($paste['meta']);
  220. if (!is_object($meta)) $meta = new stdClass;
  221. // support older attachments
  222. if (property_exists($meta, 'attachment'))
  223. {
  224. self::$_cache[$pasteid]->attachment = $meta->attachment;
  225. unset($meta->attachment);
  226. if (property_exists($meta, 'attachmentname'))
  227. {
  228. self::$_cache[$pasteid]->attachmentname = $meta->attachmentname;
  229. unset($meta->attachmentname);
  230. }
  231. }
  232. // support current attachments
  233. elseif (array_key_exists('attachment', $paste) && strlen($paste['attachment']))
  234. {
  235. self::$_cache[$pasteid]->attachment = $paste['attachment'];
  236. if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname']))
  237. {
  238. self::$_cache[$pasteid]->attachmentname = $paste['attachmentname'];
  239. }
  240. }
  241. self::$_cache[$pasteid]->meta = $meta;
  242. self::$_cache[$pasteid]->meta->postdate = (int) $paste['postdate'];
  243. $expire_date = (int) $paste['expiredate'];
  244. if (
  245. $expire_date > 0
  246. ) self::$_cache[$pasteid]->meta->expire_date = $expire_date;
  247. if (
  248. $paste['opendiscussion']
  249. ) self::$_cache[$pasteid]->meta->opendiscussion = true;
  250. if (
  251. $paste['burnafterreading']
  252. ) self::$_cache[$pasteid]->meta->burnafterreading = true;
  253. }
  254. }
  255. return self::$_cache[$pasteid];
  256. }
  257. /**
  258. * Delete a paste and its discussion.
  259. *
  260. * @access public
  261. * @param string $pasteid
  262. * @return void
  263. */
  264. public function delete($pasteid)
  265. {
  266. self::_exec(
  267. 'DELETE FROM ' . self::_sanitizeIdentifier('paste') .
  268. ' WHERE dataid = ?', array($pasteid)
  269. );
  270. self::_exec(
  271. 'DELETE FROM ' . self::_sanitizeIdentifier('comment') .
  272. ' WHERE pasteid = ?', array($pasteid)
  273. );
  274. if (
  275. array_key_exists($pasteid, self::$_cache)
  276. ) unset(self::$_cache[$pasteid]);
  277. }
  278. /**
  279. * Test if a paste exists.
  280. *
  281. * @access public
  282. * @param string $pasteid
  283. * @return void
  284. */
  285. public function exists($pasteid)
  286. {
  287. if (
  288. !array_key_exists($pasteid, self::$_cache)
  289. ) self::$_cache[$pasteid] = $this->read($pasteid);
  290. return (bool) self::$_cache[$pasteid];
  291. }
  292. /**
  293. * Create a comment in a paste.
  294. *
  295. * @access public
  296. * @param string $pasteid
  297. * @param string $parentid
  298. * @param string $commentid
  299. * @param array $comment
  300. * @return bool
  301. */
  302. public function createComment($pasteid, $parentid, $commentid, $comment)
  303. {
  304. return self::_exec(
  305. 'INSERT INTO ' . self::_sanitizeIdentifier('comment') .
  306. ' VALUES(?,?,?,?,?,?,?)',
  307. array(
  308. $commentid,
  309. $pasteid,
  310. $parentid,
  311. $comment['data'],
  312. $comment['meta']['nickname'],
  313. $comment['meta']['vizhash'],
  314. $comment['meta']['postdate'],
  315. )
  316. );
  317. }
  318. /**
  319. * Read all comments of paste.
  320. *
  321. * @access public
  322. * @param string $pasteid
  323. * @return array
  324. */
  325. public function readComments($pasteid)
  326. {
  327. $rows = self::_select(
  328. 'SELECT * FROM ' . self::_sanitizeIdentifier('comment') .
  329. ' WHERE pasteid = ?', array($pasteid)
  330. );
  331. // create comment list
  332. $comments = array();
  333. if (count($rows))
  334. {
  335. foreach ($rows as $row)
  336. {
  337. $i = $this->getOpenSlot($comments, (int) $row['postdate']);
  338. $comments[$i] = new stdClass;
  339. $comments[$i]->id = $row['dataid'];
  340. $comments[$i]->parentid = $row['parentid'];
  341. $comments[$i]->data = $row['data'];
  342. $comments[$i]->meta = new stdClass;
  343. $comments[$i]->meta->postdate = (int) $row['postdate'];
  344. if (array_key_exists('nickname', $row))
  345. $comments[$i]->meta->nickname = $row['nickname'];
  346. if (array_key_exists('vizhash', $row))
  347. $comments[$i]->meta->vizhash = $row['vizhash'];
  348. }
  349. ksort($comments);
  350. }
  351. return $comments;
  352. }
  353. /**
  354. * Test if a comment exists.
  355. *
  356. * @access public
  357. * @param string $pasteid
  358. * @param string $parentid
  359. * @param string $commentid
  360. * @return void
  361. */
  362. public function existsComment($pasteid, $parentid, $commentid)
  363. {
  364. return (bool) self::_select(
  365. 'SELECT dataid FROM ' . self::_sanitizeIdentifier('comment') .
  366. ' WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  367. array($pasteid, $parentid, $commentid), true
  368. );
  369. }
  370. /**
  371. * Returns up to batch size number of paste ids that have expired
  372. *
  373. * @access private
  374. * @param int $batchsize
  375. * @return array
  376. */
  377. protected function _getExpiredPastes($batchsize)
  378. {
  379. $pastes = array();
  380. $rows = self::_select(
  381. 'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') .
  382. ' WHERE expiredate < ? LIMIT ?', array(time(), $batchsize)
  383. );
  384. if (count($rows))
  385. {
  386. foreach ($rows as $row)
  387. {
  388. $pastes[] = $row['dataid'];
  389. }
  390. }
  391. return $pastes;
  392. }
  393. /**
  394. * execute a statement
  395. *
  396. * @access private
  397. * @static
  398. * @param string $sql
  399. * @param array $params
  400. * @throws PDOException
  401. * @return bool
  402. */
  403. private static function _exec($sql, array $params)
  404. {
  405. $statement = self::$_db->prepare($sql);
  406. $result = $statement->execute($params);
  407. $statement->closeCursor();
  408. return $result;
  409. }
  410. /**
  411. * run a select statement
  412. *
  413. * @access private
  414. * @static
  415. * @param string $sql
  416. * @param array $params
  417. * @param bool $firstOnly if only the first row should be returned
  418. * @throws PDOException
  419. * @return array
  420. */
  421. private static function _select($sql, array $params, $firstOnly = false)
  422. {
  423. $statement = self::$_db->prepare($sql);
  424. $statement->execute($params);
  425. $result = $firstOnly ?
  426. $statement->fetch(PDO::FETCH_ASSOC) :
  427. $statement->fetchAll(PDO::FETCH_ASSOC);
  428. $statement->closeCursor();
  429. return $result;
  430. }
  431. /**
  432. * get table list query, depending on the database type
  433. *
  434. * @access private
  435. * @static
  436. * @param string $type
  437. * @throws Exception
  438. * @return string
  439. */
  440. private static function _getTableQuery($type)
  441. {
  442. switch($type)
  443. {
  444. case 'ibm':
  445. $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
  446. break;
  447. case 'informix':
  448. $sql = 'SELECT tabname FROM systables ';
  449. break;
  450. case 'mssql':
  451. $sql = "SELECT name FROM sysobjects "
  452. . "WHERE type = 'U' ORDER BY name";
  453. break;
  454. case 'mysql':
  455. $sql = 'SHOW TABLES';
  456. break;
  457. case 'oci':
  458. $sql = 'SELECT table_name FROM all_tables';
  459. break;
  460. case 'pgsql':
  461. $sql = "SELECT c.relname AS table_name "
  462. . "FROM pg_class c, pg_user u "
  463. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  464. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  465. . "AND c.relname !~ '^(pg_|sql_)' "
  466. . "UNION "
  467. . "SELECT c.relname AS table_name "
  468. . "FROM pg_class c "
  469. . "WHERE c.relkind = 'r' "
  470. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  471. . "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
  472. . "AND c.relname !~ '^pg_'";
  473. break;
  474. case 'sqlite':
  475. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  476. . "UNION ALL SELECT name FROM sqlite_temp_master "
  477. . "WHERE type='table' ORDER BY name";
  478. break;
  479. default:
  480. throw new Exception(
  481. "PDO type $type is currently not supported.", 5
  482. );
  483. }
  484. return $sql;
  485. }
  486. /**
  487. * get a value by key from the config table
  488. *
  489. * @access private
  490. * @static
  491. * @param string $key
  492. * @throws PDOException
  493. * @return string
  494. */
  495. private static function _getConfig($key)
  496. {
  497. $row = self::_select(
  498. 'SELECT value FROM ' . self::_sanitizeIdentifier('config') .
  499. ' WHERE id = ?', array($key), true
  500. );
  501. return $row['value'];
  502. }
  503. /**
  504. * get the primary key clauses, depending on the database driver
  505. *
  506. * @access private
  507. * @static
  508. * @param string $key
  509. * @return array
  510. */
  511. private static function _getPrimaryKeyClauses($key = 'dataid')
  512. {
  513. $main_key = $after_key = '';
  514. if (self::$_type === 'mysql')
  515. {
  516. $after_key = ", PRIMARY KEY ($key)";
  517. }
  518. else
  519. {
  520. $main_key = ' PRIMARY KEY';
  521. }
  522. return array($main_key, $after_key);
  523. }
  524. /**
  525. * create the paste table
  526. *
  527. * @access private
  528. * @static
  529. * @return void
  530. */
  531. private static function _createPasteTable()
  532. {
  533. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  534. self::$_db->exec(
  535. 'CREATE TABLE ' . self::_sanitizeIdentifier('paste') . ' ( ' .
  536. "dataid CHAR(16) NOT NULL$main_key, " .
  537. 'data BLOB, ' .
  538. 'postdate INT, ' .
  539. 'expiredate INT, ' .
  540. 'opendiscussion INT, ' .
  541. 'burnafterreading INT, ' .
  542. 'meta TEXT, ' .
  543. 'attachment MEDIUMBLOB, ' .
  544. "attachmentname BLOB$after_key );"
  545. );
  546. }
  547. /**
  548. * create the paste table
  549. *
  550. * @access private
  551. * @static
  552. * @return void
  553. */
  554. private static function _createCommentTable()
  555. {
  556. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  557. self::$_db->exec(
  558. 'CREATE TABLE ' . self::_sanitizeIdentifier('comment') . ' ( ' .
  559. "dataid CHAR(16) NOT NULL$main_key, " .
  560. 'pasteid CHAR(16), ' .
  561. 'parentid CHAR(16), ' .
  562. 'data BLOB, ' .
  563. 'nickname BLOB, ' .
  564. 'vizhash BLOB, ' .
  565. "postdate INT$after_key );"
  566. );
  567. self::$_db->exec(
  568. 'CREATE INDEX parent ON ' . self::_sanitizeIdentifier('comment') .
  569. '(pasteid);'
  570. );
  571. }
  572. /**
  573. * create the paste table
  574. *
  575. * @access private
  576. * @static
  577. * @return void
  578. */
  579. private static function _createConfigTable()
  580. {
  581. list($main_key, $after_key) = self::_getPrimaryKeyClauses('id');
  582. self::$_db->exec(
  583. 'CREATE TABLE ' . self::_sanitizeIdentifier('config') .
  584. " ( id CHAR(16) NOT NULL$main_key, value TEXT$after_key );"
  585. );
  586. self::_exec(
  587. 'INSERT INTO ' . self::_sanitizeIdentifier('config') .
  588. ' VALUES(?,?)',
  589. array('VERSION', privatebin::VERSION)
  590. );
  591. }
  592. /**
  593. * sanitizes identifiers
  594. *
  595. * @access private
  596. * @static
  597. * @param string $identifier
  598. * @return string
  599. */
  600. private static function _sanitizeIdentifier($identifier)
  601. {
  602. return preg_replace('/[^A-Za-z0-9_]+/', '', self::$_prefix . $identifier);
  603. }
  604. /**
  605. * upgrade the database schema from an old version
  606. *
  607. * @access private
  608. * @static
  609. * @param string $oldversion
  610. * @return void
  611. */
  612. private static function _upgradeDatabase($oldversion)
  613. {
  614. switch ($oldversion)
  615. {
  616. case '0.21':
  617. // create the meta column if necessary (pre 0.21 change)
  618. try {
  619. self::$_db->exec('SELECT meta FROM ' . self::_sanitizeIdentifier('paste') . ' LIMIT 1;');
  620. } catch (PDOException $e) {
  621. self::$_db->exec('ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN meta TEXT;');
  622. }
  623. // SQLite only allows one ALTER statement at a time...
  624. self::$_db->exec(
  625. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN attachment MEDIUMBLOB;'
  626. );
  627. self::$_db->exec(
  628. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN attachmentname BLOB;'
  629. );
  630. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  631. // size as BLOB, so there is no need to change it there
  632. if (self::$_type !== 'sqlite')
  633. {
  634. self::$_db->exec(
  635. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') .
  636. ' ADD PRIMARY KEY (dataid), MODIFY COLUMN data BLOB;'
  637. );
  638. self::$_db->exec(
  639. 'ALTER TABLE ' . self::_sanitizeIdentifier('comment') .
  640. ' ADD PRIMARY KEY (dataid), MODIFY COLUMN data BLOB, ' .
  641. 'MODIFY COLUMN nickname BLOB, MODIFY COLUMN vizhash BLOB;'
  642. );
  643. }
  644. else
  645. {
  646. self::$_db->exec(
  647. 'CREATE UNIQUE INDEX primary ON ' . self::_sanitizeIdentifier('paste') . '(dataid);'
  648. );
  649. self::$_db->exec(
  650. 'CREATE UNIQUE INDEX primary ON ' . self::_sanitizeIdentifier('comment') . '(dataid);'
  651. );
  652. }
  653. self::$_db->exec(
  654. 'CREATE INDEX parent ON ' . self::_sanitizeIdentifier('comment') . '(pasteid);'
  655. );
  656. }
  657. }
  658. }