Database.php 28 KB

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