Database.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 1.3.5
  11. */
  12. namespace PrivateBin\Data;
  13. use Exception;
  14. use PDO;
  15. use PDOException;
  16. use PrivateBin\Controller;
  17. use PrivateBin\Json;
  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(array $options)
  65. {
  66. // if needed initialize the singleton
  67. if (!(self::$_instance instanceof self)) {
  68. self::$_instance = new self;
  69. }
  70. // set table prefix if given
  71. if (array_key_exists('tbl', $options)) {
  72. self::$_prefix = $options['tbl'];
  73. }
  74. // initialize the db connection with new options
  75. if (
  76. array_key_exists('dsn', $options) &&
  77. array_key_exists('usr', $options) &&
  78. array_key_exists('pwd', $options) &&
  79. array_key_exists('opt', $options)
  80. ) {
  81. // set default options
  82. $options['opt'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
  83. $options['opt'][PDO::ATTR_EMULATE_PREPARES] = false;
  84. $options['opt'][PDO::ATTR_PERSISTENT] = true;
  85. $db_tables_exist = true;
  86. // setup type and dabase connection
  87. self::$_type = strtolower(
  88. substr($options['dsn'], 0, strpos($options['dsn'], ':'))
  89. );
  90. $tableQuery = self::_getTableQuery(self::$_type);
  91. self::$_db = new PDO(
  92. $options['dsn'],
  93. $options['usr'],
  94. $options['pwd'],
  95. $options['opt']
  96. );
  97. // check if the database contains the required tables
  98. $tables = self::$_db->query($tableQuery)->fetchAll(PDO::FETCH_COLUMN, 0);
  99. // create paste table if necessary
  100. if (!in_array(self::_sanitizeIdentifier('paste'), $tables)) {
  101. self::_createPasteTable();
  102. $db_tables_exist = false;
  103. }
  104. // create comment table if necessary
  105. if (!in_array(self::_sanitizeIdentifier('comment'), $tables)) {
  106. self::_createCommentTable();
  107. $db_tables_exist = false;
  108. }
  109. // create config table if necessary
  110. $db_version = Controller::VERSION;
  111. if (!in_array(self::_sanitizeIdentifier('config'), $tables)) {
  112. self::_createConfigTable();
  113. // if we only needed to create the config table, the DB is older then 0.22
  114. if ($db_tables_exist) {
  115. $db_version = '0.21';
  116. }
  117. } else {
  118. $db_version = self::_getConfig('VERSION');
  119. }
  120. // update database structure if necessary
  121. if (version_compare($db_version, Controller::VERSION, '<')) {
  122. self::_upgradeDatabase($db_version);
  123. }
  124. } else {
  125. throw new Exception(
  126. 'Missing configuration for key dsn, usr, pwd or opt in the section model_options, please check your configuration file', 6
  127. );
  128. }
  129. return self::$_instance;
  130. }
  131. /**
  132. * Create a paste.
  133. *
  134. * @access public
  135. * @param string $pasteid
  136. * @param array $paste
  137. * @return bool
  138. */
  139. public function create($pasteid, array $paste)
  140. {
  141. if (
  142. array_key_exists($pasteid, self::$_cache)
  143. ) {
  144. if (false !== self::$_cache[$pasteid]) {
  145. return false;
  146. } else {
  147. unset(self::$_cache[$pasteid]);
  148. }
  149. }
  150. $expire_date = 0;
  151. $opendiscussion = $burnafterreading = false;
  152. $attachment = $attachmentname = null;
  153. $meta = $paste['meta'];
  154. $isVersion1 = array_key_exists('data', $paste);
  155. list($createdKey) = self::_getVersionedKeys($isVersion1 ? 1 : 2);
  156. $created = (int) $meta[$createdKey];
  157. unset($meta[$createdKey], $paste['meta']);
  158. if (array_key_exists('expire_date', $meta)) {
  159. $expire_date = (int) $meta['expire_date'];
  160. unset($meta['expire_date']);
  161. }
  162. if (array_key_exists('opendiscussion', $meta)) {
  163. $opendiscussion = $meta['opendiscussion'];
  164. unset($meta['opendiscussion']);
  165. }
  166. if (array_key_exists('burnafterreading', $meta)) {
  167. $burnafterreading = $meta['burnafterreading'];
  168. unset($meta['burnafterreading']);
  169. }
  170. if ($isVersion1) {
  171. if (array_key_exists('attachment', $meta)) {
  172. $attachment = $meta['attachment'];
  173. unset($meta['attachment']);
  174. }
  175. if (array_key_exists('attachmentname', $meta)) {
  176. $attachmentname = $meta['attachmentname'];
  177. unset($meta['attachmentname']);
  178. }
  179. } else {
  180. $opendiscussion = $paste['adata'][2];
  181. $burnafterreading = $paste['adata'][3];
  182. }
  183. try {
  184. return self::_exec(
  185. 'INSERT INTO ' . self::_sanitizeIdentifier('paste') .
  186. ' VALUES(?,?,?,?,?,?,?,?,?)',
  187. array(
  188. $pasteid,
  189. $isVersion1 ? $paste['data'] : Json::encode($paste),
  190. $created,
  191. $expire_date,
  192. (int) $opendiscussion,
  193. (int) $burnafterreading,
  194. Json::encode($meta),
  195. $attachment,
  196. $attachmentname,
  197. )
  198. );
  199. } catch (Exception $e) {
  200. return false;
  201. }
  202. }
  203. /**
  204. * Read a paste.
  205. *
  206. * @access public
  207. * @param string $pasteid
  208. * @return array|false
  209. */
  210. public function read($pasteid)
  211. {
  212. if (array_key_exists($pasteid, self::$_cache)) {
  213. return self::$_cache[$pasteid];
  214. }
  215. self::$_cache[$pasteid] = false;
  216. $paste = self::_select(
  217. 'SELECT * FROM ' . self::_sanitizeIdentifier('paste') .
  218. ' WHERE dataid = ?', array($pasteid), true
  219. );
  220. if ($paste === false) {
  221. return false;
  222. }
  223. // create array
  224. $data = Json::decode($paste['data']);
  225. $isVersion2 = array_key_exists('v', $data) && $data['v'] >= 2;
  226. if ($isVersion2) {
  227. self::$_cache[$pasteid] = $data;
  228. list($createdKey) = self::_getVersionedKeys(2);
  229. } else {
  230. self::$_cache[$pasteid] = array('data' => $paste['data']);
  231. list($createdKey) = self::_getVersionedKeys(1);
  232. }
  233. try {
  234. $paste['meta'] = Json::decode($paste['meta']);
  235. } catch (Exception $e) {
  236. $paste['meta'] = array();
  237. }
  238. $paste = self::upgradePreV1Format($paste);
  239. self::$_cache[$pasteid]['meta'] = $paste['meta'];
  240. self::$_cache[$pasteid]['meta'][$createdKey] = (int) $paste['postdate'];
  241. $expire_date = (int) $paste['expiredate'];
  242. if ($expire_date > 0) {
  243. self::$_cache[$pasteid]['meta']['expire_date'] = $expire_date;
  244. }
  245. if ($isVersion2) {
  246. return self::$_cache[$pasteid];
  247. }
  248. // support v1 attachments
  249. if (array_key_exists('attachment', $paste) && strlen($paste['attachment'])) {
  250. self::$_cache[$pasteid]['attachment'] = $paste['attachment'];
  251. if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname'])) {
  252. self::$_cache[$pasteid]['attachmentname'] = $paste['attachmentname'];
  253. }
  254. }
  255. if ($paste['opendiscussion']) {
  256. self::$_cache[$pasteid]['meta']['opendiscussion'] = true;
  257. }
  258. if ($paste['burnafterreading']) {
  259. self::$_cache[$pasteid]['meta']['burnafterreading'] = true;
  260. }
  261. return self::$_cache[$pasteid];
  262. }
  263. /**
  264. * Delete a paste and its discussion.
  265. *
  266. * @access public
  267. * @param string $pasteid
  268. */
  269. public function delete($pasteid)
  270. {
  271. self::_exec(
  272. 'DELETE FROM ' . self::_sanitizeIdentifier('paste') .
  273. ' WHERE dataid = ?', array($pasteid)
  274. );
  275. self::_exec(
  276. 'DELETE FROM ' . self::_sanitizeIdentifier('comment') .
  277. ' WHERE pasteid = ?', array($pasteid)
  278. );
  279. if (
  280. array_key_exists($pasteid, self::$_cache)
  281. ) {
  282. unset(self::$_cache[$pasteid]);
  283. }
  284. }
  285. /**
  286. * Test if a paste exists.
  287. *
  288. * @access public
  289. * @param string $pasteid
  290. * @return bool
  291. */
  292. public function exists($pasteid)
  293. {
  294. if (
  295. !array_key_exists($pasteid, self::$_cache)
  296. ) {
  297. self::$_cache[$pasteid] = $this->read($pasteid);
  298. }
  299. return (bool) self::$_cache[$pasteid];
  300. }
  301. /**
  302. * Create a comment in a paste.
  303. *
  304. * @access public
  305. * @param string $pasteid
  306. * @param string $parentid
  307. * @param string $commentid
  308. * @param array $comment
  309. * @return bool
  310. */
  311. public function createComment($pasteid, $parentid, $commentid, array $comment)
  312. {
  313. if (array_key_exists('data', $comment)) {
  314. $version = 1;
  315. $data = $comment['data'];
  316. } else {
  317. $version = 2;
  318. $data = Json::encode($comment);
  319. }
  320. list($createdKey, $iconKey) = self::_getVersionedKeys($version);
  321. $meta = $comment['meta'];
  322. unset($comment['meta']);
  323. foreach (array('nickname', $iconKey) as $key) {
  324. if (!array_key_exists($key, $meta)) {
  325. $meta[$key] = null;
  326. }
  327. }
  328. try {
  329. return self::_exec(
  330. 'INSERT INTO ' . self::_sanitizeIdentifier('comment') .
  331. ' VALUES(?,?,?,?,?,?,?)',
  332. array(
  333. $commentid,
  334. $pasteid,
  335. $parentid,
  336. $data,
  337. $meta['nickname'],
  338. $meta[$iconKey],
  339. $meta[$createdKey],
  340. )
  341. );
  342. } catch (Exception $e) {
  343. return false;
  344. }
  345. }
  346. /**
  347. * Read all comments of paste.
  348. *
  349. * @access public
  350. * @param string $pasteid
  351. * @return array
  352. */
  353. public function readComments($pasteid)
  354. {
  355. $rows = self::_select(
  356. 'SELECT * FROM ' . self::_sanitizeIdentifier('comment') .
  357. ' WHERE pasteid = ?', array($pasteid)
  358. );
  359. // create comment list
  360. $comments = array();
  361. if (count($rows)) {
  362. foreach ($rows as $row) {
  363. $i = $this->getOpenSlot($comments, (int) $row['postdate']);
  364. $data = Json::decode($row['data']);
  365. if (array_key_exists('v', $data) && $data['v'] >= 2) {
  366. $version = 2;
  367. $comments[$i] = $data;
  368. } else {
  369. $version = 1;
  370. $comments[$i] = array('data' => $row['data']);
  371. }
  372. list($createdKey, $iconKey) = self::_getVersionedKeys($version);
  373. $comments[$i]['id'] = $row['dataid'];
  374. $comments[$i]['parentid'] = $row['parentid'];
  375. $comments[$i]['meta'] = array($createdKey => (int) $row['postdate']);
  376. foreach (array('nickname' => 'nickname', 'vizhash' => $iconKey) as $rowKey => $commentKey) {
  377. if (array_key_exists($rowKey, $row) && !empty($row[$rowKey])) {
  378. $comments[$i]['meta'][$commentKey] = $row[$rowKey];
  379. }
  380. }
  381. }
  382. ksort($comments);
  383. }
  384. return $comments;
  385. }
  386. /**
  387. * Test if a comment exists.
  388. *
  389. * @access public
  390. * @param string $pasteid
  391. * @param string $parentid
  392. * @param string $commentid
  393. * @return bool
  394. */
  395. public function existsComment($pasteid, $parentid, $commentid)
  396. {
  397. try {
  398. return (bool) self::_select(
  399. 'SELECT dataid FROM ' . self::_sanitizeIdentifier('comment') .
  400. ' WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  401. array($pasteid, $parentid, $commentid), true
  402. );
  403. } catch (Exception $e) {
  404. return false;
  405. }
  406. }
  407. /**
  408. * Save a value.
  409. *
  410. * @access public
  411. * @param string $value
  412. * @param string $namespace
  413. * @param string $key
  414. * @return bool
  415. */
  416. public function setValue($value, $namespace, $key = '')
  417. {
  418. if ($namespace === 'traffic_limiter') {
  419. self::$_traffic_limiter_cache[$key] = $value;
  420. try {
  421. $value = Json::encode(self::$_traffic_limiter_cache);
  422. } catch (Exception $e) {
  423. return false;
  424. }
  425. }
  426. return self::_exec(
  427. 'UPDATE ' . self::_sanitizeIdentifier('config') .
  428. ' SET value = ? WHERE id = ?',
  429. array($value, strtoupper($namespace))
  430. );
  431. }
  432. /**
  433. * Load a value.
  434. *
  435. * @access public
  436. * @param string $namespace
  437. * @param string $key
  438. * @return string
  439. */
  440. public function getValue($namespace, $key = '')
  441. {
  442. $configKey = strtoupper($namespace);
  443. $value = $this->_getConfig($configKey);
  444. if ($value === '') {
  445. // initialize the row, so that setValue can rely on UPDATE queries
  446. self::_exec(
  447. 'INSERT INTO ' . self::_sanitizeIdentifier('config') .
  448. ' VALUES(?,?)',
  449. array($configKey, '')
  450. );
  451. // migrate filesystem based salt into database
  452. $file = 'data' . DIRECTORY_SEPARATOR . 'salt.php';
  453. if ($namespace === 'salt' && is_readable($file)) {
  454. $value = Filesystem::getInstance(array('dir' => 'data'))->getValue('salt');
  455. $this->setValue($value, 'salt');
  456. @unlink($file);
  457. return $value;
  458. }
  459. }
  460. if ($value && $namespace === 'traffic_limiter') {
  461. try {
  462. self::$_traffic_limiter_cache = Json::decode($value);
  463. } catch (Exception $e) {
  464. self::$_traffic_limiter_cache = array();
  465. }
  466. if (array_key_exists($key, self::$_traffic_limiter_cache)) {
  467. return self::$_traffic_limiter_cache[$key];
  468. }
  469. }
  470. return (string) $value;
  471. }
  472. /**
  473. * Returns up to batch size number of paste ids that have expired
  474. *
  475. * @access private
  476. * @param int $batchsize
  477. * @return array
  478. */
  479. protected function _getExpiredPastes($batchsize)
  480. {
  481. $pastes = array();
  482. $rows = self::_select(
  483. 'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') .
  484. ' WHERE expiredate < ? AND expiredate != ? LIMIT ?',
  485. array(time(), 0, $batchsize)
  486. );
  487. if (count($rows)) {
  488. foreach ($rows as $row) {
  489. $pastes[] = $row['dataid'];
  490. }
  491. }
  492. return $pastes;
  493. }
  494. /**
  495. * execute a statement
  496. *
  497. * @access private
  498. * @static
  499. * @param string $sql
  500. * @param array $params
  501. * @throws PDOException
  502. * @return bool
  503. */
  504. private static function _exec($sql, array $params)
  505. {
  506. $statement = self::$_db->prepare($sql);
  507. $result = $statement->execute($params);
  508. $statement->closeCursor();
  509. return $result;
  510. }
  511. /**
  512. * run a select statement
  513. *
  514. * @access private
  515. * @static
  516. * @param string $sql
  517. * @param array $params
  518. * @param bool $firstOnly if only the first row should be returned
  519. * @throws PDOException
  520. * @return array|false
  521. */
  522. private static function _select($sql, array $params, $firstOnly = false)
  523. {
  524. $statement = self::$_db->prepare($sql);
  525. $statement->execute($params);
  526. $result = $firstOnly ?
  527. $statement->fetch(PDO::FETCH_ASSOC) :
  528. $statement->fetchAll(PDO::FETCH_ASSOC);
  529. $statement->closeCursor();
  530. return $result;
  531. }
  532. /**
  533. * get version dependent key names
  534. *
  535. * @access private
  536. * @static
  537. * @param int $version
  538. * @return array
  539. */
  540. private static function _getVersionedKeys($version)
  541. {
  542. if ($version === 1) {
  543. return array('postdate', 'vizhash');
  544. }
  545. return array('created', 'icon');
  546. }
  547. /**
  548. * get table list query, depending on the database type
  549. *
  550. * @access private
  551. * @static
  552. * @param string $type
  553. * @throws Exception
  554. * @return string
  555. */
  556. private static function _getTableQuery($type)
  557. {
  558. switch ($type) {
  559. case 'ibm':
  560. $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
  561. break;
  562. case 'informix':
  563. $sql = 'SELECT tabname FROM systables ';
  564. break;
  565. case 'mssql':
  566. $sql = 'SELECT name FROM sysobjects '
  567. . "WHERE type = 'U' ORDER BY name";
  568. break;
  569. case 'mysql':
  570. $sql = 'SHOW TABLES';
  571. break;
  572. case 'oci':
  573. $sql = 'SELECT table_name FROM all_tables';
  574. break;
  575. case 'pgsql':
  576. $sql = 'SELECT c.relname AS table_name '
  577. . 'FROM pg_class c, pg_user u '
  578. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  579. . 'AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) '
  580. . "AND c.relname !~ '^(pg_|sql_)' "
  581. . 'UNION '
  582. . 'SELECT c.relname AS table_name '
  583. . 'FROM pg_class c '
  584. . "WHERE c.relkind = 'r' "
  585. . 'AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) '
  586. . 'AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) '
  587. . "AND c.relname !~ '^pg_'";
  588. break;
  589. case 'sqlite':
  590. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  591. . 'UNION ALL SELECT name FROM sqlite_temp_master '
  592. . "WHERE type='table' ORDER BY name";
  593. break;
  594. default:
  595. throw new Exception(
  596. "PDO type $type is currently not supported.", 5
  597. );
  598. }
  599. return $sql;
  600. }
  601. /**
  602. * get a value by key from the config table
  603. *
  604. * @access private
  605. * @static
  606. * @param string $key
  607. * @throws PDOException
  608. * @return string
  609. */
  610. private static function _getConfig($key)
  611. {
  612. $row = self::_select(
  613. 'SELECT value FROM ' . self::_sanitizeIdentifier('config') .
  614. ' WHERE id = ?', array($key), true
  615. );
  616. return $row ? $row['value'] : '';
  617. }
  618. /**
  619. * get the primary key clauses, depending on the database driver
  620. *
  621. * @access private
  622. * @static
  623. * @param string $key
  624. * @return array
  625. */
  626. private static function _getPrimaryKeyClauses($key = 'dataid')
  627. {
  628. $main_key = $after_key = '';
  629. if (self::$_type === 'mysql') {
  630. $after_key = ", PRIMARY KEY ($key)";
  631. } else {
  632. $main_key = ' PRIMARY KEY';
  633. }
  634. return array($main_key, $after_key);
  635. }
  636. /**
  637. * get the data type, depending on the database driver
  638. *
  639. * PostgreSQL uses a different API for BLOBs then SQL, hence we use TEXT
  640. *
  641. * @access private
  642. * @static
  643. * @return string
  644. */
  645. private static function _getDataType()
  646. {
  647. return self::$_type === 'pgsql' ? 'TEXT' : 'BLOB';
  648. }
  649. /**
  650. * get the attachment type, depending on the database driver
  651. *
  652. * PostgreSQL uses a different API for BLOBs then SQL, hence we use TEXT
  653. *
  654. * @access private
  655. * @static
  656. * @return string
  657. */
  658. private static function _getAttachmentType()
  659. {
  660. return self::$_type === 'pgsql' ? 'TEXT' : 'MEDIUMBLOB';
  661. }
  662. /**
  663. * create the paste table
  664. *
  665. * @access private
  666. * @static
  667. */
  668. private static function _createPasteTable()
  669. {
  670. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  671. $dataType = self::_getDataType();
  672. $attachmentType = self::_getAttachmentType();
  673. self::$_db->exec(
  674. 'CREATE TABLE ' . self::_sanitizeIdentifier('paste') . ' ( ' .
  675. "dataid CHAR(16) NOT NULL$main_key, " .
  676. "data $attachmentType, " .
  677. 'postdate INT, ' .
  678. 'expiredate INT, ' .
  679. 'opendiscussion INT, ' .
  680. 'burnafterreading INT, ' .
  681. 'meta TEXT, ' .
  682. "attachment $attachmentType, " .
  683. "attachmentname $dataType$after_key );"
  684. );
  685. }
  686. /**
  687. * create the paste table
  688. *
  689. * @access private
  690. * @static
  691. */
  692. private static function _createCommentTable()
  693. {
  694. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  695. $dataType = self::_getDataType();
  696. self::$_db->exec(
  697. 'CREATE TABLE ' . self::_sanitizeIdentifier('comment') . ' ( ' .
  698. "dataid CHAR(16) NOT NULL$main_key, " .
  699. 'pasteid CHAR(16), ' .
  700. 'parentid CHAR(16), ' .
  701. "data $dataType, " .
  702. "nickname $dataType, " .
  703. "vizhash $dataType, " .
  704. "postdate INT$after_key );"
  705. );
  706. self::$_db->exec(
  707. 'CREATE INDEX IF NOT EXISTS comment_parent ON ' .
  708. self::_sanitizeIdentifier('comment') . '(pasteid);'
  709. );
  710. }
  711. /**
  712. * create the paste table
  713. *
  714. * @access private
  715. * @static
  716. */
  717. private static function _createConfigTable()
  718. {
  719. list($main_key, $after_key) = self::_getPrimaryKeyClauses('id');
  720. self::$_db->exec(
  721. 'CREATE TABLE ' . self::_sanitizeIdentifier('config') .
  722. " ( id CHAR(16) NOT NULL$main_key, value TEXT$after_key );"
  723. );
  724. self::_exec(
  725. 'INSERT INTO ' . self::_sanitizeIdentifier('config') .
  726. ' VALUES(?,?)',
  727. array('VERSION', Controller::VERSION)
  728. );
  729. }
  730. /**
  731. * sanitizes identifiers
  732. *
  733. * @access private
  734. * @static
  735. * @param string $identifier
  736. * @return string
  737. */
  738. private static function _sanitizeIdentifier($identifier)
  739. {
  740. return preg_replace('/[^A-Za-z0-9_]+/', '', self::$_prefix . $identifier);
  741. }
  742. /**
  743. * upgrade the database schema from an old version
  744. *
  745. * @access private
  746. * @static
  747. * @param string $oldversion
  748. */
  749. private static function _upgradeDatabase($oldversion)
  750. {
  751. $dataType = self::_getDataType();
  752. $attachmentType = self::_getAttachmentType();
  753. switch ($oldversion) {
  754. case '0.21':
  755. // create the meta column if necessary (pre 0.21 change)
  756. try {
  757. self::$_db->exec('SELECT meta FROM ' . self::_sanitizeIdentifier('paste') . ' LIMIT 1;');
  758. } catch (PDOException $e) {
  759. self::$_db->exec('ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD COLUMN meta TEXT;');
  760. }
  761. // SQLite only allows one ALTER statement at a time...
  762. self::$_db->exec(
  763. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') .
  764. " ADD COLUMN attachment $attachmentType;"
  765. );
  766. self::$_db->exec(
  767. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . " ADD COLUMN attachmentname $dataType;"
  768. );
  769. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  770. // size as BLOB, so there is no need to change it there
  771. if (self::$_type !== 'sqlite') {
  772. self::$_db->exec(
  773. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') .
  774. " ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType;"
  775. );
  776. self::$_db->exec(
  777. 'ALTER TABLE ' . self::_sanitizeIdentifier('comment') .
  778. " ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType, " .
  779. "MODIFY COLUMN nickname $dataType, MODIFY COLUMN vizhash $dataType;"
  780. );
  781. } else {
  782. self::$_db->exec(
  783. 'CREATE UNIQUE INDEX IF NOT EXISTS paste_dataid ON ' .
  784. self::_sanitizeIdentifier('paste') . '(dataid);'
  785. );
  786. self::$_db->exec(
  787. 'CREATE UNIQUE INDEX IF NOT EXISTS comment_dataid ON ' .
  788. self::_sanitizeIdentifier('comment') . '(dataid);'
  789. );
  790. }
  791. self::$_db->exec(
  792. 'CREATE INDEX IF NOT EXISTS comment_parent ON ' .
  793. self::_sanitizeIdentifier('comment') . '(pasteid);'
  794. );
  795. // no break, continue with updates for 0.22 and later
  796. case '1.3':
  797. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  798. // size as BLOB and PostgreSQL uses TEXT, so there is no need
  799. // to change it there
  800. if (self::$_type !== 'sqlite' && self::$_type !== 'pgsql') {
  801. self::$_db->exec(
  802. 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') .
  803. " MODIFY COLUMN data $attachmentType;"
  804. );
  805. }
  806. // no break, continue with updates for all newer versions
  807. default:
  808. self::_exec(
  809. 'UPDATE ' . self::_sanitizeIdentifier('config') .
  810. ' SET value = ? WHERE id = ?',
  811. array(Controller::VERSION, 'VERSION')
  812. );
  813. }
  814. }
  815. }