1<?php
2
3/////////////////////////////////////////////////////////////////
4/// getID3() by James Heinrich <info@getid3.org>               //
5//  available at https://github.com/JamesHeinrich/getID3       //
6//            or https://www.getid3.org                        //
7//            or http://getid3.sourceforge.net                 //
8//                                                             //
9// extension.cache.mysql.php - part of getID3()                //
10// Please see readme.txt for more information                  //
11//                                                            ///
12/////////////////////////////////////////////////////////////////
13//                                                             //
14// This extension written by Allan Hansen <ahØartemis*dk>      //
15// Table name mod by Carlo Capocasa <calroØcarlocapocasa*com>  //
16//                                                            ///
17/////////////////////////////////////////////////////////////////
18
19
20/**
21* This is a caching extension for getID3(). It works the exact same
22* way as the getID3 class, but return cached information very fast
23*
24* Example:  (see also demo.cache.mysql.php in /demo/)
25*
26*    Normal getID3 usage (example):
27*
28*       require_once 'getid3/getid3.php';
29*       $getID3 = new getID3;
30*       $getID3->encoding = 'UTF-8';
31*       $info1 = $getID3->analyze('file1.flac');
32*       $info2 = $getID3->analyze('file2.wv');
33*
34*    getID3_cached usage:
35*
36*       require_once 'getid3/getid3.php';
37*       require_once 'getid3/getid3/extension.cache.mysql.php';
38*       // 5th parameter (tablename) is optional, default is 'getid3_cache'
39*       $getID3 = new getID3_cached_mysql('localhost', 'database', 'username', 'password', 'tablename');
40*       $getID3->encoding = 'UTF-8';
41*       $info1 = $getID3->analyze('file1.flac');
42*       $info2 = $getID3->analyze('file2.wv');
43*
44*
45* Supported Cache Types    (this extension)
46*
47*   SQL Databases:
48*
49*   cache_type          cache_options
50*   -------------------------------------------------------------------
51*   mysql               host, database, username, password
52*
53*
54*   DBM-Style Databases:    (use extension.cache.dbm)
55*
56*   cache_type          cache_options
57*   -------------------------------------------------------------------
58*   gdbm                dbm_filename, lock_filename
59*   ndbm                dbm_filename, lock_filename
60*   db2                 dbm_filename, lock_filename
61*   db3                 dbm_filename, lock_filename
62*   db4                 dbm_filename, lock_filename  (PHP5 required)
63*
64*   PHP must have write access to both dbm_filename and lock_filename.
65*
66*
67* Recommended Cache Types
68*
69*   Infrequent updates, many reads      any DBM
70*   Frequent updates                    mysql
71*/
72
73
74class getID3_cached_mysql extends getID3
75{
76	/**
77	 * @var resource
78	 */
79	private $cursor;
80
81	/**
82	 * @var resource
83	 */
84	private $connection;
85
86	/**
87	 * @var string
88	 */
89	private $table;
90
91
92	/**
93	 * constructor - see top of this file for cache type and cache_options
94	 *
95	 * @param string $host
96	 * @param string $database
97	 * @param string $username
98	 * @param string $password
99	 * @param string $table
100	 *
101	 * @throws Exception
102	 * @throws getid3_exception
103	 */
104	public function __construct($host, $database, $username, $password, $table='getid3_cache') {
105
106		// Check for mysql support
107		if (!function_exists('mysql_pconnect')) {
108			throw new Exception('PHP not compiled with mysql support.');
109		}
110
111		// Connect to database
112		$this->connection = mysql_pconnect($host, $username, $password);
113		if (!$this->connection) {
114			throw new Exception('mysql_pconnect() failed - check permissions and spelling.');
115		}
116
117		// Select database
118		if (!mysql_select_db($database, $this->connection)) {
119			throw new Exception('Cannot use database '.$database);
120		}
121
122		// Set table
123		$this->table = $table;
124
125		// Create cache table if not exists
126		$this->create_table();
127
128		// Check version number and clear cache if changed
129		$version = '';
130		$SQLquery  = 'SELECT `value`';
131		$SQLquery .= ' FROM `'.mysql_real_escape_string($this->table).'`';
132		$SQLquery .= ' WHERE (`filename` = \''.mysql_real_escape_string(getID3::VERSION).'\')';
133		$SQLquery .= ' AND (`filesize` = -1)';
134		$SQLquery .= ' AND (`filetime` = -1)';
135		$SQLquery .= ' AND (`analyzetime` = -1)';
136		if ($this->cursor = mysql_query($SQLquery, $this->connection)) {
137			list($version) = mysql_fetch_array($this->cursor);
138		}
139		if ($version != getID3::VERSION) {
140			$this->clear_cache();
141		}
142
143		parent::__construct();
144	}
145
146
147
148	/**
149	 * clear cache
150	 */
151	public function clear_cache() {
152
153		$this->cursor = mysql_query('DELETE FROM `'.mysql_real_escape_string($this->table).'`', $this->connection);
154		$this->cursor = mysql_query('INSERT INTO `'.mysql_real_escape_string($this->table).'` VALUES (\''.getID3::VERSION.'\', -1, -1, -1, \''.getID3::VERSION.'\')', $this->connection);
155	}
156
157
158
159	/**
160	 * analyze file
161	 *
162	 * @param string   $filename
163	 * @param int      $filesize
164	 * @param string   $original_filename
165	 * @param resource $fp
166	 *
167	 * @return mixed
168	 */
169	public function analyze($filename, $filesize=null, $original_filename='', $fp=null) {
170
171		$filetime = 0;
172		if (file_exists($filename)) {
173
174			// Short-hands
175			$filetime = filemtime($filename);
176			$filesize =  filesize($filename);
177
178			// Lookup file
179			$SQLquery  = 'SELECT `value`';
180			$SQLquery .= ' FROM `'.mysql_real_escape_string($this->table).'`';
181			$SQLquery .= ' WHERE (`filename` = \''.mysql_real_escape_string($filename).'\')';
182			$SQLquery .= '   AND (`filesize` = \''.mysql_real_escape_string($filesize).'\')';
183			$SQLquery .= '   AND (`filetime` = \''.mysql_real_escape_string($filetime).'\')';
184			$this->cursor = mysql_query($SQLquery, $this->connection);
185			if (mysql_num_rows($this->cursor) > 0) {
186				// Hit
187				list($result) = mysql_fetch_array($this->cursor);
188				return unserialize(base64_decode($result));
189			}
190		}
191
192		// Miss
193		$analysis = parent::analyze($filename, $filesize, $original_filename, $fp);
194
195		// Save result
196		if (file_exists($filename)) {
197			$SQLquery  = 'INSERT INTO `'.mysql_real_escape_string($this->table).'` (`filename`, `filesize`, `filetime`, `analyzetime`, `value`) VALUES (';
198			$SQLquery .=   '\''.mysql_real_escape_string($filename).'\'';
199			$SQLquery .= ', \''.mysql_real_escape_string($filesize).'\'';
200			$SQLquery .= ', \''.mysql_real_escape_string($filetime).'\'';
201			$SQLquery .= ', \''.mysql_real_escape_string(time()   ).'\'';
202			$SQLquery .= ', \''.mysql_real_escape_string(base64_encode(serialize($analysis))).'\')';
203			$this->cursor = mysql_query($SQLquery, $this->connection);
204		}
205		return $analysis;
206	}
207
208
209
210	/**
211	 * (re)create sql table
212	 *
213	 * @param bool $drop
214	 */
215	private function create_table($drop=false) {
216
217		$SQLquery  = 'CREATE TABLE IF NOT EXISTS `'.mysql_real_escape_string($this->table).'` (';
218		$SQLquery .=   '`filename` VARCHAR(990) NOT NULL DEFAULT \'\'';
219		$SQLquery .= ', `filesize` INT(11) NOT NULL DEFAULT \'0\'';
220		$SQLquery .= ', `filetime` INT(11) NOT NULL DEFAULT \'0\'';
221		$SQLquery .= ', `analyzetime` INT(11) NOT NULL DEFAULT \'0\'';
222		$SQLquery .= ', `value` LONGTEXT NOT NULL';
223		$SQLquery .= ', PRIMARY KEY (`filename`, `filesize`, `filetime`))';
224		$this->cursor = mysql_query($SQLquery, $this->connection);
225		echo mysql_error($this->connection);
226	}
227}
228