[xiph-commits] r14710 - in branches/dir.xiph.org: cgi-bin cronjobs inc

balbinus at svn.xiph.org balbinus at svn.xiph.org
Fri Apr 11 11:25:21 PDT 2008


Author: balbinus
Date: 2008-04-11 11:25:21 -0700 (Fri, 11 Apr 2008)
New Revision: 14710

Modified:
   branches/dir.xiph.org/cgi-bin/yp.php
   branches/dir.xiph.org/cronjobs/prune_mountpoints.php
   branches/dir.xiph.org/inc/class.mountpoint.php
   branches/dir.xiph.org/inc/class.server.php
   branches/dir.xiph.org/inc/class.tag.php
   branches/dir.xiph.org/inc/lib.apilog.php
Log:
Modifications batch.

Use objects everywhere (first part).

 * cronjobs/prune_mountpoints.php:
     Change timeout to 10 minutes.
 * cgi-bin/yp.php:
     New reason for refusing to add: duplicate (server is already in the db).
     Genre: replace the forbidden chars by spaces instead of blank, so that they
     get correctly split. Added possible cause for refusal in case of illegal
     listen_url. Use objects for db operations. Counters are handled by
     Mountpoint now (and are subsequently related to mountpoints, not servers).
     On server removal, remove the mountpoint too if it has no more linked
     servers.
 * inc/class.server.php:
     New retrieveByListenUrl() method. New retrieveByMountpointId() method. New
     remove() method. Don't use INSERT... ON DUPLICATE KEY. Handle the "checked"
     field. New removeFromDb() / removeFromCache() protected methods.
 * inc/class.tag.php:
     New deleteMountpointTags() method.
 * inc/class.mountpoint.php:
     This class now handles the counters too. New findSimilar() method. New
     hasLinkedServers() method. New remove() method. New incrementCounter()
     method. New decrementCounter() method. Don't use INSERT... ON DUPLICATE
     KEY. $table_name is now a static property. New removeFromDb() /
     removeFromCache() protected methods.
 * inc/lib.apilog.php:
     New serverRemoved() / mountpointRemoved() methods for logging server and
     mountpoint removals.


Modified: branches/dir.xiph.org/cgi-bin/yp.php
===================================================================
--- branches/dir.xiph.org/cgi-bin/yp.php	2008-04-11 11:23:07 UTC (rev 14709)
+++ branches/dir.xiph.org/cgi-bin/yp.php	2008-04-11 18:25:21 UTC (rev 14710)
@@ -13,6 +13,7 @@
 define('SERVER_REFUSED_MISSING_ARG', 0);
 define('SERVER_REFUSED_PARSE_ERROR', 1);
 define('SERVER_REFUSED_ILLEGAL_URL', 2);
+define('SERVER_REFUSED_DUPLICATE',   3);
 
 // Do we have enough data?
 if (!array_key_exists('action', $_REQUEST))
@@ -62,8 +63,8 @@
 		    // Genre, space-normalized
 		    $genre = mb_convert_encoding($_REQUEST['genre'], 'UTF-8',
                                          'UTF-8,ISO-8859-1,auto');
-		    $genre = str_replace(array('+', '-', '*', '<', '>', '~', '"', '(', ')', '|', '!', '?', ',', ';', ':'),
-							     array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''),
+		    $genre = str_replace(array('+', '-', '*', '<', '>', '~', '"', '(', ')', '|', '!', '?', ',', ';', ':', '/'),
+							     array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '),
 							     $genre);
 		    $genre = preg_replace('/\s+/', ' ', $genre);
 		    $genre_list = array_slice(explode(' ', $genre), 0, 10);
@@ -82,7 +83,7 @@
                 || !preg_match('/^.*[A-Za-z0-9\-]+\.[A-Za-z0-9]+$/', $url['host'])
                 || preg_match('/^(10\.|192\.168\.|127\.)/', $url['host']))
             {
-                throw new ServerRefusedAPIException('Illegal listen_url.', SERVER_REFUSED_ILLEGAL_URL, $listen_url);
+                throw new ServerRefusedAPIException('Illegal listen_url. Incorrect <hostname>.', SERVER_REFUSED_ILLEGAL_URL, $listen_url);
             }
 		
 		    // Cluster password
@@ -92,48 +93,18 @@
 		    // URL
 		    $url = array_key_exists('url', $_REQUEST) ? $_REQUEST['url'] : null;
 		
-		    // MySQL Connection
-		    $db = DirXiphOrgDBC::getInstance();
-		
-		    // Look for the mountpoint (same listen URL)
-		    $server_id = $sid = null;
-		    $query = 'SELECT `id`, `mountpoint_id` FROM `server` WHERE `listen_url` = "%s";';
-		    $query = sprintf($query, mysql_real_escape_string($listen_url));
-		    $mp_id = $server_id = false; // MySQL auto-increment keys can't be 0
-		    $mp = $server = null;
-		    try
+		    // Look for the server (same listen URL)
+		    $server = Server::retrieveByListenUrl($listen_url);
+		    if ($server instanceOf Server)
 		    {
-			    // The mountpoint exists yet. Either an error from the Icecast server, or
-			    // we didn't wipe out old stuff fast enough.
-			    $res = $db->singleQuery($query);
-			    $mp_id = $res->current('mountpoint_id');
-			    $mp = Mountpoint::retrieveByPk($mp_id);
-			    $server_id = $res->current('id');
-			    $server = Server::retrieveByPk($server_id);
+		        throw new ServerRefusedAPIException('Entry already in the YP.', SERVER_REFUSED_DUPLICATE, $listen_url);
 		    }
-		    catch (SQLNoResultException $e)
-		    {
-			    // The mountpoint doesn't exist yet in our database (it's OK)
-		    }
 	        
-		    // Look for the mountpoint, bis (different listen URL, same stream name)
-		    $query = 'SELECT `id` FROM `mountpoint` WHERE `stream_name` = "%s" AND `media_type_id` = %d AND `bitrate` = %d;';
-		    $query = sprintf($query, mysql_real_escape_string($stream_name), content_type_lookup($media_type), mysql_real_escape_string($bitrate));
-		    try
-		    {
-			    // The mountpoint exists, only a different server.
-			    $res = $db->singleQuery($query);
-			    $mp_id = $res->current('id');
-			    $mp = Mountpoint::retrieveByPk($mp_id);
-		    }
-		    catch (SQLNoResultException $e)
-		    {
-			    // The mountpoint doesn't exist yet in our database (it's OK)
-		    }
+		    // Look for the mountpoint (different listen URL, same stream name)
+            $mountpoint = Mountpoint::findSimilar($stream_name,
+                                                  content_type_lookup($media_type),
+                                                  $bitrate);
 		
-		    // SID
-		    $sid = UUIDGen::generate();
-		
 		    // Mountpoint
 		    if (!($mp instanceOf Mountpoint))
 		    {
@@ -149,6 +120,9 @@
 			
 			    if ($mp_id !== false)
 			    {
+		            $mp->incrementCounter(Mountpoint::COUNTER_TOTAL);
+		            $mp->incrementCounter(Mountpoint::COUNTER_MEDIA_TYPE);
+		            
 			        // Log
 			        APILog::mountpointAdded(true, $mp_id, $listen_url);
 			        
@@ -163,9 +137,12 @@
 			        APILog::mountpointAdded(false, $mp_id, $listen_url);
 			    }
 		    }
-		
+		    
+		    // SID
+		    $sid = UUIDGen::generate();
+		    
 		    // Server
-		    if ($mp instanceOf Mountpoint && !$server_id)
+		    if ($mp instanceOf Mountpoint)
 		    {
 		        $server = new Server(0, false, true);
 		        $server->setMountpointId($mp_id);
@@ -189,21 +166,9 @@
 		        }
 		    }
 	        
-		    // Tags and stuff
+		    // Final response
 		    if ($mp instanceOf Mountpoint && $server instanceOf Server)
 		    {
-			    // Increment the "total servers" key in memcache
-			    if (!$memcache->increment(ENVIRONMENT.'_servers_total'))
-     			{
-				    $memcache->set(ENVIRONMENT.'_servers_total', 1);
-			    }
-			    $ct_id = content_type_lookup($media_type);
-			    $ct_key = ENVIRONMENT.'_servers_'.intval($ct_id);
-			    if (!$memcache->increment($ct_key))
-			    {
-				    $memcache->set($ct_key, 1);
-			    }
-			
 			    // Return success
 			    header("YPResponse: 1");
 			    header("YPMessage: Successfully added.");
@@ -259,7 +224,7 @@
 			        throw new APIException("Not enough arguments.");
 		        }
 		    }
-		
+		    
 		    // SID
 		    $sid = preg_replace('/[^A-F0-9\-]/', '', strtoupper ($_REQUEST['sid']));
 		    // Remote IP
@@ -277,19 +242,21 @@
 		    $max_listeners = array_key_exists('max_listeners', $_REQUEST)
         		             ? intval($_REQUEST['max_listeners']) : 0;
 		
-		    // MySQL Connection
-		    $db = DirXiphOrgDBC::getInstance();
-		
-		    // Update the data
+		    // Find the server
 		    $server = Server::retrieveBySID($sid);
 		    if (!($server instanceOf Server))
 		    {
 		        throw new NoSuchSIDAPIException();
 		    }
-		    $query = 'UPDATE `server` SET `current_song` = "%s", `listeners` = %d, `last_touched_from` = INET_ATON("%s"), `last_touched_at` = NOW() WHERE `sid` = "%s";';
-		    $query = sprintf($query, mysql_real_escape_string($current_song), $listeners, mysql_real_escape_string($ip), mysql_real_escape_string($sid));
-		    $res = $db->noReturnQuery($query);
-		    if ($res && $db->affected_rows > 0)
+		    
+		    // Update the data
+		    $server->setCurrentSong($current_song);
+		    $server->setListeners($listeners);
+		    $server->setLastTouchedFrom($ip);
+		    $server->setLastTouchedAt();
+		    $res = $server->save();
+		    
+		    if ($res !== false)
 		    {
 			    // Return success
 			    header("YPResponse: 1");
@@ -301,7 +268,13 @@
 		    }
 		    else
 		    {
-		        throw new NoSuchSIDAPIException();
+			    // Return success
+			    header("YPResponse: 1");
+			    header("YPMessage: Unable to save new server data.");
+			    
+                // Log stuff
+                APILog::request(REQUEST_TOUCH, false, $server->getListenUrl(),
+                                $server->getId(), $server->getMountpointId());
 		    }
 		}
 		catch (NoSuchSIDAPIException $e)
@@ -344,61 +317,57 @@
 			        throw new APIException("Not enough arguments.");
 		        }
 		    }
-		
+		    
 		    // SID
 		    $sid = preg_replace('/[^a-f0-9\-]/', '', strtolower($_REQUEST['sid']));
-		
-		    // MySQL Connection
-		    $db = DirXiphOrgDBC::getInstance();
-		
-		    // Remove the data
+		    
+		    // Find the server
 		    $server = Server::retrieveBySID($sid);
 		    if (!($server instanceOf Server))
 		    {
 		        throw new NoSuchSIDAPIException();
 		    }
-		    $query = 'SELECT s.`id`, s.`mountpoint_id`, m.`media_type_id` FROM `server` AS s INNER JOIN `mountpoint` AS m ON s.`mountpoint_id` = m.`id` WHERE s.`sid` = "%s";';
-		    $query = sprintf($query, mysql_real_escape_string($sid));
-		    try
+	        
+		    // Remove the data
+		    $mp_id = $server->getMountpointId();
+		    $server_id = $server->getId();
+		    $listen_url = $server->getListenUrl();
+	        $res = $server->remove();
+	        APILog::serverRemoved($res, $server_id, $mp_id, $listen_url);
+		    if ($res)
 		    {
-			    $res = $db->selectQuery($query);
-			    $server_id = $res->current('id');
-			    $mp_id = $res->current('mountpoint_id');
-			    $media_type = $res->current('media_type_id');
-			
-			    // Remove server
-			    $query = 'DELETE FROM `server` WHERE `id` = %d;';
-			    $query = sprintf($query, $server_id);
-			    $res = $db->singleQuery($query);
-			
-			    if ($res)
-			    {
-				    // Decrement the servers keys in memcache
-				    $memcache->decrement(ENVIRONMENT.'_servers_total');
-				    $memcache->decrement(ENVIRONMENT.'_servers_'.intval($media_type));
-				
-				    // Return success
-				    header("YPResponse: 1");
-				    header("YPMessage: Deleted server info.");
-				    
-                    // Log stuff
-                    APILog::request(REQUEST_REMOVE, true, $server->getListenUrl(),
-                                    $server->getId(), $server->getMountpointId());
-			    }
-			    else
-			    {
-				    // Return failure
-				    header("YPResponse: 0");
-				    header("YPMessage: Error occured while processing your request.");
-				    
-                    // Log stuff
-                    APILog::request(REQUEST_REMOVE, false, $server->getListenUrl(),
-                                    $server->getId(), $server->getMountpointId());
-			    }
+		        $mountpoint = Mountpoint::retrieveByPk($mp_id);
+		        if (!$mountpoint->hasLinkedServers())
+		        {
+		            $res = $mountpoint->remove();
+		            $mountpoint->decrementCounter(Mountpoint::COUNTER_TOTAL);
+		            $mountpoint->decrementCounter(Mountpoint::COUNTER_MEDIA_TYPE);
+		            
+		            // Log stuff
+		            APILog::mountpointRemoved($res, $mp_id, $listen_url);
+		        }
+	        }
+		    
+		    // Output final status
+		    if ($res)
+		    {
+			    // Return success
+			    header("YPResponse: 1");
+			    header("YPMessage: Deleted server info.");
+			    
+                // Log stuff
+                APILog::request(REQUEST_REMOVE, true, $server->getListenUrl(),
+                                $server->getId(), $server->getMountpointId());
 		    }
-		    catch (SQLNoResultException $e)
+		    else
 		    {
-			    throw new NoSuchSIDAPIException();
+			    // Return failure
+			    header("YPResponse: 0");
+			    header("YPMessage: Error occured while processing your request.");
+			    
+                // Log stuff
+                APILog::request(REQUEST_REMOVE, false, $server->getListenUrl(),
+                                $server->getId(), $server->getMountpointId());
 		    }
 		}
 		catch (NoSuchSIDAPIException $e)
@@ -410,8 +379,20 @@
             // Log stuff
             APILog::request(REQUEST_REMOVE, false, $listen_url,
                             $server_id !== false ? $server_id : null,
-                            $mountpoint_id !== false ? $mountpoint_id : null);
+                            $mp_id !== false ? $mp_id : null);
 		}
+	    catch (APIException $e)
+	    {
+		    // Return failure
+		    header("YPResponse: 0");
+		    header("YPMessage: Touch impossible. Reason: ".$e->getMessage());
+		    header("SID: -1");
+		    
+            // Log stuff
+            APILog::request(REQUEST_REMOVE, false, $listen_url,
+                            $server_id !== false ? $server_id : null,
+                            $mp_id !== false ? $mp_id : null);
+	    }
 		
 		break;
 }

Modified: branches/dir.xiph.org/cronjobs/prune_mountpoints.php
===================================================================
--- branches/dir.xiph.org/cronjobs/prune_mountpoints.php	2008-04-11 11:23:07 UTC (rev 14709)
+++ branches/dir.xiph.org/cronjobs/prune_mountpoints.php	2008-04-11 18:25:21 UTC (rev 14710)
@@ -10,9 +10,7 @@
 $memcache = DirXiphOrgMCC::getInstance();
 
 // Old stuff that "timeouted"
-$db->noReturnQuery('DELETE FROM `server` WHERE `last_touched_at` <= DATE_SUB(NOW(), INTERVAL 30 MINUTE);');
-$nb = $db->affected_rows;
-$memcache->decrement(ENVIRONMENT.'_servers', $nb);
+$db->noReturnQuery('DELETE FROM `server` WHERE `last_touched_at` <= DATE_SUB(NOW(), INTERVAL 10 MINUTE);');
 
 // Useless mountpoint
 try

Modified: branches/dir.xiph.org/inc/class.mountpoint.php
===================================================================
--- branches/dir.xiph.org/inc/class.mountpoint.php	2008-04-11 11:23:07 UTC (rev 14709)
+++ branches/dir.xiph.org/inc/class.mountpoint.php	2008-04-11 18:25:21 UTC (rev 14710)
@@ -2,8 +2,8 @@
 
 class Mountpoint
 {
-    protected $mountpoint_id = null;
-    protected $table_name = 'mountpoint';
+    protected $mountpoint_id = 0;
+    protected static $table_name = 'mountpoint';
     protected $cache_expiration = 60;
     public $loaded = false;
     
@@ -19,6 +19,9 @@
     protected $samplerate;
     protected $cluster_password;
     
+    const COUNTER_TOTAL = 'total';
+    const COUNTER_MEDIA_TYPE = 'media_type';
+    
     public function __construct($mountpoint_id, $force_reload = false, $no_load = false)
     {
         if (!is_numeric($mountpoint_id) || $mountpoint_id < 0)
@@ -70,6 +73,115 @@
     }
     
     /**
+     * Looks for a similar mountpoint in the db.
+     * 
+     * @return bool
+     */
+    public static function findSimilar($stream_name, $media_type, $bitrate)
+    {
+        // MySQL Connection
+		$db = DirXiphOrgDBC::getInstance();
+		
+		try
+		{
+		    $query = 'SELECT `id` FROM `%s` WHERE `stream_name` = "%s" AND `media_type_id` = %d AND `bitrate` = %d;';
+		    $query = sprintf($query, self::$table_name,
+		                     mysql_real_escape_string($stream_name),
+		                     $media_type, mysql_real_escape_string($bitrate));
+            
+		    // The mountpoint exists, only a different server.
+		    $res = $db->singleQuery($query);
+		    $mp_id = $res->current('id');
+		    $mp = Mountpoint::retrieveByPk($mp_id);
+		    
+		    return $mp;
+	    }
+	    catch (SQLNoResultException $e)
+	    {
+		    // The mountpoint doesn't exist yet in our database (it's OK)
+		    return false;
+	    }
+    }
+    
+    /**
+     * Checks if the mountpoint still has servers attached in the db.
+     * 
+     * @return bool
+     */
+    public function hasLinkedServers()
+    {
+        $data = Server::retrieveByMountpointId($this->mountpoint_id, false);
+        
+        return ($data !== false && $data !== array());
+    }
+    
+    /**
+     * Deletes the server from both the database and the cache.
+     * 
+     * @return bool
+     */
+    public function remove()
+    {
+        $res0 = $this->removeFromDb();
+        $res1 = $this->removeFromCache();
+        
+        return $res0 && $res1;
+    }
+    
+    /**
+     * Increments a counter by one.
+     * 
+     * @return bool
+     */
+    public function incrementCounter($counter)
+    {
+        // Memcache connection
+        $cache = DirXiphOrgMCC::getInstance();
+        
+	    // Decrement the servers keys in memcache
+	    if ($counter == self::COUNTER_MEDIA_TYPE)
+	    {
+	        $counter = intval($this->media_type_id);
+	    }
+	    $key = sprintf("%s_mountpoints_%s", ENVIRONMENT, $counter);
+	    if (!$cache->increment($key))
+	    {
+	        if (!$cache->set($key, 1))
+	        {
+	            return false;
+	        }
+	        
+	        return true;
+	    }
+	    
+	    return true;
+    }
+    
+    /**
+     * Decrements a counter by one.
+     * 
+     * @return bool
+     */
+    public function decrementCounter($counter)
+    {
+        // Memcache connection
+        $cache = DirXiphOrgMCC::getInstance();
+        
+	    // Decrement the servers keys in memcache
+	    if ($counter == self::COUNTER_MEDIA_TYPE)
+	    {
+	        $counter = intval($this->media_type_id);
+	    }
+	    $key = sprintf("%s_mountpoints_%s", ENVIRONMENT, $counter);
+	    if (!$cache->decrement($key))
+	    {
+	        return false;
+	    }
+	    
+	    return true;
+    }
+    
+    /**
      * Saves the mountpoint into the database.
      * 
      * @return integer
@@ -80,10 +192,23 @@
 		$db = DirXiphOrgDBC::getInstance();
 		
 		// Query
-        $query = 'INSERT INTO `%1$s` (`stream_name`, `description`, `url`, `listeners`, `current_song`, `media_type_id`, `bitrate`, `channels`, `samplerate`, `cluster_password`) '
-			    .'VALUES ("%2$s", %3$s, %4$s, %5$d, %6$s, %7$d, "%8$s", %9$s, %10$s, %11$s) '
-			    .'ON DUPLICATE KEY UPDATE `stream_name` = "%2$s", `description` = %3$s, `url` = %4$s, `listeners` = %5$d, `current_song` = %6$s, `media_type_id` = %7$d, `bitrate` = "%8$s", `channels` = %9$s, `samplerate` = %10$s, `cluster_password` = %11$s;';
-	    $query = sprintf($query, $this->table_name,
+		if ($this->mountpoint_id == 0)
+		{
+            $query = 'INSERT INTO `%1$s` (`stream_name`, `description`, `url`, '
+                    .'`listeners`, `current_song`, `media_type_id`, `bitrate`, '
+                    .'`channels`, `samplerate`, `cluster_password`) '
+    			    .'VALUES ("%2$s", %3$s, %4$s, %5$d, %6$s, %7$d, "%8$s", '
+    			    .'%9$s, %10$s, %11$s);';
+	    }
+	    else
+	    {
+		    $query = 'UPDATE `%1$s` SET `stream_name` = "%2$s", '
+		            .'`description` = %3$s, `url` = %4$s, `listeners` = %5$d, '
+		            .'`current_song` = %6$s, `media_type_id` = %7$d, '
+		            .'`bitrate` = "%8$s", `channels` = %9$s, '
+		            .'`samplerate` = %10$s, `cluster_password` = %11$s;';
+        }
+	    $query = sprintf($query, self::$table_name,
 	                             mysql_real_escape_string($this->stream_name),
 							     ($this->description != null) ? '"'.mysql_real_escape_string($this->description).'"' : 'NULL',
 							     ($this->url != null) ? '"'.mysql_real_escape_string($this->url).'"' : 'NULL',
@@ -94,11 +219,19 @@
 							     ($this->channels != null) ? intval($this->channels) : 'NULL',
 							     ($this->samplerate != null) ? intval($this->samplerate) : 'NULL',
 							     ($this->cluster_password != null) ? '"'.mysql_real_escape_string($this->cluster_password).'"' : 'NULL');
-	    $mp_id = $db->insertQuery($query);
-	    if ($mp_id !== false && $this->mountpoint_id == 0)
+							     
+	    if ($this->mountpoint_id == 0)
 	    {
-	        $this->mountpoint_id = $mp_id;
+	        $mp_id = $db->insertQuery($query);
+	        if ($mp_id !== false)
+	        {
+	            $this->mountpoint_id = $mp_id;
+	        }
 	    }
+	    else
+	    {
+	        $mp_id = $db->noReturnQuery($query);
+	    }
 	    
 	    return $mp_id;
     }
@@ -117,7 +250,7 @@
         try
         {
             $query = "SELECT * FROM `%s` WHERE `id` = %d;";
-            $query = sprintf($query, $this->table_name, $this->mountpoint_id);
+            $query = sprintf($query, self::$table_name, $this->mountpoint_id);
             $m = $db->singleQuery($query);
             
             $this->loadFromArray($m->array_data[0]);
@@ -131,6 +264,31 @@
     }
     
     /**
+     * Remove the data from the database.
+     * 
+     * @return boolean
+     */
+    protected function removeFromDb()
+    {
+        // MySQL Connection
+		$db = DirXiphOrgDBC::getInstance();
+		
+		// Mountpoint removal query
+        $query = 'DELETE FROM `%s` WHERE `id` = %d;';
+	    $query = sprintf($query, self::$table_name,
+	                             $this->mountpoint_id);
+	    $res = $db->noReturnQuery($query);
+	    
+	    if ($res)
+	    {
+		    // Tag removal
+		    Tag::deleteMountpointTags($this->mountpoint_id);
+	    }
+	    
+	    return (bool) $res;
+    }
+    
+    /**
      * Saves the data into the cache.
      * 
      * @return boolean
@@ -165,6 +323,20 @@
     }
     
     /**
+     * Remove the data from the cache.
+     * 
+     * @return boolean.
+     */
+    protected function removeFromCache()
+    {
+        // Memcache connection
+        $cache = DirXiphOrgMCC::getInstance();
+        
+        $a = $cache->delete($this->getCacheKey());
+        return ($a === true);
+    }
+    
+    /**
      * Builds a cache key for this mountpoint.
      * 
      * @return string

Modified: branches/dir.xiph.org/inc/class.server.php
===================================================================
--- branches/dir.xiph.org/inc/class.server.php	2008-04-11 11:23:07 UTC (rev 14709)
+++ branches/dir.xiph.org/inc/class.server.php	2008-04-11 18:25:21 UTC (rev 14710)
@@ -2,7 +2,7 @@
 
 class Server
 {
-    protected $server_id;
+    protected $server_id = 0;
     protected static $table_name = 'server';
     protected $cache_expiration = 60;
     public $loaded = false;
@@ -14,6 +14,7 @@
     protected $listeners;
     protected $last_touched_at;
     protected $last_touched_from;
+    protected $checked;
     
     public function __construct($server_id, $force_reload = false, $no_load = false)
     {
@@ -76,7 +77,7 @@
 		
 		try
 		{
-		    $sql = "SELECT `id` FROM %s WHERE `sid` = '%s';";
+		    $sql = "SELECT `id` FROM `%s` WHERE `sid` = '%s';";
 		    $sql = sprintf($sql, self::$table_name, mysql_real_escape_string($sid));
 		    $res = $db->singleQuery($sql);
 	    }
@@ -89,6 +90,84 @@
     }
     
     /**
+     * Retrieves the server from the db.
+     * 
+     * @return Server or false if an error occured.
+     */
+    public static function retrieveByListenUrl($url)
+    {
+        // MySQL Connection
+		$db = DirXiphOrgDBC::getInstance();
+		
+		try
+		{
+		    $sql = "SELECT `id` FROM `%s` WHERE `listen_url` = '%s';";
+		    $sql = sprintf($sql, self::$table_name, mysql_real_escape_string($url));
+		    $res = $db->singleQuery($sql);
+	    }
+	    catch (SQLNoResultException $e)
+		{
+		    return false;
+		}
+		
+		return self::retrieveByPk(intval($res->current('id')));
+    }
+    
+    /**
+     * Retrieves servers by mountpoint_id.
+     * 
+     * @param int $mp_id
+     * @param bool $load_servers If set to true, will return only a list of IDs.
+     * @return array
+     */
+    public static function retrieveByMountpointId($mp_id, $load_servers = true)
+    {
+        // MySQL Connection
+		$db = DirXiphOrgDBC::getInstance();
+		
+		try
+		{
+		    $sql = "SELECT `id` FROM `%s` WHERE `mountpoint_id` = %d;";
+		    $sql = sprintf($sql, self::$table_name, $mp_id);
+		    $res = $db->selectQuery($sql);
+	    }
+	    catch (SQLNoResultException $e)
+		{
+		    return false;
+		}
+		
+		$data = array();
+		while (!$res->endOf())
+		{
+		    if ($load_servers)
+		    {
+    		    $data[] = self::retrieveByPk(intval($res->current('id')));
+		    }
+		    else
+		    {
+		        $data[] = intval($res->current('id'));
+		    }
+		    
+		    $res->next();
+		}
+		
+		return $data;
+    }
+    
+    /**
+     * Deletes the server from both the database and the cache.
+     * 
+     * @return bool
+     */
+    public function remove()
+    {
+        $res0 = $this->removeFromDb();
+        $res1 = $this->removeFromCache();
+        
+        return $res0 && $res1;
+    }
+    
+    /**
      * Saves the server into the database.
      * 
      * @return integer
@@ -99,9 +178,23 @@
 		$db = DirXiphOrgDBC::getInstance();
 		
 		// Query
-        $query = 'INSERT INTO `%1$s` (`mountpoint_id`, `sid`, `current_song`, `listen_url`, `listeners`, `last_touched_at`, `last_touched_from`) '
-			    .'VALUES (%2$d, "%3$s", %4$s, "%5$s", %6$d, %7$s, INET_ATON("%8$s")) '
-			    .'ON DUPLICATE KEY UPDATE `mountpoint_id` = %2$d, `sid` = "%3$s", `current_song` = %4$s, `listen_url` = "%5$s", `listeners` = %6$d, `last_touched_at` = %7$s, `last_touched_from` = INET_ATON("%8$s");';
+		$query = '';
+		if ($this->server_id == 0)
+		{
+            $query = 'INSERT INTO `%1$s` (`mountpoint_id`, `sid`, '
+                    .'`current_song`, `listen_url`, `listeners`, '
+                    .'`last_touched_at`, `last_touched_from`, `checked`) '
+	    		    .'VALUES (%2$d, "%3$s", %4$s, "%5$s", %6$d, %7$s, '
+	    		    .'INET_ATON("%8$s"), %9$d);';
+	    }
+	    else
+	    {
+    		$query = 'UPDATE `%1$s` SET `mountpoint_id` = %2$d, `sid` = "%3$s", '
+    		        .'`current_song` = %4$s, `listen_url` = "%5$s", '
+    		        .'`listeners` = %6$d, `last_touched_at` = %7$s, '
+    		        .'`last_touched_from` = INET_ATON("%8$s"), '
+    		        .'`checked` = %9$d;';
+        }
 	    $query = sprintf($query, self::$table_name,
 	                             $this->mountpoint_id,
 							     mysql_real_escape_string($this->sid),
@@ -109,9 +202,22 @@
 							     mysql_real_escape_string($this->listen_url),
 							     ($this->listeners != null) ? $this->listeners : 0,
 							     ($this->last_touched_at != null) ? '"'.mysql_real_escape_string($this->last_touched_at).'"' : 'NOW()',
-							     mysql_real_escape_string($this->last_touched_from));
-	    $server_id = $db->insertQuery($query);
+							     mysql_real_escape_string($this->last_touched_from),
+							     ($this->checked != null) ? $this->checked : 0);
 	    
+		if ($this->server_id == 0)
+		{
+	        $server_id = $db->insertQuery($query);
+	        if ($server_id !== false)
+	        {
+	            $this->server_id = $server_id;
+	        }
+        }
+        else
+        {
+            $server_id = $db->noReturnQuery($query);
+        }
+	    
 	    return $server_id;
     }
     
@@ -128,7 +234,7 @@
 		// Query
 		try
 		{
-            $query = "SELECT `mountpoint_id`, `sid`, `current_song`, `listen_url`, `listeners`, `last_touched_at`, INET_NTOA(`last_touched_from`) AS `last_touched_from` FROM `%s` WHERE `id` = %d;";
+            $query = "SELECT `mountpoint_id`, `sid`, `current_song`, `listen_url`, `listeners`, `last_touched_at`, INET_NTOA(`last_touched_from`) AS `last_touched_from`, `checked` FROM `%s` WHERE `id` = %d;";
             $query = sprintf($query, self::$table_name, $this->server_id);
             $m = $db->singleQuery($query);
             
@@ -143,6 +249,25 @@
     }
     
     /**
+     * Remove the data from the database.
+     * 
+     * @return boolean
+     */
+    protected function removeFromDb()
+    {
+        // MySQL Connection
+		$db = DirXiphOrgDBC::getInstance();
+		
+		// Query
+        $query = 'DELETE FROM `%s` WHERE `id` = %d;';
+	    $query = sprintf($query, self::$table_name,
+	                             $this->server_id);
+	    $res = $db->noReturnQuery($query);
+	    
+	    return (bool) $res;
+    }
+    
+    /**
      * Saves the data into the cache.
      * 
      * @return boolean
@@ -177,6 +302,20 @@
     }
     
     /**
+     * Remove the data from the cache.
+     * 
+     * @return boolean.
+     */
+    protected function removeFromCache()
+    {
+        // Memcache connection
+        $cache = DirXiphOrgMCC::getInstance();
+        
+        $a = $cache->delete($this->getCacheKey());
+        return ($a === true);
+    }
+    
+    /**
      * Builds a cache key for this mountpoint.
      * 
      * @return string
@@ -215,6 +354,7 @@
         $this->listeners = intval($a['listeners']);
         $this->last_touched_at = $a['last_touched_at'];
         $this->last_touched_from = $a['last_touched_from'];
+        $this->checked = $a['checked'];
         
         $this->loaded = true;
         
@@ -237,6 +377,7 @@
         $a['listeners'] = intval($this->listeners);
         $a['last_touched_at'] = $this->last_touched_at;
         $a['last_touched_from'] = $this->last_touched_from;
+        $a['checked'] = $this->checked;
         
         return $a;
     }
@@ -320,6 +461,27 @@
     {
         return $this->last_touched_from;
     }
+    
+    public function setChecked($c)
+    {
+        $this->checked = intval($c);
+    }
+    
+    /**
+     * @return int
+     */
+    public function getChecked()
+    {
+        return $this->checked;
+    }
+    
+    /**
+     * @return bool
+     */
+    public function isChecked()
+    {
+        return (bool) $this->checked;
+    }
 }
 
 ?>

Modified: branches/dir.xiph.org/inc/class.tag.php
===================================================================
--- branches/dir.xiph.org/inc/class.tag.php	2008-04-11 11:23:07 UTC (rev 14709)
+++ branches/dir.xiph.org/inc/class.tag.php	2008-04-11 18:25:21 UTC (rev 14710)
@@ -118,6 +118,26 @@
 	        }
 		}
     }
+    
+    /**
+     * Delete the mountpoint-to-tags associations for a given mountpoint (plus
+     * decrement the tag cloud).
+     */
+    public static function deleteMountpointTags($mountpoint_id)
+    {
+        // MySQL Connection
+	    $db = DirXiphOrgDBC::getInstance();
+	    
+	    $sql = 'UPDATE `tag_cloud` SET `tag_usage` = `tag_usage` - 1 WHERE `tag_id` IN (SELECT `tag_id` FROM `mountpoints_tags` WHERE `mountpoint_id` = %d);';
+	    $sql = sprintf($sql, intval($mountpoint_id));
+	    $res0 = $db->noReturnQuery($sql);
+	    
+	    $sql = "DELETE FROM `mountpoints_tags` WHERE `mountpoint_id` = %d;";
+	    $sql = sprintf($sql, intval($mountpoint_id));
+	    $res1 = $db->noReturnQuery($sql);
+	    
+	    return $res0 && $res1;
+    }
 }
 
 ?>

Modified: branches/dir.xiph.org/inc/lib.apilog.php
===================================================================
--- branches/dir.xiph.org/inc/lib.apilog.php	2008-04-11 11:23:07 UTC (rev 14709)
+++ branches/dir.xiph.org/inc/lib.apilog.php	2008-04-11 18:25:21 UTC (rev 14710)
@@ -14,18 +14,22 @@
                              $listen_url !== null ? sprintf('%u', crc32($listen_url)) : 0,
                              $server_id, $mountpoint_id);
         $db->noReturnQuery($sql);
-        
-/*        mail_error('annie.dupont1137 at gmail.com', 'log-api',
-                   $result, __FILE__, 0);*/
     }
     
     public static function serverAdded($ok, $server_id, $mountpoint_id,
                                        $listen_url)
     {
-        self::log($ok ?'Server added' : 'Server add failed',
+        self::log($ok ? 'Server added' : 'Server add failed',
                   $listen_url, $server_id, $mountpoint_id);
     }
     
+    public static function serverRemoved($ok, $server_id, $mountpoint_id,
+                                         $listen_url)
+    {
+        self::log($ok ? 'Server removed' : 'Server removal failed',
+                  $listen_url, $server_id, $mountpoint_id);
+    }
+    
     public static function mountpointAdded($ok, $mountpoint_id,
                                            $listen_url = null)
     {
@@ -33,6 +37,13 @@
                   $listen_url, null, $mountpoint_id);
     }
     
+    public static function mountpointRemoved($ok, $mountpoint_id,
+                                             $listen_url = null)
+    {
+        self::log($ok ? 'Mountpoint removed' : 'Mountpoint removal failed',
+                  $listen_url, null, $mountpoint_id);
+    }
+    
     public static function request($req_type, $ok, $listen_url = null,
                                    $server_id = null, $mountpoint_id = null)
     {



More information about the commits mailing list