Database.php 28 KB

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