1
0

Database.php 30 KB

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