db.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. // check if the database contains the required tables
  77. self::$_type = strtolower(
  78. substr($options['dsn'], 0, strpos($options['dsn'], ':'))
  79. );
  80. switch(self::$_type)
  81. {
  82. case 'ibm':
  83. $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
  84. break;
  85. case 'informix':
  86. $sql = 'SELECT tabname FROM systables ';
  87. break;
  88. case 'mssql':
  89. $sql = "SELECT name FROM sysobjects "
  90. . "WHERE type = 'U' ORDER BY name";
  91. break;
  92. case 'mysql':
  93. $sql = 'SHOW TABLES';
  94. break;
  95. case 'oci':
  96. $sql = 'SELECT table_name FROM all_tables';
  97. break;
  98. case 'pgsql':
  99. $sql = "SELECT c.relname AS table_name "
  100. . "FROM pg_class c, pg_user u "
  101. . "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
  102. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  103. . "AND c.relname !~ '^(pg_|sql_)' "
  104. . "UNION "
  105. . "SELECT c.relname AS table_name "
  106. . "FROM pg_class c "
  107. . "WHERE c.relkind = 'r' "
  108. . "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
  109. . "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
  110. . "AND c.relname !~ '^pg_'";
  111. break;
  112. case 'sqlite':
  113. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  114. . "UNION ALL SELECT name FROM sqlite_temp_master "
  115. . "WHERE type='table' ORDER BY name";
  116. break;
  117. default:
  118. throw new Exception(
  119. 'PDO type ' .
  120. self::$_type .
  121. ' is currently not supported.',
  122. 5
  123. );
  124. }
  125. self::$_db = new PDO(
  126. $options['dsn'],
  127. $options['usr'],
  128. $options['pwd'],
  129. $options['opt']
  130. );
  131. $statement = self::$_db->query($sql);
  132. $tables = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
  133. // create paste table if needed
  134. if (!in_array(self::$_prefix . 'paste', $tables))
  135. {
  136. self::$_db->exec(
  137. 'CREATE TABLE ' . self::$_prefix . 'paste ( ' .
  138. 'dataid CHAR(16), ' .
  139. 'data TEXT, ' .
  140. 'postdate INT, ' .
  141. 'expiredate INT, ' .
  142. 'opendiscussion INT, ' .
  143. 'burnafterreading INT, ' .
  144. 'meta TEXT );'
  145. );
  146. }
  147. // check if the meta column exists
  148. else
  149. {
  150. try {
  151. self::$_db->exec('SELECT meta FROM ' . self::$_prefix . 'paste LIMIT 1;');
  152. } catch (PDOException $e) {
  153. if ($e->getCode() == 'HY000')
  154. {
  155. self::$_db->exec('ALTER TABLE ' . self::$_prefix . 'paste ADD COLUMN meta TEXT;');
  156. }
  157. }
  158. }
  159. // create comment table if needed
  160. if (!array_key_exists(self::$_prefix . 'comment', $tables))
  161. {
  162. self::$_db->exec(
  163. 'CREATE TABLE ' . self::$_prefix . 'comment ( ' .
  164. 'dataid CHAR(16), ' .
  165. 'pasteid CHAR(16), ' .
  166. 'parentid CHAR(16), ' .
  167. 'data TEXT, ' .
  168. 'nickname VARCHAR(255), ' .
  169. 'vizhash TEXT, ' .
  170. 'postdate INT );'
  171. );
  172. }
  173. }
  174. }
  175. return parent::$_instance;
  176. }
  177. /**
  178. * Create a paste.
  179. *
  180. * @access public
  181. * @param string $pasteid
  182. * @param array $paste
  183. * @return bool
  184. */
  185. public function create($pasteid, $paste)
  186. {
  187. if (
  188. array_key_exists($pasteid, self::$_cache)
  189. ) {
  190. if(false !== self::$_cache[$pasteid]) {
  191. return false;
  192. } else {
  193. unset(self::$_cache[$pasteid]);
  194. }
  195. }
  196. $opendiscussion = $burnafterreading = false;
  197. $meta = $paste['meta'];
  198. unset($meta['postdate']);
  199. $expire_date = 0;
  200. if (array_key_exists('expire_date', $paste['meta']))
  201. {
  202. $expire_date = (int) $paste['meta']['expire_date'];
  203. unset($meta['expire_date']);
  204. }
  205. if (array_key_exists('opendiscussion', $paste['meta']))
  206. {
  207. $opendiscussion = (bool) $paste['meta']['opendiscussion'];
  208. unset($meta['opendiscussion']);
  209. }
  210. if (array_key_exists('burnafterreading', $paste['meta']))
  211. {
  212. $burnafterreading = (bool) $paste['meta']['burnafterreading'];
  213. unset($meta['burnafterreading']);
  214. }
  215. return self::_exec(
  216. 'INSERT INTO ' . self::$_prefix . 'paste VALUES(?,?,?,?,?,?,?)',
  217. array(
  218. $pasteid,
  219. $paste['data'],
  220. $paste['meta']['postdate'],
  221. $expire_date,
  222. (int) $opendiscussion,
  223. (int) $burnafterreading,
  224. json_encode($meta),
  225. )
  226. );
  227. }
  228. /**
  229. * Read a paste.
  230. *
  231. * @access public
  232. * @param string $pasteid
  233. * @return stdClass|false
  234. */
  235. public function read($pasteid)
  236. {
  237. if (
  238. !array_key_exists($pasteid, self::$_cache)
  239. ) {
  240. self::$_cache[$pasteid] = false;
  241. $paste = self::_select(
  242. 'SELECT * FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  243. array($pasteid), true
  244. );
  245. if(false !== $paste) {
  246. // create object
  247. self::$_cache[$pasteid] = new stdClass;
  248. self::$_cache[$pasteid]->data = $paste['data'];
  249. $meta = json_decode($paste['meta']);
  250. if (!is_object($meta)) $meta = new stdClass;
  251. if (property_exists($meta, 'attachment'))
  252. {
  253. self::$_cache[$pasteid]->attachment = $meta->attachment;
  254. unset($meta->attachment);
  255. if (property_exists($meta, 'attachmentname'))
  256. {
  257. self::$_cache[$pasteid]->attachmentname = $meta->attachmentname;
  258. unset($meta->attachmentname);
  259. }
  260. }
  261. self::$_cache[$pasteid]->meta = $meta;
  262. self::$_cache[$pasteid]->meta->postdate = (int) $paste['postdate'];
  263. $expire_date = (int) $paste['expiredate'];
  264. if (
  265. $expire_date > 0
  266. ) self::$_cache[$pasteid]->meta->expire_date = $expire_date;
  267. if (
  268. $paste['opendiscussion']
  269. ) self::$_cache[$pasteid]->meta->opendiscussion = true;
  270. if (
  271. $paste['burnafterreading']
  272. ) self::$_cache[$pasteid]->meta->burnafterreading = true;
  273. }
  274. }
  275. return self::$_cache[$pasteid];
  276. }
  277. /**
  278. * Delete a paste and its discussion.
  279. *
  280. * @access public
  281. * @param string $pasteid
  282. * @return void
  283. */
  284. public function delete($pasteid)
  285. {
  286. self::_exec(
  287. 'DELETE FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  288. array($pasteid)
  289. );
  290. self::_exec(
  291. 'DELETE FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  292. array($pasteid)
  293. );
  294. if (
  295. array_key_exists($pasteid, self::$_cache)
  296. ) unset(self::$_cache[$pasteid]);
  297. }
  298. /**
  299. * Test if a paste exists.
  300. *
  301. * @access public
  302. * @param string $dataid
  303. * @return void
  304. */
  305. public function exists($pasteid)
  306. {
  307. if (
  308. !array_key_exists($pasteid, self::$_cache)
  309. ) self::$_cache[$pasteid] = $this->read($pasteid);
  310. return (bool) self::$_cache[$pasteid];
  311. }
  312. /**
  313. * Create a comment in a paste.
  314. *
  315. * @access public
  316. * @param string $pasteid
  317. * @param string $parentid
  318. * @param string $commentid
  319. * @param array $comment
  320. * @return int|false
  321. */
  322. public function createComment($pasteid, $parentid, $commentid, $comment)
  323. {
  324. return self::_exec(
  325. 'INSERT INTO ' . self::$_prefix . 'comment VALUES(?,?,?,?,?,?,?)',
  326. array(
  327. $commentid,
  328. $pasteid,
  329. $parentid,
  330. $comment['data'],
  331. $comment['meta']['nickname'],
  332. $comment['meta']['vizhash'],
  333. $comment['meta']['postdate'],
  334. )
  335. );
  336. }
  337. /**
  338. * Read all comments of paste.
  339. *
  340. * @access public
  341. * @param string $pasteid
  342. * @return array
  343. */
  344. public function readComments($pasteid)
  345. {
  346. $rows = self::_select(
  347. 'SELECT * FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  348. array($pasteid)
  349. );
  350. // create object
  351. $commentTemplate = new stdClass;
  352. $commentTemplate->meta = new stdClass;
  353. // create comment list
  354. $comments = array();
  355. if (count($rows))
  356. {
  357. foreach ($rows as $row)
  358. {
  359. $i = (int) $row['postdate'];
  360. $comments[$i] = clone $commentTemplate;
  361. $comments[$i]->data = $row['data'];
  362. $comments[$i]->meta->nickname = $row['nickname'];
  363. $comments[$i]->meta->vizhash = $row['vizhash'];
  364. $comments[$i]->meta->postdate = $i;
  365. $comments[$i]->meta->commentid = $row['dataid'];
  366. $comments[$i]->meta->parentid = $row['parentid'];
  367. }
  368. ksort($comments);
  369. }
  370. return $comments;
  371. }
  372. /**
  373. * Test if a comment exists.
  374. *
  375. * @access public
  376. * @param string $dataid
  377. * @param string $parentid
  378. * @param string $commentid
  379. * @return void
  380. */
  381. public function existsComment($pasteid, $parentid, $commentid)
  382. {
  383. return (bool) self::_select(
  384. 'SELECT dataid FROM ' . self::$_prefix . 'comment ' .
  385. 'WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  386. array($pasteid, $parentid, $commentid), true
  387. );
  388. }
  389. /**
  390. * execute a statement
  391. *
  392. * @access private
  393. * @static
  394. * @param string $sql
  395. * @param array $params
  396. * @throws PDOException
  397. * @return array
  398. */
  399. private static function _exec($sql, array $params)
  400. {
  401. $statement = self::$_db->prepare($sql);
  402. $result = $statement->execute($params);
  403. $statement->closeCursor();
  404. return $result;
  405. }
  406. /**
  407. * run a select statement
  408. *
  409. * @access private
  410. * @static
  411. * @param string $sql
  412. * @param array $params
  413. * @param bool $firstOnly if only the first row should be returned
  414. * @throws PDOException
  415. * @return array
  416. */
  417. private static function _select($sql, array $params, $firstOnly = false)
  418. {
  419. $statement = self::$_db->prepare($sql);
  420. $statement->execute($params);
  421. $result = $firstOnly ?
  422. $statement->fetch(PDO::FETCH_ASSOC) :
  423. $statement->fetchAll(PDO::FETCH_ASSOC);
  424. $statement->closeCursor();
  425. return $result;
  426. }
  427. }