1
0

Database.php 27 KB

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