PageRenderTime 106ms CodeModel.GetById 19ms RepoModel.GetById 13ms app.codeStats 0ms

/libs/Zend/Cache/Backend/Sqlite.php

https://github.com/quarkness/piwik
PHP | 678 lines | 386 code | 32 blank | 260 comment | 54 complexity | 507c9052187140bd66041d718534e40c MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Cache
  17. * @subpackage Zend_Cache_Backend
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Sqlite.php 24348 2011-08-04 17:51:24Z mabe $
  21. */
  22. /**
  23. * @see Zend_Cache_Backend_Interface
  24. */
  25. // require_once 'Zend/Cache/Backend/ExtendedInterface.php';
  26. /**
  27. * @see Zend_Cache_Backend
  28. */
  29. // require_once 'Zend/Cache/Backend.php';
  30. /**
  31. * @package Zend_Cache
  32. * @subpackage Zend_Cache_Backend
  33. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  34. * @license http://framework.zend.com/license/new-bsd New BSD License
  35. */
  36. class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
  37. {
  38. /**
  39. * Available options
  40. *
  41. * =====> (string) cache_db_complete_path :
  42. * - the complete path (filename included) of the SQLITE database
  43. *
  44. * ====> (int) automatic_vacuum_factor :
  45. * - Disable / Tune the automatic vacuum process
  46. * - The automatic vacuum process defragment the database file (and make it smaller)
  47. * when a clean() or delete() is called
  48. * 0 => no automatic vacuum
  49. * 1 => systematic vacuum (when delete() or clean() methods are called)
  50. * x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete()
  51. *
  52. * @var array Available options
  53. */
  54. protected $_options = array(
  55. 'cache_db_complete_path' => null,
  56. 'automatic_vacuum_factor' => 10
  57. );
  58. /**
  59. * DB ressource
  60. *
  61. * @var mixed $_db
  62. */
  63. private $_db = null;
  64. /**
  65. * Boolean to store if the structure has benn checked or not
  66. *
  67. * @var boolean $_structureChecked
  68. */
  69. private $_structureChecked = false;
  70. /**
  71. * Constructor
  72. *
  73. * @param array $options Associative array of options
  74. * @throws Zend_cache_Exception
  75. * @return void
  76. */
  77. public function __construct(array $options = array())
  78. {
  79. parent::__construct($options);
  80. if ($this->_options['cache_db_complete_path'] === null) {
  81. Zend_Cache::throwException('cache_db_complete_path option has to set');
  82. }
  83. if (!extension_loaded('sqlite')) {
  84. Zend_Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment");
  85. }
  86. $this->_getConnection();
  87. }
  88. /**
  89. * Destructor
  90. *
  91. * @return void
  92. */
  93. public function __destruct()
  94. {
  95. @sqlite_close($this->_getConnection());
  96. }
  97. /**
  98. * Test if a cache is available for the given id and (if yes) return it (false else)
  99. *
  100. * @param string $id Cache id
  101. * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
  102. * @return string|false Cached datas
  103. */
  104. public function load($id, $doNotTestCacheValidity = false)
  105. {
  106. $this->_checkAndBuildStructure();
  107. $sql = "SELECT content FROM cache WHERE id='$id'";
  108. if (!$doNotTestCacheValidity) {
  109. $sql = $sql . " AND (expire=0 OR expire>" . time() . ')';
  110. }
  111. $result = $this->_query($sql);
  112. $row = @sqlite_fetch_array($result);
  113. if ($row) {
  114. return $row['content'];
  115. }
  116. return false;
  117. }
  118. /**
  119. * Test if a cache is available or not (for the given id)
  120. *
  121. * @param string $id Cache id
  122. * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
  123. */
  124. public function test($id)
  125. {
  126. $this->_checkAndBuildStructure();
  127. $sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
  128. $result = $this->_query($sql);
  129. $row = @sqlite_fetch_array($result);
  130. if ($row) {
  131. return ((int) $row['lastModified']);
  132. }
  133. return false;
  134. }
  135. /**
  136. * Save some string datas into a cache record
  137. *
  138. * Note : $data is always "string" (serialization is done by the
  139. * core not by the backend)
  140. *
  141. * @param string $data Datas to cache
  142. * @param string $id Cache id
  143. * @param array $tags Array of strings, the cache record will be tagged by each string entry
  144. * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
  145. * @throws Zend_Cache_Exception
  146. * @return boolean True if no problem
  147. */
  148. public function save($data, $id, $tags = array(), $specificLifetime = false)
  149. {
  150. $this->_checkAndBuildStructure();
  151. $lifetime = $this->getLifetime($specificLifetime);
  152. $data = @sqlite_escape_string($data);
  153. $mktime = time();
  154. if ($lifetime === null) {
  155. $expire = 0;
  156. } else {
  157. $expire = $mktime + $lifetime;
  158. }
  159. $this->_query("DELETE FROM cache WHERE id='$id'");
  160. $sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)";
  161. $res = $this->_query($sql);
  162. if (!$res) {
  163. $this->_log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id");
  164. return false;
  165. }
  166. $res = true;
  167. foreach ($tags as $tag) {
  168. $res = $this->_registerTag($id, $tag) && $res;
  169. }
  170. return $res;
  171. }
  172. /**
  173. * Remove a cache record
  174. *
  175. * @param string $id Cache id
  176. * @return boolean True if no problem
  177. */
  178. public function remove($id)
  179. {
  180. $this->_checkAndBuildStructure();
  181. $res = $this->_query("SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'");
  182. $result1 = @sqlite_fetch_single($res);
  183. $result2 = $this->_query("DELETE FROM cache WHERE id='$id'");
  184. $result3 = $this->_query("DELETE FROM tag WHERE id='$id'");
  185. $this->_automaticVacuum();
  186. return ($result1 && $result2 && $result3);
  187. }
  188. /**
  189. * Clean some cache records
  190. *
  191. * Available modes are :
  192. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  193. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  194. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  195. * ($tags can be an array of strings or a single string)
  196. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  197. * ($tags can be an array of strings or a single string)
  198. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  199. * ($tags can be an array of strings or a single string)
  200. *
  201. * @param string $mode Clean mode
  202. * @param array $tags Array of tags
  203. * @return boolean True if no problem
  204. */
  205. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  206. {
  207. $this->_checkAndBuildStructure();
  208. $return = $this->_clean($mode, $tags);
  209. $this->_automaticVacuum();
  210. return $return;
  211. }
  212. /**
  213. * Return an array of stored cache ids
  214. *
  215. * @return array array of stored cache ids (string)
  216. */
  217. public function getIds()
  218. {
  219. $this->_checkAndBuildStructure();
  220. $res = $this->_query("SELECT id FROM cache WHERE (expire=0 OR expire>" . time() . ")");
  221. $result = array();
  222. while ($id = @sqlite_fetch_single($res)) {
  223. $result[] = $id;
  224. }
  225. return $result;
  226. }
  227. /**
  228. * Return an array of stored tags
  229. *
  230. * @return array array of stored tags (string)
  231. */
  232. public function getTags()
  233. {
  234. $this->_checkAndBuildStructure();
  235. $res = $this->_query("SELECT DISTINCT(name) AS name FROM tag");
  236. $result = array();
  237. while ($id = @sqlite_fetch_single($res)) {
  238. $result[] = $id;
  239. }
  240. return $result;
  241. }
  242. /**
  243. * Return an array of stored cache ids which match given tags
  244. *
  245. * In case of multiple tags, a logical AND is made between tags
  246. *
  247. * @param array $tags array of tags
  248. * @return array array of matching cache ids (string)
  249. */
  250. public function getIdsMatchingTags($tags = array())
  251. {
  252. $first = true;
  253. $ids = array();
  254. foreach ($tags as $tag) {
  255. $res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
  256. if (!$res) {
  257. return array();
  258. }
  259. $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
  260. $ids2 = array();
  261. foreach ($rows as $row) {
  262. $ids2[] = $row['id'];
  263. }
  264. if ($first) {
  265. $ids = $ids2;
  266. $first = false;
  267. } else {
  268. $ids = array_intersect($ids, $ids2);
  269. }
  270. }
  271. $result = array();
  272. foreach ($ids as $id) {
  273. $result[] = $id;
  274. }
  275. return $result;
  276. }
  277. /**
  278. * Return an array of stored cache ids which don't match given tags
  279. *
  280. * In case of multiple tags, a logical OR is made between tags
  281. *
  282. * @param array $tags array of tags
  283. * @return array array of not matching cache ids (string)
  284. */
  285. public function getIdsNotMatchingTags($tags = array())
  286. {
  287. $res = $this->_query("SELECT id FROM cache");
  288. $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
  289. $result = array();
  290. foreach ($rows as $row) {
  291. $id = $row['id'];
  292. $matching = false;
  293. foreach ($tags as $tag) {
  294. $res = $this->_query("SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'");
  295. if (!$res) {
  296. return array();
  297. }
  298. $nbr = (int) @sqlite_fetch_single($res);
  299. if ($nbr > 0) {
  300. $matching = true;
  301. }
  302. }
  303. if (!$matching) {
  304. $result[] = $id;
  305. }
  306. }
  307. return $result;
  308. }
  309. /**
  310. * Return an array of stored cache ids which match any given tags
  311. *
  312. * In case of multiple tags, a logical AND is made between tags
  313. *
  314. * @param array $tags array of tags
  315. * @return array array of any matching cache ids (string)
  316. */
  317. public function getIdsMatchingAnyTags($tags = array())
  318. {
  319. $first = true;
  320. $ids = array();
  321. foreach ($tags as $tag) {
  322. $res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
  323. if (!$res) {
  324. return array();
  325. }
  326. $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
  327. $ids2 = array();
  328. foreach ($rows as $row) {
  329. $ids2[] = $row['id'];
  330. }
  331. if ($first) {
  332. $ids = $ids2;
  333. $first = false;
  334. } else {
  335. $ids = array_merge($ids, $ids2);
  336. }
  337. }
  338. $result = array();
  339. foreach ($ids as $id) {
  340. $result[] = $id;
  341. }
  342. return $result;
  343. }
  344. /**
  345. * Return the filling percentage of the backend storage
  346. *
  347. * @throws Zend_Cache_Exception
  348. * @return int integer between 0 and 100
  349. */
  350. public function getFillingPercentage()
  351. {
  352. $dir = dirname($this->_options['cache_db_complete_path']);
  353. $free = disk_free_space($dir);
  354. $total = disk_total_space($dir);
  355. if ($total == 0) {
  356. Zend_Cache::throwException('can\'t get disk_total_space');
  357. } else {
  358. if ($free >= $total) {
  359. return 100;
  360. }
  361. return ((int) (100. * ($total - $free) / $total));
  362. }
  363. }
  364. /**
  365. * Return an array of metadatas for the given cache id
  366. *
  367. * The array must include these keys :
  368. * - expire : the expire timestamp
  369. * - tags : a string array of tags
  370. * - mtime : timestamp of last modification time
  371. *
  372. * @param string $id cache id
  373. * @return array array of metadatas (false if the cache id is not found)
  374. */
  375. public function getMetadatas($id)
  376. {
  377. $tags = array();
  378. $res = $this->_query("SELECT name FROM tag WHERE id='$id'");
  379. if ($res) {
  380. $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
  381. foreach ($rows as $row) {
  382. $tags[] = $row['name'];
  383. }
  384. }
  385. $this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
  386. $res = $this->_query("SELECT lastModified,expire FROM cache WHERE id='$id'");
  387. if (!$res) {
  388. return false;
  389. }
  390. $row = @sqlite_fetch_array($res, SQLITE_ASSOC);
  391. return array(
  392. 'tags' => $tags,
  393. 'mtime' => $row['lastModified'],
  394. 'expire' => $row['expire']
  395. );
  396. }
  397. /**
  398. * Give (if possible) an extra lifetime to the given cache id
  399. *
  400. * @param string $id cache id
  401. * @param int $extraLifetime
  402. * @return boolean true if ok
  403. */
  404. public function touch($id, $extraLifetime)
  405. {
  406. $sql = "SELECT expire FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
  407. $res = $this->_query($sql);
  408. if (!$res) {
  409. return false;
  410. }
  411. $expire = @sqlite_fetch_single($res);
  412. $newExpire = $expire + $extraLifetime;
  413. $res = $this->_query("UPDATE cache SET lastModified=" . time() . ", expire=$newExpire WHERE id='$id'");
  414. if ($res) {
  415. return true;
  416. } else {
  417. return false;
  418. }
  419. }
  420. /**
  421. * Return an associative array of capabilities (booleans) of the backend
  422. *
  423. * The array must include these keys :
  424. * - automatic_cleaning (is automating cleaning necessary)
  425. * - tags (are tags supported)
  426. * - expired_read (is it possible to read expired cache records
  427. * (for doNotTestCacheValidity option for example))
  428. * - priority does the backend deal with priority when saving
  429. * - infinite_lifetime (is infinite lifetime can work with this backend)
  430. * - get_list (is it possible to get the list of cache ids and the complete list of tags)
  431. *
  432. * @return array associative of with capabilities
  433. */
  434. public function getCapabilities()
  435. {
  436. return array(
  437. 'automatic_cleaning' => true,
  438. 'tags' => true,
  439. 'expired_read' => true,
  440. 'priority' => false,
  441. 'infinite_lifetime' => true,
  442. 'get_list' => true
  443. );
  444. }
  445. /**
  446. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  447. *
  448. * Force a cache record to expire
  449. *
  450. * @param string $id Cache id
  451. */
  452. public function ___expire($id)
  453. {
  454. $time = time() - 1;
  455. $this->_query("UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'");
  456. }
  457. /**
  458. * Return the connection resource
  459. *
  460. * If we are not connected, the connection is made
  461. *
  462. * @throws Zend_Cache_Exception
  463. * @return resource Connection resource
  464. */
  465. private function _getConnection()
  466. {
  467. if (is_resource($this->_db)) {
  468. return $this->_db;
  469. } else {
  470. $this->_db = @sqlite_open($this->_options['cache_db_complete_path']);
  471. if (!(is_resource($this->_db))) {
  472. Zend_Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file");
  473. }
  474. return $this->_db;
  475. }
  476. }
  477. /**
  478. * Execute an SQL query silently
  479. *
  480. * @param string $query SQL query
  481. * @return mixed|false query results
  482. */
  483. private function _query($query)
  484. {
  485. $db = $this->_getConnection();
  486. if (is_resource($db)) {
  487. $res = @sqlite_query($db, $query);
  488. if ($res === false) {
  489. return false;
  490. } else {
  491. return $res;
  492. }
  493. }
  494. return false;
  495. }
  496. /**
  497. * Deal with the automatic vacuum process
  498. *
  499. * @return void
  500. */
  501. private function _automaticVacuum()
  502. {
  503. if ($this->_options['automatic_vacuum_factor'] > 0) {
  504. $rand = rand(1, $this->_options['automatic_vacuum_factor']);
  505. if ($rand == 1) {
  506. $this->_query('VACUUM');
  507. }
  508. }
  509. }
  510. /**
  511. * Register a cache id with the given tag
  512. *
  513. * @param string $id Cache id
  514. * @param string $tag Tag
  515. * @return boolean True if no problem
  516. */
  517. private function _registerTag($id, $tag) {
  518. $res = $this->_query("DELETE FROM TAG WHERE name='$tag' AND id='$id'");
  519. $res = $this->_query("INSERT INTO tag (name, id) VALUES ('$tag', '$id')");
  520. if (!$res) {
  521. $this->_log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id");
  522. return false;
  523. }
  524. return true;
  525. }
  526. /**
  527. * Build the database structure
  528. *
  529. * @return false
  530. */
  531. private function _buildStructure()
  532. {
  533. $this->_query('DROP INDEX tag_id_index');
  534. $this->_query('DROP INDEX tag_name_index');
  535. $this->_query('DROP INDEX cache_id_expire_index');
  536. $this->_query('DROP TABLE version');
  537. $this->_query('DROP TABLE cache');
  538. $this->_query('DROP TABLE tag');
  539. $this->_query('CREATE TABLE version (num INTEGER PRIMARY KEY)');
  540. $this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
  541. $this->_query('CREATE TABLE tag (name TEXT, id TEXT)');
  542. $this->_query('CREATE INDEX tag_id_index ON tag(id)');
  543. $this->_query('CREATE INDEX tag_name_index ON tag(name)');
  544. $this->_query('CREATE INDEX cache_id_expire_index ON cache(id, expire)');
  545. $this->_query('INSERT INTO version (num) VALUES (1)');
  546. }
  547. /**
  548. * Check if the database structure is ok (with the good version)
  549. *
  550. * @return boolean True if ok
  551. */
  552. private function _checkStructureVersion()
  553. {
  554. $result = $this->_query("SELECT num FROM version");
  555. if (!$result) return false;
  556. $row = @sqlite_fetch_array($result);
  557. if (!$row) {
  558. return false;
  559. }
  560. if (((int) $row['num']) != 1) {
  561. // old cache structure
  562. $this->_log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped');
  563. return false;
  564. }
  565. return true;
  566. }
  567. /**
  568. * Clean some cache records
  569. *
  570. * Available modes are :
  571. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  572. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  573. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  574. * ($tags can be an array of strings or a single string)
  575. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  576. * ($tags can be an array of strings or a single string)
  577. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  578. * ($tags can be an array of strings or a single string)
  579. *
  580. * @param string $mode Clean mode
  581. * @param array $tags Array of tags
  582. * @return boolean True if no problem
  583. */
  584. private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  585. {
  586. switch ($mode) {
  587. case Zend_Cache::CLEANING_MODE_ALL:
  588. $res1 = $this->_query('DELETE FROM cache');
  589. $res2 = $this->_query('DELETE FROM tag');
  590. return $res1 && $res2;
  591. break;
  592. case Zend_Cache::CLEANING_MODE_OLD:
  593. $mktime = time();
  594. $res1 = $this->_query("DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)");
  595. $res2 = $this->_query("DELETE FROM cache WHERE expire>0 AND expire<=$mktime");
  596. return $res1 && $res2;
  597. break;
  598. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  599. $ids = $this->getIdsMatchingTags($tags);
  600. $result = true;
  601. foreach ($ids as $id) {
  602. $result = $this->remove($id) && $result;
  603. }
  604. return $result;
  605. break;
  606. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  607. $ids = $this->getIdsNotMatchingTags($tags);
  608. $result = true;
  609. foreach ($ids as $id) {
  610. $result = $this->remove($id) && $result;
  611. }
  612. return $result;
  613. break;
  614. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  615. $ids = $this->getIdsMatchingAnyTags($tags);
  616. $result = true;
  617. foreach ($ids as $id) {
  618. $result = $this->remove($id) && $result;
  619. }
  620. return $result;
  621. break;
  622. default:
  623. break;
  624. }
  625. return false;
  626. }
  627. /**
  628. * Check if the database structure is ok (with the good version), if no : build it
  629. *
  630. * @throws Zend_Cache_Exception
  631. * @return boolean True if ok
  632. */
  633. private function _checkAndBuildStructure()
  634. {
  635. if (!($this->_structureChecked)) {
  636. if (!$this->_checkStructureVersion()) {
  637. $this->_buildStructure();
  638. if (!$this->_checkStructureVersion()) {
  639. Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']);
  640. }
  641. }
  642. $this->_structureChecked = true;
  643. }
  644. return true;
  645. }
  646. }