1
0

Database.php 22 KB

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