Database.php 31 KB

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