Database.php 29 KB

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