Database.php 27 KB

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