Database.php 30 KB

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