1
0

Database.php 30 KB

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