1
0

Database.php 30 KB

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