Database.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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->bindParam($position, $parameter, PDO::PARAM_INT);
  521. } elseif (strlen($parameter) >= 4000) {
  522. $statement->bindParam($position, $parameter, PDO::PARAM_STR, strlen($parameter));
  523. } else {
  524. $statement->bindParam($position, $parameter);
  525. }
  526. }
  527. $result = $statement->execute();
  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. if ($firstOnly) {
  547. $result = $statement->fetch(PDO::FETCH_ASSOC);
  548. } elseif (self::$_type === 'oci') {
  549. // workaround for https://bugs.php.net/bug.php?id=46728
  550. $result = array();
  551. while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
  552. $result[] = array_map('self::_sanitizeClob', $row);
  553. }
  554. } else {
  555. $result = $statement->fetchAll(PDO::FETCH_ASSOC);
  556. }
  557. $statement->closeCursor();
  558. if (self::$_type === 'oci' && is_array($result)) {
  559. // returned CLOB values are streams, convert these into strings
  560. $result = $firstOnly ?
  561. array_map('self::_sanitizeClob', $result) :
  562. $result;
  563. }
  564. return $result;
  565. }
  566. /**
  567. * get version dependent key names
  568. *
  569. * @access private
  570. * @static
  571. * @param int $version
  572. * @return array
  573. */
  574. private static function _getVersionedKeys($version)
  575. {
  576. if ($version === 1) {
  577. return array('postdate', 'vizhash');
  578. }
  579. return array('created', 'icon');
  580. }
  581. /**
  582. * get table list query, depending on the database type
  583. *
  584. * @access private
  585. * @static
  586. * @param string $type
  587. * @throws Exception
  588. * @return string
  589. */
  590. private static function _getTableQuery($type)
  591. {
  592. switch ($type) {
  593. case 'ibm':
  594. $sql = 'SELECT "tabname" FROM "SYSCAT"."TABLES"';
  595. break;
  596. case 'informix':
  597. $sql = 'SELECT "tabname" FROM "systables"';
  598. break;
  599. case 'mssql':
  600. // U: tables created by the user
  601. $sql = 'SELECT "name" FROM "sysobjects" '
  602. . 'WHERE "type" = \'U\' ORDER BY "name"';
  603. break;
  604. case 'mysql':
  605. $sql = 'SHOW TABLES';
  606. break;
  607. case 'oci':
  608. $sql = 'SELECT table_name FROM all_tables';
  609. break;
  610. case 'pgsql':
  611. $sql = 'SELECT c."relname" AS "table_name" '
  612. . 'FROM "pg_class" c, "pg_user" u '
  613. . 'WHERE c."relowner" = u."usesysid" AND c."relkind" = \'r\' '
  614. . 'AND NOT EXISTS (SELECT 1 FROM "pg_views" WHERE "viewname" = c."relname") '
  615. . "AND c.\"relname\" !~ '^(pg_|sql_)' "
  616. . 'UNION '
  617. . 'SELECT c."relname" AS "table_name" '
  618. . 'FROM "pg_class" c '
  619. . "WHERE c.\"relkind\" = 'r' "
  620. . 'AND NOT EXISTS (SELECT 1 FROM "pg_views" WHERE "viewname" = c."relname") '
  621. . 'AND NOT EXISTS (SELECT 1 FROM "pg_user" WHERE "usesysid" = c."relowner") '
  622. . "AND c.\"relname\" !~ '^pg_'";
  623. break;
  624. case 'sqlite':
  625. $sql = 'SELECT "name" FROM "sqlite_master" WHERE "type"=\'table\' '
  626. . 'UNION ALL SELECT "name" FROM "sqlite_temp_master" '
  627. . 'WHERE "type"=\'table\' ORDER BY "name"';
  628. break;
  629. default:
  630. throw new Exception(
  631. "PDO type $type is currently not supported.", 5
  632. );
  633. }
  634. return $sql;
  635. }
  636. /**
  637. * get a value by key from the config table
  638. *
  639. * @access private
  640. * @static
  641. * @param string $key
  642. * @return string
  643. */
  644. private static function _getConfig($key)
  645. {
  646. try {
  647. $row = self::_select(
  648. 'SELECT "value" FROM "' . self::_sanitizeIdentifier('config') .
  649. '" WHERE "id" = ?', array($key), true
  650. );
  651. } catch (PDOException $e) {
  652. return '';
  653. }
  654. return $row ? $row['value'] : '';
  655. }
  656. /**
  657. * get the primary key clauses, depending on the database driver
  658. *
  659. * @access private
  660. * @static
  661. * @param string $key
  662. * @return array
  663. */
  664. private static function _getPrimaryKeyClauses($key = 'dataid')
  665. {
  666. $main_key = $after_key = '';
  667. switch (self::$_type) {
  668. case 'mysql':
  669. case 'oci':
  670. $after_key = ", PRIMARY KEY (\"$key\")";
  671. break;
  672. default:
  673. $main_key = ' PRIMARY KEY';
  674. break;
  675. }
  676. return array($main_key, $after_key);
  677. }
  678. /**
  679. * get the data type, depending on the database driver
  680. *
  681. * PostgreSQL and OCI uses a different API for BLOBs then SQL, hence we use TEXT and CLOB
  682. *
  683. * @access private
  684. * @static
  685. * @return string
  686. */
  687. private static function _getDataType()
  688. {
  689. switch (self::$_type) {
  690. case 'oci':
  691. return 'CLOB';
  692. case 'pgsql':
  693. return 'TEXT';
  694. default:
  695. return 'BLOB';
  696. }
  697. }
  698. /**
  699. * get the attachment type, depending on the database driver
  700. *
  701. * PostgreSQL and OCI use different APIs for BLOBs then SQL, hence we use TEXT and CLOB
  702. *
  703. * @access private
  704. * @static
  705. * @return string
  706. */
  707. private static function _getAttachmentType()
  708. {
  709. switch (self::$_type) {
  710. case 'oci':
  711. return 'CLOB';
  712. case 'pgsql':
  713. return 'TEXT';
  714. default:
  715. return 'MEDIUMBLOB';
  716. }
  717. }
  718. /**
  719. * get the meta type, depending on the database driver
  720. *
  721. * OCI doesn't accept TEXT so it has to be VARCHAR2(4000)
  722. *
  723. * @access private
  724. * @static
  725. * @return string
  726. */
  727. private static function _getMetaType()
  728. {
  729. switch (self::$_type) {
  730. case 'oci':
  731. return 'VARCHAR2(4000)';
  732. default:
  733. return 'TEXT';
  734. }
  735. }
  736. /**
  737. * create the paste table
  738. *
  739. * @access private
  740. * @static
  741. */
  742. private static function _createPasteTable()
  743. {
  744. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  745. $dataType = self::_getDataType();
  746. $attachmentType = self::_getAttachmentType();
  747. $metaType = self::_getMetaType();
  748. self::$_db->exec(
  749. 'CREATE TABLE "' . self::_sanitizeIdentifier('paste') . '" ( ' .
  750. "\"dataid\" CHAR(16) NOT NULL$main_key, " .
  751. "\"data\" $attachmentType, " .
  752. '"postdate" INT, ' .
  753. '"expiredate" INT, ' .
  754. '"opendiscussion" INT, ' .
  755. '"burnafterreading" INT, ' .
  756. "\"meta\" $metaType, " .
  757. "\"attachment\" $attachmentType, " .
  758. "\"attachmentname\" $dataType$after_key )"
  759. );
  760. }
  761. /**
  762. * create the paste table
  763. *
  764. * @access private
  765. * @static
  766. */
  767. private static function _createCommentTable()
  768. {
  769. list($main_key, $after_key) = self::_getPrimaryKeyClauses();
  770. $dataType = self::_getDataType();
  771. self::$_db->exec(
  772. 'CREATE TABLE "' . self::_sanitizeIdentifier('comment') . '" ( ' .
  773. "\"dataid\" CHAR(16) NOT NULL$main_key, " .
  774. '"pasteid" CHAR(16), ' .
  775. '"parentid" CHAR(16), ' .
  776. "\"data\" $dataType, " .
  777. "\"nickname\" $dataType, " .
  778. "\"vizhash\" $dataType, " .
  779. "\"postdate\" INT$after_key )"
  780. );
  781. if (self::$_type === 'oci') {
  782. self::$_db->exec(
  783. 'declare
  784. already_exists exception;
  785. columns_indexed exception;
  786. pragma exception_init( already_exists, -955 );
  787. pragma exception_init(columns_indexed, -1408);
  788. begin
  789. execute immediate \'create index "comment_parent" on "' . self::_sanitizeIdentifier('comment') . '" ("pasteid")\';
  790. exception
  791. when already_exists or columns_indexed then
  792. NULL;
  793. end;'
  794. );
  795. } else {
  796. self::$_db->exec(
  797. 'CREATE INDEX IF NOT EXISTS "comment_parent" ON "' .
  798. self::_sanitizeIdentifier('comment') . '" ("pasteid")'
  799. );
  800. }
  801. }
  802. /**
  803. * create the paste table
  804. *
  805. * @access private
  806. * @static
  807. */
  808. private static function _createConfigTable()
  809. {
  810. list($main_key, $after_key) = self::_getPrimaryKeyClauses('id');
  811. $charType = self::$_type === 'oci' ? 'VARCHAR2(16)' : 'CHAR(16)';
  812. $textType = self::_getMetaType();
  813. self::$_db->exec(
  814. 'CREATE TABLE "' . self::_sanitizeIdentifier('config') .
  815. "\" ( \"id\" $charType NOT NULL$main_key, \"value\" $textType$after_key )"
  816. );
  817. self::_exec(
  818. 'INSERT INTO "' . self::_sanitizeIdentifier('config') .
  819. '" VALUES(?,?)',
  820. array('VERSION', Controller::VERSION)
  821. );
  822. }
  823. /**
  824. * sanitizes CLOB values used with OCI
  825. *
  826. * From: https://stackoverflow.com/questions/36200534/pdo-oci-into-a-clob-field
  827. *
  828. * @access public
  829. * @static
  830. * @param int|string|resource $value
  831. * @return int|string
  832. */
  833. public static function _sanitizeClob($value)
  834. {
  835. if (is_resource($value)) {
  836. $value = stream_get_contents($value);
  837. }
  838. return $value;
  839. }
  840. /**
  841. * sanitizes identifiers
  842. *
  843. * @access private
  844. * @static
  845. * @param string $identifier
  846. * @return string
  847. */
  848. private static function _sanitizeIdentifier($identifier)
  849. {
  850. return preg_replace('/[^A-Za-z0-9_]+/', '', self::$_prefix . $identifier);
  851. }
  852. /**
  853. * upgrade the database schema from an old version
  854. *
  855. * @access private
  856. * @static
  857. * @param string $oldversion
  858. */
  859. private static function _upgradeDatabase($oldversion)
  860. {
  861. $dataType = self::_getDataType();
  862. $attachmentType = self::_getAttachmentType();
  863. switch ($oldversion) {
  864. case '0.21':
  865. // create the meta column if necessary (pre 0.21 change)
  866. try {
  867. self::$_db->exec(
  868. 'SELECT "meta" FROM "' . self::_sanitizeIdentifier('paste') . '" ' .
  869. (self::$_type === 'oci' ? 'FETCH NEXT 1 ROWS ONLY' : 'LIMIT 1')
  870. );
  871. } catch (PDOException $e) {
  872. self::$_db->exec('ALTER TABLE "' . self::_sanitizeIdentifier('paste') . '" ADD COLUMN "meta" TEXT');
  873. }
  874. // SQLite only allows one ALTER statement at a time...
  875. self::$_db->exec(
  876. 'ALTER TABLE "' . self::_sanitizeIdentifier('paste') .
  877. "\" ADD COLUMN \"attachment\" $attachmentType"
  878. );
  879. self::$_db->exec(
  880. 'ALTER TABLE "' . self::_sanitizeIdentifier('paste') . "\" ADD COLUMN \"attachmentname\" $dataType"
  881. );
  882. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  883. // size as BLOB, so there is no need to change it there
  884. if (self::$_type !== 'sqlite') {
  885. self::$_db->exec(
  886. 'ALTER TABLE "' . self::_sanitizeIdentifier('paste') .
  887. "\" ADD PRIMARY KEY (\"dataid\"), MODIFY COLUMN \"data\" $dataType"
  888. );
  889. self::$_db->exec(
  890. 'ALTER TABLE "' . self::_sanitizeIdentifier('comment') .
  891. "\" ADD PRIMARY KEY (\"dataid\"), MODIFY COLUMN \"data\" $dataType, " .
  892. "MODIFY COLUMN \"nickname\" $dataType, MODIFY COLUMN \"vizhash\" $dataType"
  893. );
  894. } else {
  895. self::$_db->exec(
  896. 'CREATE UNIQUE INDEX IF NOT EXISTS "paste_dataid" ON "' .
  897. self::_sanitizeIdentifier('paste') . '" ("dataid")'
  898. );
  899. self::$_db->exec(
  900. 'CREATE UNIQUE INDEX IF NOT EXISTS "comment_dataid" ON "' .
  901. self::_sanitizeIdentifier('comment') . '" ("dataid")'
  902. );
  903. }
  904. self::$_db->exec(
  905. 'CREATE INDEX IF NOT EXISTS "comment_parent" ON "' .
  906. self::_sanitizeIdentifier('comment') . '" ("pasteid")'
  907. );
  908. // no break, continue with updates for 0.22 and later
  909. case '1.3':
  910. // SQLite doesn't support MODIFY, but it allows TEXT of similar
  911. // size as BLOB and PostgreSQL uses TEXT, so there is no need
  912. // to change it there
  913. if (self::$_type !== 'sqlite' && self::$_type !== 'pgsql') {
  914. self::$_db->exec(
  915. 'ALTER TABLE "' . self::_sanitizeIdentifier('paste') .
  916. "\" MODIFY COLUMN \"data\" $attachmentType"
  917. );
  918. }
  919. // no break, continue with updates for all newer versions
  920. default:
  921. self::_exec(
  922. 'UPDATE "' . self::_sanitizeIdentifier('config') .
  923. '" SET "value" = ? WHERE "id" = ?',
  924. array(Controller::VERSION, 'VERSION')
  925. );
  926. }
  927. }
  928. }