Database.php 32 KB

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