Database.php 30 KB

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