db.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.21.1
  11. */
  12. /**
  13. * zerobin_db
  14. *
  15. * Model for DB access, implemented as a singleton.
  16. */
  17. class zerobin_db extends zerobin_abstract
  18. {
  19. /**
  20. * cache for select queries
  21. *
  22. * @var array
  23. */
  24. private static $_cache = array();
  25. /**
  26. * instance of database connection
  27. *
  28. * @access private
  29. * @static
  30. * @var PDO
  31. */
  32. private static $_db;
  33. /**
  34. * table prefix
  35. *
  36. * @access private
  37. * @static
  38. * @var string
  39. */
  40. private static $_prefix = '';
  41. /**
  42. * database type
  43. *
  44. * @access private
  45. * @static
  46. * @var string
  47. */
  48. private static $_type = '';
  49. /**
  50. * get instance of singleton
  51. *
  52. * @access public
  53. * @static
  54. * @param array $options
  55. * @throws Exception
  56. * @return zerobin_db
  57. */
  58. public static function getInstance($options = null)
  59. {
  60. // if needed initialize the singleton
  61. if(!(self::$_instance instanceof zerobin_db)) {
  62. self::$_instance = new self;
  63. }
  64. if (is_array($options))
  65. {
  66. // set table prefix if given
  67. if (array_key_exists('tbl', $options)) self::$_prefix = $options['tbl'];
  68. // initialize the db connection with new options
  69. if (
  70. array_key_exists('dsn', $options) &&
  71. array_key_exists('usr', $options) &&
  72. array_key_exists('pwd', $options) &&
  73. array_key_exists('opt', $options)
  74. )
  75. {
  76. // set default options
  77. $options['opt'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
  78. $options['opt'][PDO::ATTR_EMULATE_PREPARES] = false;
  79. $options['opt'][PDO::ATTR_PERSISTENT] = true;
  80. // check if the database contains the required tables
  81. self::$_type = strtolower(
  82. substr($options['dsn'], 0, strpos($options['dsn'], ':'))
  83. );
  84. switch(self::$_type)
  85. {
  86. case 'ibm':
  87. $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
  88. break;
  89. case 'informix':
  90. $sql = 'SELECT tabname FROM systables ';
  91. break;
  92. case 'mssql':
  93. $sql = "SELECT name FROM sysobjects "
  94. . "WHERE type = 'U' ORDER BY name";
  95. break;
  96. case 'mysql':
  97. $sql = 'SHOW TABLES';
  98. break;
  99. case 'oci':
  100. $sql = 'SELECT table_name FROM all_tables';
  101. break;
  102. case 'pgsql':
  103. $sql = "SELECT c.relname AS table_name "
  104. . "FROM pg_class c, pg_user u "
  105. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  106. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  107. . "AND c.relname !~ '^(pg_|sql_)' "
  108. . "UNION "
  109. . "SELECT c.relname AS table_name "
  110. . "FROM pg_class c "
  111. . "WHERE c.relkind = 'r' "
  112. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  113. . "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
  114. . "AND c.relname !~ '^pg_'";
  115. break;
  116. case 'sqlite':
  117. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  118. . "UNION ALL SELECT name FROM sqlite_temp_master "
  119. . "WHERE type='table' ORDER BY name";
  120. break;
  121. default:
  122. throw new Exception(
  123. 'PDO type ' .
  124. self::$_type .
  125. ' is currently not supported.',
  126. 5
  127. );
  128. }
  129. self::$_db = new PDO(
  130. $options['dsn'],
  131. $options['usr'],
  132. $options['pwd'],
  133. $options['opt']
  134. );
  135. $statement = self::$_db->query($sql);
  136. $tables = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
  137. // create paste table if needed
  138. if (!in_array(self::$_prefix . 'paste', $tables))
  139. {
  140. self::$_db->exec(
  141. 'CREATE TABLE ' . self::$_prefix . 'paste ( ' .
  142. 'dataid CHAR(16), ' .
  143. 'data TEXT, ' .
  144. 'postdate INT, ' .
  145. 'expiredate INT, ' .
  146. 'opendiscussion INT, ' .
  147. 'burnafterreading INT, ' .
  148. 'meta TEXT );'
  149. );
  150. }
  151. // check if the meta column exists
  152. else
  153. {
  154. try {
  155. self::_exec('SELECT meta FROM ' . self::$_prefix . 'paste LIMIT 1;', array());
  156. } catch (PDOException $e) {
  157. self::$_db->exec('ALTER TABLE ' . self::$_prefix . 'paste ADD COLUMN meta TEXT;');
  158. }
  159. }
  160. // create comment table if needed
  161. if (!in_array(self::$_prefix . 'comment', $tables))
  162. {
  163. self::$_db->exec(
  164. 'CREATE TABLE ' . self::$_prefix . 'comment ( ' .
  165. 'dataid CHAR(16), ' .
  166. 'pasteid CHAR(16), ' .
  167. 'parentid CHAR(16), ' .
  168. 'data TEXT, ' .
  169. 'nickname VARCHAR(255), ' .
  170. 'vizhash TEXT, ' .
  171. 'postdate INT );'
  172. );
  173. }
  174. }
  175. }
  176. return self::$_instance;
  177. }
  178. /**
  179. * Create a paste.
  180. *
  181. * @access public
  182. * @param string $pasteid
  183. * @param array $paste
  184. * @return bool
  185. */
  186. public function create($pasteid, $paste)
  187. {
  188. if (
  189. array_key_exists($pasteid, self::$_cache)
  190. ) {
  191. if(false !== self::$_cache[$pasteid]) {
  192. return false;
  193. } else {
  194. unset(self::$_cache[$pasteid]);
  195. }
  196. }
  197. $opendiscussion = $burnafterreading = false;
  198. $meta = $paste['meta'];
  199. unset($meta['postdate']);
  200. $expire_date = 0;
  201. if (array_key_exists('expire_date', $paste['meta']))
  202. {
  203. $expire_date = (int) $paste['meta']['expire_date'];
  204. unset($meta['expire_date']);
  205. }
  206. if (array_key_exists('opendiscussion', $paste['meta']))
  207. {
  208. $opendiscussion = (bool) $paste['meta']['opendiscussion'];
  209. unset($meta['opendiscussion']);
  210. }
  211. if (array_key_exists('burnafterreading', $paste['meta']))
  212. {
  213. $burnafterreading = (bool) $paste['meta']['burnafterreading'];
  214. unset($meta['burnafterreading']);
  215. }
  216. return self::_exec(
  217. 'INSERT INTO ' . self::$_prefix . 'paste VALUES(?,?,?,?,?,?,?)',
  218. array(
  219. $pasteid,
  220. $paste['data'],
  221. $paste['meta']['postdate'],
  222. $expire_date,
  223. (int) $opendiscussion,
  224. (int) $burnafterreading,
  225. json_encode($meta),
  226. )
  227. );
  228. }
  229. /**
  230. * Read a paste.
  231. *
  232. * @access public
  233. * @param string $pasteid
  234. * @return stdClass|false
  235. */
  236. public function read($pasteid)
  237. {
  238. if (
  239. !array_key_exists($pasteid, self::$_cache)
  240. ) {
  241. self::$_cache[$pasteid] = false;
  242. $paste = self::_select(
  243. 'SELECT * FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  244. array($pasteid), true
  245. );
  246. if(false !== $paste) {
  247. // create object
  248. self::$_cache[$pasteid] = new stdClass;
  249. self::$_cache[$pasteid]->data = $paste['data'];
  250. $meta = json_decode($paste['meta']);
  251. if (!is_object($meta)) $meta = new stdClass;
  252. if (property_exists($meta, 'attachment'))
  253. {
  254. self::$_cache[$pasteid]->attachment = $meta->attachment;
  255. unset($meta->attachment);
  256. if (property_exists($meta, 'attachmentname'))
  257. {
  258. self::$_cache[$pasteid]->attachmentname = $meta->attachmentname;
  259. unset($meta->attachmentname);
  260. }
  261. }
  262. self::$_cache[$pasteid]->meta = $meta;
  263. self::$_cache[$pasteid]->meta->postdate = (int) $paste['postdate'];
  264. $expire_date = (int) $paste['expiredate'];
  265. if (
  266. $expire_date > 0
  267. ) self::$_cache[$pasteid]->meta->expire_date = $expire_date;
  268. if (
  269. $paste['opendiscussion']
  270. ) self::$_cache[$pasteid]->meta->opendiscussion = true;
  271. if (
  272. $paste['burnafterreading']
  273. ) self::$_cache[$pasteid]->meta->burnafterreading = true;
  274. }
  275. }
  276. return self::$_cache[$pasteid];
  277. }
  278. /**
  279. * Delete a paste and its discussion.
  280. *
  281. * @access public
  282. * @param string $pasteid
  283. * @return void
  284. */
  285. public function delete($pasteid)
  286. {
  287. self::_exec(
  288. 'DELETE FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  289. array($pasteid)
  290. );
  291. self::_exec(
  292. 'DELETE FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  293. array($pasteid)
  294. );
  295. if (
  296. array_key_exists($pasteid, self::$_cache)
  297. ) unset(self::$_cache[$pasteid]);
  298. }
  299. /**
  300. * Test if a paste exists.
  301. *
  302. * @access public
  303. * @param string $dataid
  304. * @return void
  305. */
  306. public function exists($pasteid)
  307. {
  308. if (
  309. !array_key_exists($pasteid, self::$_cache)
  310. ) self::$_cache[$pasteid] = $this->read($pasteid);
  311. return (bool) self::$_cache[$pasteid];
  312. }
  313. /**
  314. * Create a comment in a paste.
  315. *
  316. * @access public
  317. * @param string $pasteid
  318. * @param string $parentid
  319. * @param string $commentid
  320. * @param array $comment
  321. * @return int|false
  322. */
  323. public function createComment($pasteid, $parentid, $commentid, $comment)
  324. {
  325. return self::_exec(
  326. 'INSERT INTO ' . self::$_prefix . 'comment VALUES(?,?,?,?,?,?,?)',
  327. array(
  328. $commentid,
  329. $pasteid,
  330. $parentid,
  331. $comment['data'],
  332. $comment['meta']['nickname'],
  333. $comment['meta']['vizhash'],
  334. $comment['meta']['postdate'],
  335. )
  336. );
  337. }
  338. /**
  339. * Read all comments of paste.
  340. *
  341. * @access public
  342. * @param string $pasteid
  343. * @return array
  344. */
  345. public function readComments($pasteid)
  346. {
  347. $rows = self::_select(
  348. 'SELECT * FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  349. array($pasteid)
  350. );
  351. // create comment list
  352. $comments = array();
  353. if (count($rows))
  354. {
  355. foreach ($rows as $row)
  356. {
  357. $i = $this->getOpenSlot($comments, (int) $row['postdate']);
  358. $comments[$i] = new stdClass;
  359. $comments[$i]->data = $row['data'];
  360. $comments[$i]->meta = new stdClass;
  361. if (array_key_exists('nickname', $row))
  362. $comments[$i]->meta->nickname = $row['nickname'];
  363. if (array_key_exists('vizhash', $row))
  364. $comments[$i]->meta->vizhash = $row['vizhash'];
  365. $comments[$i]->meta->postdate = (int) $row['postdate'];
  366. $comments[$i]->meta->commentid = $row['dataid'];
  367. $comments[$i]->meta->parentid = $row['parentid'];
  368. }
  369. ksort($comments);
  370. }
  371. return $comments;
  372. }
  373. /**
  374. * Test if a comment exists.
  375. *
  376. * @access public
  377. * @param string $dataid
  378. * @param string $parentid
  379. * @param string $commentid
  380. * @return void
  381. */
  382. public function existsComment($pasteid, $parentid, $commentid)
  383. {
  384. return (bool) self::_select(
  385. 'SELECT dataid FROM ' . self::$_prefix . 'comment ' .
  386. 'WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  387. array($pasteid, $parentid, $commentid), true
  388. );
  389. }
  390. /**
  391. * execute a statement
  392. *
  393. * @access private
  394. * @static
  395. * @param string $sql
  396. * @param array $params
  397. * @throws PDOException
  398. * @return array
  399. */
  400. private static function _exec($sql, array $params)
  401. {
  402. $statement = self::$_db->prepare($sql);
  403. $result = $statement->execute($params);
  404. $statement->closeCursor();
  405. return $result;
  406. }
  407. /**
  408. * run a select statement
  409. *
  410. * @access private
  411. * @static
  412. * @param string $sql
  413. * @param array $params
  414. * @param bool $firstOnly if only the first row should be returned
  415. * @throws PDOException
  416. * @return array
  417. */
  418. private static function _select($sql, array $params, $firstOnly = false)
  419. {
  420. $statement = self::$_db->prepare($sql);
  421. $statement->execute($params);
  422. $result = $firstOnly ?
  423. $statement->fetch(PDO::FETCH_ASSOC) :
  424. $statement->fetchAll(PDO::FETCH_ASSOC);
  425. $statement->closeCursor();
  426. return $result;
  427. }
  428. }