conn = new PDO('sqlite:../db/cache.db'); } public function getCache($key) { $query = "SELECT data FROM cache WHERE uri_key='$key'"; $result = $this->conn->query($query); return $result->fetchColumn(); } public function setCache($key, $title, $uri, $data) { $query = "INSERT INTO cache VALUES ('$title', '$key', '$uri', '$data', datetime('now'))"; if (!($this->conn->exec($query))) { $error = $this->conn->errorInfo(); throw new Exception($error[2]); } return $this->conn->lastInsertId(); } public function getAllCache() { $query = "SELECT rowid as id, * FROM cache"; $result = $this->conn->query($query); return $result->fetchAll(PDO::FETCH_ASSOC); } public function deleteCache($id) { $query = "DELETE FROM cache WHERE rowid=".(int)$id; $this->conn->exec($query); } public function clearCache() { $query = "DELETE FROM cache"; $this->conn->exec($query); } } /** * Reads the cache from the db and displays it * Returns false is not found in cache */ function readFromCache() { $key = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); $db = new CacheDb(); if (($data = $db->getCache($key)) !== false) { echo $data; exit(); } } function cachePage($uri, $title) { if (!($parseUrl = parse_url($uri))) { throw new Exception('Malformed URI'); } if ($parseUrl['scheme'] != 'http') { throw new Exception('Only http scheme is allowed'); } if ($parseUrl['host'] != $_SERVER['SERVER_NAME'] && $parseUrl['host'] != $_SERVER['SERVER_ADDR']) { throw new Exception('Remote hosts are not allowed'); } if (!($data = file_get_contents($uri))) { throw new Exception('Failed to load URI'); } $key = md5($parseUrl['host'] . (isset($parseUrl['path']) ? $parseUrl['path'] : '') . (isset($parseUrl['query']) ? '?'.$parseUrl['query'] : '')); $db = new CacheDb(); $db->setCache($key, $title, urlencode($uri), $data); } function getCacheList() { $db = new CacheDb(); return $db->getAllCache(); } function deleteCache($id) { $db = new CacheDb(); $db->deleteCache($id); } function clearCache() { $db = new CacheDb(); $db->clearCache(); }