db.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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::$_prefix . 'paste', $tables))
  96. {
  97. self::_createPasteTable();
  98. $db_tables_exist = false;
  99. }
  100. // create comment table if necessary
  101. if (!in_array(self::$_prefix . '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::$_prefix . '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. }
  125. return self::$_instance;
  126. }
  127. /**
  128. * Create a paste.
  129. *
  130. * @access public
  131. * @param string $pasteid
  132. * @param array $paste
  133. * @return bool
  134. */
  135. public function create($pasteid, $paste)
  136. {
  137. if (
  138. array_key_exists($pasteid, self::$_cache)
  139. ) {
  140. if(false !== self::$_cache[$pasteid]) {
  141. return false;
  142. } else {
  143. unset(self::$_cache[$pasteid]);
  144. }
  145. }
  146. $opendiscussion = $burnafterreading = false;
  147. $attachment = $attachmentname = '';
  148. $meta = $paste['meta'];
  149. unset($meta['postdate']);
  150. $expire_date = 0;
  151. if (array_key_exists('expire_date', $paste['meta']))
  152. {
  153. $expire_date = (int) $paste['meta']['expire_date'];
  154. unset($meta['expire_date']);
  155. }
  156. if (array_key_exists('opendiscussion', $paste['meta']))
  157. {
  158. $opendiscussion = (bool) $paste['meta']['opendiscussion'];
  159. unset($meta['opendiscussion']);
  160. }
  161. if (array_key_exists('burnafterreading', $paste['meta']))
  162. {
  163. $burnafterreading = (bool) $paste['meta']['burnafterreading'];
  164. unset($meta['burnafterreading']);
  165. }
  166. if (array_key_exists('attachment', $paste['meta']))
  167. {
  168. $attachment = $paste['meta']['attachment'];
  169. unset($meta['attachment']);
  170. }
  171. if (array_key_exists('attachmentname', $paste['meta']))
  172. {
  173. $attachmentname = $paste['meta']['attachmentname'];
  174. unset($meta['attachmentname']);
  175. }
  176. return self::_exec(
  177. 'INSERT INTO ' . self::$_prefix . 'paste VALUES(?,?,?,?,?,?,?,?,?)',
  178. array(
  179. $pasteid,
  180. $paste['data'],
  181. $paste['meta']['postdate'],
  182. $expire_date,
  183. (int) $opendiscussion,
  184. (int) $burnafterreading,
  185. json_encode($meta),
  186. $attachment,
  187. $attachmentname,
  188. )
  189. );
  190. }
  191. /**
  192. * Read a paste.
  193. *
  194. * @access public
  195. * @param string $pasteid
  196. * @return stdClass|false
  197. */
  198. public function read($pasteid)
  199. {
  200. if (
  201. !array_key_exists($pasteid, self::$_cache)
  202. ) {
  203. self::$_cache[$pasteid] = false;
  204. $paste = self::_select(
  205. 'SELECT * FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  206. array($pasteid), true
  207. );
  208. if(false !== $paste) {
  209. // create object
  210. self::$_cache[$pasteid] = new stdClass;
  211. self::$_cache[$pasteid]->data = $paste['data'];
  212. $meta = json_decode($paste['meta']);
  213. if (!is_object($meta)) $meta = new stdClass;
  214. // support older attachments
  215. if (property_exists($meta, 'attachment'))
  216. {
  217. self::$_cache[$pasteid]->attachment = $meta->attachment;
  218. unset($meta->attachment);
  219. if (property_exists($meta, 'attachmentname'))
  220. {
  221. self::$_cache[$pasteid]->attachmentname = $meta->attachmentname;
  222. unset($meta->attachmentname);
  223. }
  224. }
  225. // support current attachments
  226. elseif (array_key_exists('attachment', $paste) && strlen($paste['attachment']))
  227. {
  228. self::$_cache[$pasteid]->attachment = $paste['attachment'];
  229. if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname']))
  230. {
  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. ) self::$_cache[$pasteid]->meta->expire_date = $expire_date;
  240. if (
  241. $paste['opendiscussion']
  242. ) self::$_cache[$pasteid]->meta->opendiscussion = true;
  243. if (
  244. $paste['burnafterreading']
  245. ) self::$_cache[$pasteid]->meta->burnafterreading = true;
  246. }
  247. }
  248. return self::$_cache[$pasteid];
  249. }
  250. /**
  251. * Delete a paste and its discussion.
  252. *
  253. * @access public
  254. * @param string $pasteid
  255. * @return void
  256. */
  257. public function delete($pasteid)
  258. {
  259. self::_exec(
  260. 'DELETE FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  261. array($pasteid)
  262. );
  263. self::_exec(
  264. 'DELETE FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  265. array($pasteid)
  266. );
  267. if (
  268. array_key_exists($pasteid, self::$_cache)
  269. ) unset(self::$_cache[$pasteid]);
  270. }
  271. /**
  272. * Test if a paste exists.
  273. *
  274. * @access public
  275. * @param string $dataid
  276. * @return void
  277. */
  278. public function exists($pasteid)
  279. {
  280. if (
  281. !array_key_exists($pasteid, self::$_cache)
  282. ) self::$_cache[$pasteid] = $this->read($pasteid);
  283. return (bool) self::$_cache[$pasteid];
  284. }
  285. /**
  286. * Create a comment in a paste.
  287. *
  288. * @access public
  289. * @param string $pasteid
  290. * @param string $parentid
  291. * @param string $commentid
  292. * @param array $comment
  293. * @return int|false
  294. */
  295. public function createComment($pasteid, $parentid, $commentid, $comment)
  296. {
  297. return self::_exec(
  298. 'INSERT INTO ' . self::$_prefix . 'comment VALUES(?,?,?,?,?,?,?)',
  299. array(
  300. $commentid,
  301. $pasteid,
  302. $parentid,
  303. $comment['data'],
  304. $comment['meta']['nickname'],
  305. $comment['meta']['vizhash'],
  306. $comment['meta']['postdate'],
  307. )
  308. );
  309. }
  310. /**
  311. * Read all comments of paste.
  312. *
  313. * @access public
  314. * @param string $pasteid
  315. * @return array
  316. */
  317. public function readComments($pasteid)
  318. {
  319. $rows = self::_select(
  320. 'SELECT * FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  321. array($pasteid)
  322. );
  323. // create comment list
  324. $comments = array();
  325. if (count($rows))
  326. {
  327. foreach ($rows as $row)
  328. {
  329. $i = $this->getOpenSlot($comments, (int) $row['postdate']);
  330. $comments[$i] = new stdClass;
  331. $comments[$i]->id = $row['dataid'];
  332. $comments[$i]->parentid = $row['parentid'];
  333. $comments[$i]->data = $row['data'];
  334. $comments[$i]->meta = new stdClass;
  335. $comments[$i]->meta->postdate = (int) $row['postdate'];
  336. if (array_key_exists('nickname', $row))
  337. $comments[$i]->meta->nickname = $row['nickname'];
  338. if (array_key_exists('vizhash', $row))
  339. $comments[$i]->meta->vizhash = $row['vizhash'];
  340. }
  341. ksort($comments);
  342. }
  343. return $comments;
  344. }
  345. /**
  346. * Test if a comment exists.
  347. *
  348. * @access public
  349. * @param string $dataid
  350. * @param string $parentid
  351. * @param string $commentid
  352. * @return void
  353. */
  354. public function existsComment($pasteid, $parentid, $commentid)
  355. {
  356. return (bool) self::_select(
  357. 'SELECT dataid FROM ' . self::$_prefix . 'comment ' .
  358. 'WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  359. array($pasteid, $parentid, $commentid), true
  360. );
  361. }
  362. /**
  363. * execute a statement
  364. *
  365. * @access private
  366. * @static
  367. * @param string $sql
  368. * @param array $params
  369. * @throws PDOException
  370. * @return array
  371. */
  372. private static function _exec($sql, array $params)
  373. {
  374. $statement = self::$_db->prepare($sql);
  375. $result = $statement->execute($params);
  376. $statement->closeCursor();
  377. return $result;
  378. }
  379. /**
  380. * run a select statement
  381. *
  382. * @access private
  383. * @static
  384. * @param string $sql
  385. * @param array $params
  386. * @param bool $firstOnly if only the first row should be returned
  387. * @throws PDOException
  388. * @return array
  389. */
  390. private static function _select($sql, array $params, $firstOnly = false)
  391. {
  392. $statement = self::$_db->prepare($sql);
  393. $statement->execute($params);
  394. $result = $firstOnly ?
  395. $statement->fetch(PDO::FETCH_ASSOC) :
  396. $statement->fetchAll(PDO::FETCH_ASSOC);
  397. $statement->closeCursor();
  398. return $result;
  399. }
  400. /**
  401. * get table list query, depending on the database type
  402. *
  403. * @access private
  404. * @static
  405. * @param string $type
  406. * @throws Exception
  407. * @return string
  408. */
  409. private static function _getTableQuery($type)
  410. {
  411. switch($type)
  412. {
  413. case 'ibm':
  414. $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
  415. break;
  416. case 'informix':
  417. $sql = 'SELECT tabname FROM systables ';
  418. break;
  419. case 'mssql':
  420. $sql = "SELECT name FROM sysobjects "
  421. . "WHERE type = 'U' ORDER BY name";
  422. break;
  423. case 'mysql':
  424. $sql = 'SHOW TABLES';
  425. break;
  426. case 'oci':
  427. $sql = 'SELECT table_name FROM all_tables';
  428. break;
  429. case 'pgsql':
  430. $sql = "SELECT c.relname AS table_name "
  431. . "FROM pg_class c, pg_user u "
  432. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  433. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  434. . "AND c.relname !~ '^(pg_|sql_)' "
  435. . "UNION "
  436. . "SELECT c.relname AS table_name "
  437. . "FROM pg_class c "
  438. . "WHERE c.relkind = 'r' "
  439. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  440. . "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
  441. . "AND c.relname !~ '^pg_'";
  442. break;
  443. case 'sqlite':
  444. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  445. . "UNION ALL SELECT name FROM sqlite_temp_master "
  446. . "WHERE type='table' ORDER BY name";
  447. break;
  448. default:
  449. throw new Exception(
  450. "PDO type $type is currently not supported.", 5
  451. );
  452. }
  453. return $sql;
  454. }
  455. /**
  456. * get a value by key from the config table
  457. *
  458. * @access private
  459. * @static
  460. * @param string $key
  461. * @throws PDOException
  462. * @return string
  463. */
  464. private static function _getConfig($key)
  465. {
  466. $row = self::_select(
  467. 'SELECT value FROM ' . self::$_prefix . 'config WHERE id = ?',
  468. array($key), true
  469. );
  470. return $row['value'];
  471. }
  472. /**
  473. * get the primary key clauses, depending on the database driver
  474. *
  475. * @access private
  476. * @static
  477. * @param string $key
  478. * @return array
  479. */
  480. private static function _getPrimaryKeyClauses($key = 'dataid')
  481. {
  482. $main_key = $after_key = '';
  483. if (self::$_type === 'mysql')
  484. {
  485. $after_key = ", PRIMARY KEY ($key)";
  486. }
  487. else
  488. {
  489. $main_key = ' PRIMARY KEY';
  490. }
  491. return array($main_key, $after_key);
  492. }
  493. /**
  494. * create the paste table
  495. *
  496. * @access private
  497. * @static
  498. * @return void
  499. */
  500. private static function _createPasteTable()
  501. {
  502. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  503. self::$_db->exec(
  504. 'CREATE TABLE ' . self::$_prefix . 'paste ( ' .
  505. "dataid CHAR(16) NOT NULL$main_key, " .
  506. 'data BLOB, ' .
  507. 'postdate INT, ' .
  508. 'expiredate INT, ' .
  509. 'opendiscussion INT, ' .
  510. 'burnafterreading INT, ' .
  511. 'meta TEXT, ' .
  512. 'attachment MEDIUMBLOB, ' .
  513. "attachmentname BLOB$after_key );"
  514. );
  515. }
  516. /**
  517. * create the paste table
  518. *
  519. * @access private
  520. * @static
  521. * @return void
  522. */
  523. private static function _createCommentTable()
  524. {
  525. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  526. self::$_db->exec(
  527. 'CREATE TABLE ' . self::$_prefix . 'comment ( ' .
  528. "dataid CHAR(16) NOT NULL$main_key, " .
  529. 'pasteid CHAR(16), ' .
  530. 'parentid CHAR(16), ' .
  531. 'data BLOB, ' .
  532. 'nickname BLOB, ' .
  533. 'vizhash BLOB, ' .
  534. "postdate INT$after_key );"
  535. );
  536. self::$_db->exec(
  537. 'CREATE INDEX parent ON ' . self::$_prefix . 'comment(pasteid);'
  538. );
  539. }
  540. /**
  541. * create the paste table
  542. *
  543. * @access private
  544. * @static
  545. * @return void
  546. */
  547. private static function _createConfigTable()
  548. {
  549. list($main_key, $after_key) = self::_getPrimaryKeyClauses('id');
  550. self::$_db->exec(
  551. 'CREATE TABLE ' . self::$_prefix . 'config ( ' .
  552. "id CHAR(16) NOT NULL$main_key, value TEXT$after_key );"
  553. );
  554. self::_exec(
  555. 'INSERT INTO ' . self::$_prefix . 'config VALUES(?,?)',
  556. array('VERSION', privatebin::VERSION)
  557. );
  558. }
  559. /**
  560. * upgrade the database schema from an old version
  561. *
  562. * @access private
  563. * @static
  564. * @param string $oldversion
  565. * @return void
  566. */
  567. private static function _upgradeDatabase($oldversion)
  568. {
  569. switch ($oldversion)
  570. {
  571. case '0.21':
  572. // create the meta column if necessary (pre 0.21 change)
  573. try {
  574. self::$_db->exec('SELECT meta FROM ' . self::$_prefix . 'paste LIMIT 1;');
  575. } catch (PDOException $e) {
  576. self::$_db->exec('ALTER TABLE ' . self::$_prefix . 'paste ADD COLUMN meta TEXT;');
  577. }
  578. // SQLite only allows one ALTER statement at a time...
  579. self::$_db->exec(
  580. 'ALTER TABLE ' . self::$_prefix . 'paste ADD COLUMN attachment MEDIUMBLOB;'
  581. );
  582. self::$_db->exec(
  583. 'ALTER TABLE ' . self::$_prefix . 'paste ADD COLUMN attachmentname BLOB;'
  584. );
  585. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  586. // size as BLOB, so there is no need to change it there
  587. if (self::$_type !== 'sqlite')
  588. {
  589. self::$_db->exec(
  590. 'ALTER TABLE ' . self::$_prefix . 'paste ' .
  591. 'ADD PRIMARY KEY (dataid),' .
  592. 'MODIFY COLUMN data BLOB;'
  593. );
  594. self::$_db->exec(
  595. 'ALTER TABLE ' . self::$_prefix . 'comment ' .
  596. 'ADD PRIMARY KEY (dataid),' .
  597. 'MODIFY COLUMN data BLOB, ' .
  598. 'MODIFY COLUMN nickname BLOB, ' .
  599. 'MODIFY COLUMN vizhash BLOB;'
  600. );
  601. }
  602. else
  603. {
  604. self::$_db->exec(
  605. 'CREATE UNIQUE INDEX primary ON ' . self::$_prefix . 'paste(dataid);'
  606. );
  607. self::$_db->exec(
  608. 'CREATE UNIQUE INDEX primary ON ' . self::$_prefix . 'comment(dataid);'
  609. );
  610. }
  611. self::$_db->exec(
  612. 'CREATE INDEX parent ON ' . self::$_prefix . 'comment(pasteid);'
  613. );
  614. }
  615. }
  616. }