db.php 20 KB

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