1
0

Database.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. unlink($file);
  378. return $value;
  379. }
  380. }
  381. if ($value && $namespace === 'traffic_limiter') {
  382. try {
  383. $this->_last_cache = Json::decode($value);
  384. } catch (JsonException $e) {
  385. error_log('Error decoding JSON from table "config", row "traffic_limiter": ' . $e->getMessage());
  386. $this->_last_cache = array();
  387. }
  388. if (array_key_exists($key, $this->_last_cache)) {
  389. return $this->_last_cache[$key];
  390. }
  391. }
  392. return (string) $value;
  393. }
  394. /**
  395. * Returns up to batch size number of paste ids that have expired
  396. *
  397. * @access private
  398. * @param int $batchsize
  399. * @return array
  400. */
  401. protected function _getExpiredPastes($batchsize)
  402. {
  403. try {
  404. $statement = $this->_db->prepare(
  405. 'SELECT "dataid" FROM "' . $this->_sanitizeIdentifier('paste') .
  406. '" WHERE "expiredate" < ? AND "expiredate" != ? ' .
  407. ($this->_type === 'oci' ? 'FETCH NEXT ? ROWS ONLY' : 'LIMIT ?')
  408. );
  409. $statement->execute(array(time(), 0, $batchsize));
  410. return $statement->fetchAll(PDO::FETCH_COLUMN, 0);
  411. } catch (PDOException $e) {
  412. error_log('Error while attempting to find expired pastes in the database: ' . $e->getMessage());
  413. return array();
  414. }
  415. }
  416. /**
  417. * @inheritDoc
  418. */
  419. public function getAllPastes()
  420. {
  421. return $this->_db->query(
  422. 'SELECT "dataid" FROM "' . $this->_sanitizeIdentifier('paste') . '"'
  423. )->fetchAll(PDO::FETCH_COLUMN, 0);
  424. }
  425. /**
  426. * execute a statement
  427. *
  428. * @access private
  429. * @param string $sql
  430. * @param array $params
  431. * @throws PDOException
  432. * @return bool
  433. */
  434. private function _exec($sql, array $params)
  435. {
  436. $statement = $this->_db->prepare($sql);
  437. $position = 1;
  438. foreach ($params as &$parameter) {
  439. if (is_int($parameter)) {
  440. $statement->bindParam($position, $parameter, PDO::PARAM_INT);
  441. } elseif (is_string($parameter) && strlen($parameter) >= 4000) {
  442. $statement->bindParam($position, $parameter, PDO::PARAM_STR, strlen($parameter));
  443. } else {
  444. $statement->bindParam($position, $parameter);
  445. }
  446. ++$position;
  447. }
  448. $result = $statement->execute();
  449. $statement->closeCursor();
  450. return $result;
  451. }
  452. /**
  453. * run a select statement
  454. *
  455. * @access private
  456. * @param string $sql
  457. * @param array $params
  458. * @param bool $firstOnly if only the first row should be returned
  459. * @throws PDOException
  460. * @return array
  461. */
  462. private function _select($sql, array $params, $firstOnly = false)
  463. {
  464. $statement = $this->_db->prepare($sql);
  465. $statement->execute($params);
  466. if ($firstOnly) {
  467. $result = $statement->fetch(PDO::FETCH_ASSOC);
  468. if ($this->_type === 'oci' && is_array($result)) {
  469. // returned CLOB values are streams, convert these into strings
  470. $result = array_map('PrivateBin\Data\Database::_sanitizeClob', $result);
  471. }
  472. } elseif ($this->_type === 'oci') {
  473. // workaround for https://bugs.php.net/bug.php?id=46728
  474. $result = array();
  475. while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
  476. $result[] = array_map('PrivateBin\Data\Database::_sanitizeClob', $row);
  477. }
  478. } else {
  479. $result = $statement->fetchAll(PDO::FETCH_ASSOC);
  480. }
  481. $statement->closeCursor();
  482. return $result;
  483. }
  484. /**
  485. * get table list query, depending on the database type
  486. *
  487. * @access private
  488. * @param string $type
  489. * @throws Exception
  490. * @return string
  491. */
  492. private function _getTableQuery($type)
  493. {
  494. switch ($type) {
  495. case 'ibm':
  496. $sql = 'SELECT "tabname" FROM "SYSCAT"."TABLES"';
  497. break;
  498. case 'informix':
  499. $sql = 'SELECT "tabname" FROM "systables"';
  500. break;
  501. case 'mssql':
  502. // U: tables created by the user
  503. $sql = 'SELECT "name" FROM "sysobjects" '
  504. . 'WHERE "type" = \'U\' ORDER BY "name"';
  505. break;
  506. case 'mysql':
  507. $sql = 'SHOW TABLES';
  508. break;
  509. case 'oci':
  510. $sql = 'SELECT table_name FROM all_tables';
  511. break;
  512. case 'pgsql':
  513. $sql = 'SELECT "tablename" FROM "pg_catalog"."pg_tables" '
  514. . 'WHERE "schemaname" NOT IN (\'pg_catalog\', \'information_schema\')';
  515. break;
  516. case 'sqlite':
  517. $sql = 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'table\' '
  518. . 'UNION ALL SELECT "name" FROM "sqlite_temp_master" '
  519. . 'WHERE "type"=\'table\' ORDER BY "name"';
  520. break;
  521. default:
  522. throw new Exception(
  523. "PDO type $type is currently not supported.", 5
  524. );
  525. }
  526. return $sql;
  527. }
  528. /**
  529. * get a value by key from the config table
  530. *
  531. * @access private
  532. * @param string $key
  533. * @return string
  534. */
  535. private function _getConfig($key)
  536. {
  537. try {
  538. $row = $this->_select(
  539. 'SELECT "value" FROM "' . $this->_sanitizeIdentifier('config') .
  540. '" WHERE "id" = ?', array($key), true
  541. );
  542. } catch (PDOException $e) {
  543. error_log('Error while attempting to fetch configuration key "' . $key . '" in the database: ' . $e->getMessage());
  544. return '';
  545. }
  546. return $row ? $row['value'] : '';
  547. }
  548. /**
  549. * get the primary key clauses, depending on the database driver
  550. *
  551. * @access private
  552. * @param string $key
  553. * @return array
  554. */
  555. private function _getPrimaryKeyClauses($key = 'dataid')
  556. {
  557. $main_key = $after_key = '';
  558. switch ($this->_type) {
  559. case 'mysql':
  560. case 'oci':
  561. $after_key = ", PRIMARY KEY (\"$key\")";
  562. break;
  563. default:
  564. $main_key = ' PRIMARY KEY';
  565. break;
  566. }
  567. return array($main_key, $after_key);
  568. }
  569. /**
  570. * get the data type, depending on the database driver
  571. *
  572. * PostgreSQL and OCI uses a different API for BLOBs then SQL, hence we use TEXT and CLOB
  573. *
  574. * @access private
  575. * @return string
  576. */
  577. private function _getDataType()
  578. {
  579. switch ($this->_type) {
  580. case 'oci':
  581. return 'CLOB';
  582. case 'pgsql':
  583. return 'TEXT';
  584. default:
  585. return 'BLOB';
  586. }
  587. }
  588. /**
  589. * get the attachment type, depending on the database driver
  590. *
  591. * PostgreSQL and OCI use different APIs for BLOBs then SQL, hence we use TEXT and CLOB
  592. *
  593. * @access private
  594. * @return string
  595. */
  596. private function _getAttachmentType()
  597. {
  598. switch ($this->_type) {
  599. case 'oci':
  600. return 'CLOB';
  601. case 'pgsql':
  602. return 'TEXT';
  603. default:
  604. return 'MEDIUMBLOB';
  605. }
  606. }
  607. /**
  608. * get the meta type, depending on the database driver
  609. *
  610. * OCI doesn't accept TEXT so it has to be VARCHAR2(4000)
  611. *
  612. * @access private
  613. * @return string
  614. */
  615. private function _getMetaType()
  616. {
  617. switch ($this->_type) {
  618. case 'oci':
  619. return 'VARCHAR2(4000)';
  620. default:
  621. return 'TEXT';
  622. }
  623. }
  624. /**
  625. * create the paste table
  626. *
  627. * @access private
  628. */
  629. private function _createPasteTable()
  630. {
  631. list($main_key, $after_key) = $this->_getPrimaryKeyClauses();
  632. $attachmentType = $this->_getAttachmentType();
  633. $metaType = $this->_getMetaType();
  634. $this->_db->exec(
  635. 'CREATE TABLE "' . $this->_sanitizeIdentifier('paste') . '" ( ' .
  636. "\"dataid\" CHAR(16) NOT NULL$main_key, " .
  637. "\"data\" $attachmentType, " .
  638. '"expiredate" INT, ' .
  639. "\"meta\" $metaType$after_key )"
  640. );
  641. }
  642. /**
  643. * create the comment table
  644. *
  645. * @access private
  646. */
  647. private function _createCommentTable()
  648. {
  649. list($main_key, $after_key) = $this->_getPrimaryKeyClauses();
  650. $dataType = $this->_getDataType();
  651. $this->_db->exec(
  652. 'CREATE TABLE "' . $this->_sanitizeIdentifier('comment') . '" ( ' .
  653. "\"dataid\" CHAR(16) NOT NULL$main_key, " .
  654. '"pasteid" CHAR(16), ' .
  655. '"parentid" CHAR(16), ' .
  656. "\"data\" $dataType, " .
  657. "\"vizhash\" $dataType, " .
  658. "\"postdate\" INT$after_key )"
  659. );
  660. if ($this->_type === 'oci') {
  661. $this->_db->exec(
  662. 'declare
  663. already_exists exception;
  664. columns_indexed exception;
  665. pragma exception_init( already_exists, -955 );
  666. pragma exception_init(columns_indexed, -1408);
  667. begin
  668. execute immediate \'create index "comment_parent" on "' . $this->_sanitizeIdentifier('comment') . '" ("pasteid")\';
  669. exception
  670. when already_exists or columns_indexed then
  671. NULL;
  672. end;'
  673. );
  674. } else {
  675. // CREATE INDEX IF NOT EXISTS not supported as of Oracle MySQL <= 8.0
  676. $this->_db->exec(
  677. 'CREATE INDEX "' .
  678. $this->_sanitizeIdentifier('comment_parent') . '" ON "' .
  679. $this->_sanitizeIdentifier('comment') . '" ("pasteid")'
  680. );
  681. }
  682. }
  683. /**
  684. * create the config table
  685. *
  686. * @access private
  687. */
  688. private function _createConfigTable()
  689. {
  690. list($main_key, $after_key) = $this->_getPrimaryKeyClauses('id');
  691. $charType = $this->_type === 'oci' ? 'VARCHAR2(16)' : 'CHAR(16)';
  692. $textType = $this->_getMetaType();
  693. $this->_db->exec(
  694. 'CREATE TABLE "' . $this->_sanitizeIdentifier('config') .
  695. "\" ( \"id\" $charType NOT NULL$main_key, \"value\" $textType$after_key )"
  696. );
  697. $this->_exec(
  698. 'INSERT INTO "' . $this->_sanitizeIdentifier('config') .
  699. '" VALUES(?,?)',
  700. array('VERSION', Controller::VERSION)
  701. );
  702. }
  703. /**
  704. * sanitizes CLOB values used with OCI
  705. *
  706. * From: https://stackoverflow.com/questions/36200534/pdo-oci-into-a-clob-field
  707. *
  708. * @access public
  709. * @static
  710. * @param int|string|resource $value
  711. * @return int|string
  712. */
  713. public static function _sanitizeClob($value)
  714. {
  715. if (is_resource($value)) {
  716. $value = stream_get_contents($value);
  717. }
  718. return $value;
  719. }
  720. /**
  721. * sanitizes identifiers
  722. *
  723. * @access private
  724. * @param string $identifier
  725. * @return string
  726. */
  727. private function _sanitizeIdentifier($identifier)
  728. {
  729. return preg_replace('/[^A-Za-z0-9_]+/', '', $this->_prefix . $identifier);
  730. }
  731. /**
  732. * check if the current database type supports dropping columns
  733. *
  734. * @access private
  735. * @return bool
  736. */
  737. private function _supportsDropColumn()
  738. {
  739. $supportsDropColumn = true;
  740. if ($this->_type === 'sqlite') {
  741. try {
  742. $row = $this->_select('SELECT sqlite_version() AS "v"', array(), true);
  743. $supportsDropColumn = (bool) version_compare($row['v'], '3.35.0', '>=');
  744. } catch (PDOException $e) {
  745. $supportsDropColumn = false;
  746. }
  747. }
  748. return $supportsDropColumn;
  749. }
  750. /**
  751. * upgrade the database schema from an old version
  752. *
  753. * @access private
  754. * @param string $oldversion
  755. */
  756. private function _upgradeDatabase($oldversion)
  757. {
  758. $dataType = $this->_getDataType();
  759. $attachmentType = $this->_getAttachmentType();
  760. if (version_compare($oldversion, '0.21', '<=')) {
  761. // create the meta column if necessary (pre 0.21 change)
  762. try {
  763. $this->_db->exec(
  764. 'SELECT "meta" FROM "' . $this->_sanitizeIdentifier('paste') . '" ' .
  765. ($this->_type === 'oci' ? 'FETCH NEXT 1 ROWS ONLY' : 'LIMIT 1')
  766. );
  767. } catch (PDOException $e) {
  768. $this->_db->exec('ALTER TABLE "' . $this->_sanitizeIdentifier('paste') . '" ADD COLUMN "meta" TEXT');
  769. }
  770. // SQLite only allows one ALTER statement at a time...
  771. $this->_db->exec(
  772. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  773. "\" ADD COLUMN \"attachment\" $attachmentType"
  774. );
  775. $this->_db->exec(
  776. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') . "\" ADD COLUMN \"attachmentname\" $dataType"
  777. );
  778. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  779. // size as BLOB, so there is no need to change it there
  780. if ($this->_type !== 'sqlite') {
  781. $this->_db->exec(
  782. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  783. "\" ADD PRIMARY KEY (\"dataid\"), MODIFY COLUMN \"data\" $dataType"
  784. );
  785. $this->_db->exec(
  786. 'ALTER TABLE "' . $this->_sanitizeIdentifier('comment') .
  787. "\" ADD PRIMARY KEY (\"dataid\"), MODIFY COLUMN \"data\" $dataType, " .
  788. "MODIFY COLUMN \"nickname\" $dataType, MODIFY COLUMN \"vizhash\" $dataType"
  789. );
  790. } else {
  791. $this->_db->exec(
  792. 'CREATE UNIQUE INDEX IF NOT EXISTS "' .
  793. $this->_sanitizeIdentifier('paste_dataid') . '" ON "' .
  794. $this->_sanitizeIdentifier('paste') . '" ("dataid")'
  795. );
  796. $this->_db->exec(
  797. 'CREATE UNIQUE INDEX IF NOT EXISTS "' .
  798. $this->_sanitizeIdentifier('comment_dataid') . '" ON "' .
  799. $this->_sanitizeIdentifier('comment') . '" ("dataid")'
  800. );
  801. }
  802. // CREATE INDEX IF NOT EXISTS not supported as of Oracle MySQL <= 8.0
  803. $this->_db->exec(
  804. 'CREATE INDEX "' .
  805. $this->_sanitizeIdentifier('comment_parent') . '" ON "' .
  806. $this->_sanitizeIdentifier('comment') . '" ("pasteid")'
  807. );
  808. }
  809. if (version_compare($oldversion, '1.3', '<=')) {
  810. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  811. // size as BLOB and PostgreSQL uses TEXT, so there is no need
  812. // to change it there
  813. if ($this->_type !== 'sqlite' && $this->_type !== 'pgsql') {
  814. $this->_db->exec(
  815. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  816. "\" MODIFY COLUMN \"data\" $attachmentType"
  817. );
  818. }
  819. }
  820. if (version_compare($oldversion, '1.7.1', '<=')) {
  821. if ($this->_supportsDropColumn()) {
  822. $this->_db->exec(
  823. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  824. '" DROP COLUMN "postdate"'
  825. );
  826. }
  827. }
  828. if (version_compare($oldversion, '1.7.8', '<=')) {
  829. if ($this->_supportsDropColumn()) {
  830. $this->_db->exec(
  831. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  832. '" DROP COLUMN "opendiscussion"'
  833. );
  834. $this->_db->exec(
  835. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  836. '" DROP COLUMN "burnafterreading"'
  837. );
  838. $this->_db->exec(
  839. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  840. '" DROP COLUMN "attachment"'
  841. );
  842. $this->_db->exec(
  843. 'ALTER TABLE "' . $this->_sanitizeIdentifier('paste') .
  844. '" DROP COLUMN "attachmentname"'
  845. );
  846. $this->_db->exec(
  847. 'ALTER TABLE "' . $this->_sanitizeIdentifier('comment') .
  848. '" DROP COLUMN "nickname"'
  849. );
  850. }
  851. }
  852. $this->_exec(
  853. 'UPDATE "' . $this->_sanitizeIdentifier('config') .
  854. '" SET "value" = ? WHERE "id" = ?',
  855. array(Controller::VERSION, 'VERSION')
  856. );
  857. }
  858. }