1
0

Database.php 31 KB

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