db.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. foreach (array('nickname', 'vizhash') as $key)
  305. {
  306. if (!array_key_exists($key, $comment['meta']))
  307. {
  308. $comment['meta'][$key] = null;
  309. }
  310. }
  311. return self::_exec(
  312. 'INSERT INTO ' . self::_sanitizeIdentifier('comment') .
  313. ' VALUES(?,?,?,?,?,?,?)',
  314. array(
  315. $commentid,
  316. $pasteid,
  317. $parentid,
  318. $comment['data'],
  319. $comment['meta']['nickname'],
  320. $comment['meta']['vizhash'],
  321. $comment['meta']['postdate'],
  322. )
  323. );
  324. }
  325. /**
  326. * Read all comments of paste.
  327. *
  328. * @access public
  329. * @param string $pasteid
  330. * @return array
  331. */
  332. public function readComments($pasteid)
  333. {
  334. $rows = self::_select(
  335. 'SELECT * FROM ' . self::_sanitizeIdentifier('comment') .
  336. ' WHERE pasteid = ?', array($pasteid)
  337. );
  338. // create comment list
  339. $comments = array();
  340. if (count($rows))
  341. {
  342. foreach ($rows as $row)
  343. {
  344. $i = $this->getOpenSlot($comments, (int) $row['postdate']);
  345. $comments[$i] = new stdClass;
  346. $comments[$i]->id = $row['dataid'];
  347. $comments[$i]->parentid = $row['parentid'];
  348. $comments[$i]->data = $row['data'];
  349. $comments[$i]->meta = new stdClass;
  350. $comments[$i]->meta->postdate = (int) $row['postdate'];
  351. if (array_key_exists('nickname', $row) && !empty($row['nickname']))
  352. $comments[$i]->meta->nickname = $row['nickname'];
  353. if (array_key_exists('vizhash', $row) && !empty($row['vizhash']))
  354. $comments[$i]->meta->vizhash = $row['vizhash'];
  355. }
  356. ksort($comments);
  357. }
  358. return $comments;
  359. }
  360. /**
  361. * Test if a comment exists.
  362. *
  363. * @access public
  364. * @param string $pasteid
  365. * @param string $parentid
  366. * @param string $commentid
  367. * @return void
  368. */
  369. public function existsComment($pasteid, $parentid, $commentid)
  370. {
  371. return (bool) self::_select(
  372. 'SELECT dataid FROM ' . self::_sanitizeIdentifier('comment') .
  373. ' WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  374. array($pasteid, $parentid, $commentid), true
  375. );
  376. }
  377. /**
  378. * Returns up to batch size number of paste ids that have expired
  379. *
  380. * @access private
  381. * @param int $batchsize
  382. * @return array
  383. */
  384. protected function _getExpiredPastes($batchsize)
  385. {
  386. $pastes = array();
  387. $rows = self::_select(
  388. 'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') .
  389. ' WHERE expiredate < ? LIMIT ?', array(time(), $batchsize)
  390. );
  391. if (count($rows))
  392. {
  393. foreach ($rows as $row)
  394. {
  395. $pastes[] = $row['dataid'];
  396. }
  397. }
  398. return $pastes;
  399. }
  400. /**
  401. * execute a statement
  402. *
  403. * @access private
  404. * @static
  405. * @param string $sql
  406. * @param array $params
  407. * @throws PDOException
  408. * @return bool
  409. */
  410. private static function _exec($sql, array $params)
  411. {
  412. $statement = self::$_db->prepare($sql);
  413. $result = $statement->execute($params);
  414. $statement->closeCursor();
  415. return $result;
  416. }
  417. /**
  418. * run a select statement
  419. *
  420. * @access private
  421. * @static
  422. * @param string $sql
  423. * @param array $params
  424. * @param bool $firstOnly if only the first row should be returned
  425. * @throws PDOException
  426. * @return array
  427. */
  428. private static function _select($sql, array $params, $firstOnly = false)
  429. {
  430. $statement = self::$_db->prepare($sql);
  431. $statement->execute($params);
  432. $result = $firstOnly ?
  433. $statement->fetch(PDO::FETCH_ASSOC) :
  434. $statement->fetchAll(PDO::FETCH_ASSOC);
  435. $statement->closeCursor();
  436. return $result;
  437. }
  438. /**
  439. * get table list query, depending on the database type
  440. *
  441. * @access private
  442. * @static
  443. * @param string $type
  444. * @throws Exception
  445. * @return string
  446. */
  447. private static function _getTableQuery($type)
  448. {
  449. switch($type)
  450. {
  451. case 'ibm':
  452. $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
  453. break;
  454. case 'informix':
  455. $sql = 'SELECT tabname FROM systables ';
  456. break;
  457. case 'mssql':
  458. $sql = "SELECT name FROM sysobjects "
  459. . "WHERE type = 'U' ORDER BY name";
  460. break;
  461. case 'mysql':
  462. $sql = 'SHOW TABLES';
  463. break;
  464. case 'oci':
  465. $sql = 'SELECT table_name FROM all_tables';
  466. break;
  467. case 'pgsql':
  468. $sql = "SELECT c.relname AS table_name "
  469. . "FROM pg_class c, pg_user u "
  470. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  471. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  472. . "AND c.relname !~ '^(pg_|sql_)' "
  473. . "UNION "
  474. . "SELECT c.relname AS table_name "
  475. . "FROM pg_class c "
  476. . "WHERE c.relkind = 'r' "
  477. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  478. . "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
  479. . "AND c.relname !~ '^pg_'";
  480. break;
  481. case 'sqlite':
  482. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  483. . "UNION ALL SELECT name FROM sqlite_temp_master "
  484. . "WHERE type='table' ORDER BY name";
  485. break;
  486. default:
  487. throw new Exception(
  488. "PDO type $type is currently not supported.", 5
  489. );
  490. }
  491. return $sql;
  492. }
  493. /**
  494. * get a value by key from the config table
  495. *
  496. * @access private
  497. * @static
  498. * @param string $key
  499. * @throws PDOException
  500. * @return string
  501. */
  502. private static function _getConfig($key)
  503. {
  504. $row = self::_select(
  505. 'SELECT value FROM ' . self::_sanitizeIdentifier('config') .
  506. ' WHERE id = ?', array($key), true
  507. );
  508. return $row['value'];
  509. }
  510. /**
  511. * get the primary key clauses, depending on the database driver
  512. *
  513. * @access private
  514. * @static
  515. * @param string $key
  516. * @return array
  517. */
  518. private static function _getPrimaryKeyClauses($key = 'dataid')
  519. {
  520. $main_key = $after_key = '';
  521. if (self::$_type === 'mysql')
  522. {
  523. $after_key = ", PRIMARY KEY ($key)";
  524. }
  525. else
  526. {
  527. $main_key = ' PRIMARY KEY';
  528. }
  529. return array($main_key, $after_key);
  530. }
  531. /**
  532. * create the paste table
  533. *
  534. * @access private
  535. * @static
  536. * @return void
  537. */
  538. private static function _createPasteTable()
  539. {
  540. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  541. self::$_db->exec(
  542. 'CREATE TABLE ' . self::_sanitizeIdentifier('paste') . ' ( ' .
  543. "dataid CHAR(16) NOT NULL$main_key, " .
  544. 'data BLOB, ' .
  545. 'postdate INT, ' .
  546. 'expiredate INT, ' .
  547. 'opendiscussion INT, ' .
  548. 'burnafterreading INT, ' .
  549. 'meta TEXT, ' .
  550. 'attachment MEDIUMBLOB, ' .
  551. "attachmentname BLOB$after_key );"
  552. );
  553. }
  554. /**
  555. * create the paste table
  556. *
  557. * @access private
  558. * @static
  559. * @return void
  560. */
  561. private static function _createCommentTable()
  562. {
  563. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  564. self::$_db->exec(
  565. 'CREATE TABLE ' . self::_sanitizeIdentifier('comment') . ' ( ' .
  566. "dataid CHAR(16) NOT NULL$main_key, " .
  567. 'pasteid CHAR(16), ' .
  568. 'parentid CHAR(16), ' .
  569. 'data BLOB, ' .
  570. 'nickname BLOB, ' .
  571. 'vizhash BLOB, ' .
  572. "postdate INT$after_key );"
  573. );
  574. self::$_db->exec(
  575. 'CREATE INDEX parent ON ' . self::_sanitizeIdentifier('comment') .
  576. '(pasteid);'
  577. );
  578. }
  579. /**
  580. * create the paste table
  581. *
  582. * @access private
  583. * @static
  584. * @return void
  585. */
  586. private static function _createConfigTable()
  587. {
  588. list($main_key, $after_key) = self::_getPrimaryKeyClauses('id');
  589. self::$_db->exec(
  590. 'CREATE TABLE ' . self::_sanitizeIdentifier('config') .
  591. " ( id CHAR(16) NOT NULL$main_key, value TEXT$after_key );"
  592. );
  593. self::_exec(
  594. 'INSERT INTO ' . self::_sanitizeIdentifier('config') .
  595. ' VALUES(?,?)',
  596. array('VERSION', privatebin::VERSION)
  597. );
  598. }
  599. /**
  600. * sanitizes identifiers
  601. *
  602. * @access private
  603. * @static
  604. * @param string $identifier
  605. * @return string
  606. */
  607. private static function _sanitizeIdentifier($identifier)
  608. {
  609. return preg_replace('/[^A-Za-z0-9_]+/', '', self::$_prefix . $identifier);
  610. }
  611. /**
  612. * upgrade the database schema from an old version
  613. *
  614. * @access private
  615. * @static
  616. * @param string $oldversion
  617. * @return void
  618. */
  619. private static function _upgradeDatabase($oldversion)
  620. {
  621. switch ($oldversion)
  622. {
  623. case '0.21':
  624. // create the meta column if necessary (pre 0.21 change)
  625. try {
  626. self::$_db->exec('SELECT meta FROM ' . self::_sanitizeIdentifier('paste') . ' LIMIT 1;');
  627. } catch (PDOException $e) {
  628. self::$_db->exec('ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN meta TEXT;');
  629. }
  630. // SQLite only allows one ALTER statement at a time...
  631. self::$_db->exec(
  632. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN attachment MEDIUMBLOB;'
  633. );
  634. self::$_db->exec(
  635. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN attachmentname BLOB;'
  636. );
  637. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  638. // size as BLOB, so there is no need to change it there
  639. if (self::$_type !== 'sqlite')
  640. {
  641. self::$_db->exec(
  642. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') .
  643. ' ADD PRIMARY KEY (dataid), MODIFY COLUMN data BLOB;'
  644. );
  645. self::$_db->exec(
  646. 'ALTER TABLE ' . self::_sanitizeIdentifier('comment') .
  647. ' ADD PRIMARY KEY (dataid), MODIFY COLUMN data BLOB, ' .
  648. 'MODIFY COLUMN nickname BLOB, MODIFY COLUMN vizhash BLOB;'
  649. );
  650. }
  651. else
  652. {
  653. self::$_db->exec(
  654. 'CREATE UNIQUE INDEX primary ON ' . self::_sanitizeIdentifier('paste') . '(dataid);'
  655. );
  656. self::$_db->exec(
  657. 'CREATE UNIQUE INDEX primary ON ' . self::_sanitizeIdentifier('comment') . '(dataid);'
  658. );
  659. }
  660. self::$_db->exec(
  661. 'CREATE INDEX parent ON ' . self::_sanitizeIdentifier('comment') . '(pasteid);'
  662. );
  663. }
  664. }
  665. }