Database.php 30 KB

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