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