db.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 (!array_key_exists(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. unset($meta['expire_date']);
  200. if (array_key_exists('opendiscussion', $paste['meta']))
  201. {
  202. $opendiscussion = (bool) $paste['meta']['opendiscussion'];
  203. unset($meta['opendiscussion']);
  204. }
  205. if (array_key_exists('burnafterreading', $paste['meta']))
  206. {
  207. $burnafterreading = (bool) $paste['meta']['burnafterreading'];
  208. unset($meta['burnafterreading']);
  209. }
  210. return self::_exec(
  211. 'INSERT INTO ' . self::$_prefix . 'paste VALUES(?,?,?,?,?,?,?)',
  212. array(
  213. $pasteid,
  214. $paste['data'],
  215. $paste['meta']['postdate'],
  216. $paste['meta']['expire_date'],
  217. (int) $opendiscussion,
  218. (int) $burnafterreading,
  219. json_encode($meta),
  220. )
  221. );
  222. }
  223. /**
  224. * Read a paste.
  225. *
  226. * @access public
  227. * @param string $pasteid
  228. * @return stdClass|false
  229. */
  230. public function read($pasteid)
  231. {
  232. if (
  233. !array_key_exists($pasteid, self::$_cache)
  234. ) {
  235. self::$_cache[$pasteid] = false;
  236. $paste = self::_select(
  237. 'SELECT * FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  238. array($pasteid), true
  239. );
  240. if(false !== $paste) {
  241. // create object
  242. self::$_cache[$pasteid] = new stdClass;
  243. self::$_cache[$pasteid]->data = $paste['data'];
  244. self::$_cache[$pasteid]->meta = json_decode($paste['meta']);
  245. self::$_cache[$pasteid]->meta->postdate = (int) $paste['postdate'];
  246. self::$_cache[$pasteid]->meta->expire_date = (int) $paste['expiredate'];
  247. if (
  248. $paste['opendiscussion']
  249. ) self::$_cache[$pasteid]->meta->opendiscussion = true;
  250. if (
  251. $paste['burnafterreading']
  252. ) self::$_cache[$pasteid]->meta->burnafterreading = true;
  253. if (property_exists(self::$_cache[$pasteid]->meta, 'attachment'))
  254. {
  255. self::$_cache[$pasteid]->attachment = self::$_cache[$pasteid]->meta->attachment;
  256. unset(self::$_cache[$pasteid]->meta->attachment);
  257. if (property_exists(self::$_cache[$pasteid]->meta, 'attachmentname'))
  258. {
  259. self::$_cache[$pasteid]->attachmentname = self::$_cache[$pasteid]->meta->attachmentname;
  260. unset(self::$_cache[$pasteid]->meta->attachmentname);
  261. }
  262. }
  263. elseif (array_key_exists('attachment', $paste))
  264. {
  265. self::$_cache[$pasteid]->attachment = $paste['attachment'];
  266. if (array_key_exists('attachmentname', $paste))
  267. {
  268. self::$_cache[$pasteid]->attachmentname = $paste['attachmentname'];
  269. }
  270. }
  271. }
  272. }
  273. return self::$_cache[$pasteid];
  274. }
  275. /**
  276. * Delete a paste and its discussion.
  277. *
  278. * @access public
  279. * @param string $pasteid
  280. * @return void
  281. */
  282. public function delete($pasteid)
  283. {
  284. self::_exec(
  285. 'DELETE FROM ' . self::$_prefix . 'paste WHERE dataid = ?',
  286. array($pasteid)
  287. );
  288. self::_exec(
  289. 'DELETE FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  290. array($pasteid)
  291. );
  292. if (
  293. array_key_exists($pasteid, self::$_cache)
  294. ) unset(self::$_cache[$pasteid]);
  295. }
  296. /**
  297. * Test if a paste exists.
  298. *
  299. * @access public
  300. * @param string $dataid
  301. * @return void
  302. */
  303. public function exists($pasteid)
  304. {
  305. if (
  306. !array_key_exists($pasteid, self::$_cache)
  307. ) self::$_cache[$pasteid] = $this->read($pasteid);
  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 int|false
  319. */
  320. public function createComment($pasteid, $parentid, $commentid, $comment)
  321. {
  322. return self::_exec(
  323. 'INSERT INTO ' . self::$_prefix . 'comment VALUES(?,?,?,?,?,?,?)',
  324. array(
  325. $commentid,
  326. $pasteid,
  327. $parentid,
  328. $comment['data'],
  329. $comment['meta']['nickname'],
  330. $comment['meta']['vizhash'],
  331. $comment['meta']['postdate'],
  332. )
  333. );
  334. }
  335. /**
  336. * Read all comments of paste.
  337. *
  338. * @access public
  339. * @param string $pasteid
  340. * @return array
  341. */
  342. public function readComments($pasteid)
  343. {
  344. $rows = self::_select(
  345. 'SELECT * FROM ' . self::$_prefix . 'comment WHERE pasteid = ?',
  346. array($pasteid)
  347. );
  348. // create object
  349. $commentTemplate = new stdClass;
  350. $commentTemplate->meta = new stdClass;
  351. // create comment list
  352. $comments = array();
  353. if (count($rows))
  354. {
  355. foreach ($rows as $row)
  356. {
  357. $i = (int) $row['postdate'];
  358. $comments[$i] = clone $commentTemplate;
  359. $comments[$i]->data = $row['data'];
  360. $comments[$i]->meta->nickname = $row['nickname'];
  361. $comments[$i]->meta->vizhash = $row['vizhash'];
  362. $comments[$i]->meta->postdate = $i;
  363. $comments[$i]->meta->commentid = $row['dataid'];
  364. $comments[$i]->meta->parentid = $row['parentid'];
  365. }
  366. ksort($comments);
  367. }
  368. return $comments;
  369. }
  370. /**
  371. * Test if a comment exists.
  372. *
  373. * @access public
  374. * @param string $dataid
  375. * @param string $parentid
  376. * @param string $commentid
  377. * @return void
  378. */
  379. public function existsComment($pasteid, $parentid, $commentid)
  380. {
  381. return (bool) self::_select(
  382. 'SELECT dataid FROM ' . self::$_prefix . 'comment ' .
  383. 'WHERE pasteid = ? AND parentid = ? AND dataid = ?',
  384. array($pasteid, $parentid, $commentid), true
  385. );
  386. }
  387. /**
  388. * execute a statement
  389. *
  390. * @access private
  391. * @static
  392. * @param string $sql
  393. * @param array $params
  394. * @throws PDOException
  395. * @return array
  396. */
  397. private static function _exec($sql, array $params)
  398. {
  399. $statement = self::$_db->prepare($sql);
  400. $result = $statement->execute($params);
  401. $statement->closeCursor();
  402. return $result;
  403. }
  404. /**
  405. * run a select statement
  406. *
  407. * @access private
  408. * @static
  409. * @param string $sql
  410. * @param array $params
  411. * @param bool $firstOnly if only the first row should be returned
  412. * @throws PDOException
  413. * @return array
  414. */
  415. private static function _select($sql, array $params, $firstOnly = false)
  416. {
  417. $statement = self::$_db->prepare($sql);
  418. $statement->execute($params);
  419. $result = $firstOnly ?
  420. $statement->fetch(PDO::FETCH_ASSOC) :
  421. $statement->fetchAll(PDO::FETCH_ASSOC);
  422. $statement->closeCursor();
  423. return $result;
  424. }
  425. }