Database.php 28 KB

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