Database.php 31 KB

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