Database.php 31 KB

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