Database.php 27 KB

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