<?php

    lt_include( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );

    
    /*
     * This plugin generate TagCloud for a specific Blog
     */
     class PluginTagCloud extends PluginBase
     {
	
        var $pluginEnabled;
        var $cacheFolder;
         
        /*
        * Constructor
        */
        function PluginTagCloud( $source = "" ){

            $this->author = "Ben Yacoub Hatem";
            $this->desc = "This plugin generate TagCloud for a specific Blog, usage
                    :<br/>
                    <b>{ \$tagcloud->getTagCloud()}</b><br/><br/>
                   getTagCloud return html of the Tag Cloud ready to use.<br/>
                   See Readme for example usage.";
                
            $this->PluginBase($source);
            lt_include( PLOG_CLASS_PATH."class/database/db.class.php" );
            $this->db =& Db::getDb();
            $this->id = "tagcloud";
            $this->version = "20070725";
            
            $this->locales = Array("en_UK");
                                
            if( $source == "admin" )
                $this->initAdmin();
            else
                $this->init();
        }
      
        function init()
        {
            // register the events we want
            $this->registerNotification( EVENT_POST_POST_ADD );
            $this->registerNotification( EVENT_POST_POST_UPDATE );
            $this->registerNotification( EVENT_POST_POST_DELETE );    
        }
    
      
        function initAdmin()
        {
            $this->init();
            
            if (defined( "EVENT_POST_ADMIN_PURGE_TEMP_FOLDER" )) {
                // register the events we want
                $this->registerNotification( EVENT_POST_ADMIN_PURGE_TEMP_FOLDER );
            }
                    
            $this->registerAdminAction( "tagcloud", "PluginTagCloudConfigAction" );
            $this->registerAdminAction( "updateTagCloudConfig", "PluginTagCloudUpdateConfigAction" );
            $menu =& Menu::getMenu();
            if( !$menu->entryExists( "/menu/controlCenter/manageAppearancePlugins" ))                       
                $this->addMenuEntry( "/menu/controlCenter", "manageAppearancePlugins", "", "", true, false );           
            $this->addMenuEntry( "/menu/controlCenter/manageAppearancePlugins", "TagCloud", "?op=tagcloud", "" );            
        }
        
        function register()
        {
            $blogSettings = $this->blogInfo->getSettings();
            $this->pluginEnabled = $blogSettings->getValue( "plugin_tagcloud_enabled" );
            if(!$this->isEnabled())
                return;
            
            $config =& Config::getConfig();
            $this->cacheFolder = $config->getValue('temp_folder');
            $this->cacheFolder = $this->cacheFolder.'/tagcloud/'.$this->blogInfo->getId();
            if( !File::exists( $this->cacheFolder )) {
                File::createDir( $this->cacheFolder, 0755 );
            }
        }
        

        function isEnabled()
        {
            return $this->pluginEnabled;
        }        

        /**
         * process the events that we have registered
         *
         * @see PluginBase::process
         * @see PluginManager
         */
        function process( $eventType, $params )
        {
            $validEvent = false;

            // Looking for EVENT_POST_POST_ADD, EVENT_POST_POST_UPDATE, EVENT_POST_POST_DELETE
            // or EVENT_POST_ADMIN_PURGE_TEMP_FOLDER (if defined)
            if ( $eventType == EVENT_POST_POST_ADD || 
                 $eventType == EVENT_POST_POST_UPDATE ||
                 $eventType == EVENT_POST_POST_DELETE ||
                (defined( "EVENT_POST_ADMIN_PURGE_TEMP_FOLDER" ) && $eventType == EVENT_POST_ADMIN_PURGE_TEMP_FOLDER) )
            {
                $validEvent = true;
            }

            // make sure we're processing the right event!
            if( $validEvent == false) 
            {
                return true;
            }
            
            // Load all of the settings for this blog
			$this->register();

            if(!$this->isEnabled())
            {
                return true;
            }
            
            // Update the Blogtime png
            $this->createCloud();

            return true;
        }
        


	/*
	* Return cloud of the latest articles
	*/
	function createCloud(){
		$prefix = Db::getPrefix();
		$blogId = $this->blogInfo->getId();
		$blogSettings = $this->blogInfo->getSettings();
        
        if(!$this->isEnabled())
            return false;

        $MaxArticles = $blogSettings->getValue( "plugin_tagcloud_max_articles" );
        $MaxKeywords = $blogSettings->getValue( "plugin_tagcloud_max_keywords" );
        
   		$maxSize = $blogSettings->getValue( "plugin_tagcloud_max_size" );
		$maxWeight = $blogSettings->getValue( "plugin_tagcloud_max_weight" );

		$minSize = $blogSettings->getValue( "plugin_tagcloud_min_size" );
		$minWeight = $blogSettings->getValue( "plugin_tagcloud_min_weight" );	
		$minWordLength = $blogSettings->getValue( "plugin_tagcloud_min_word_length" );	
		
		$bannedwords = $blogSettings->getValue( "plugin_tagcloud_banned_keywords" );
		$bannedwords = explode(",", strtolower($bannedwords));

		$MaxArticles = mysql_escape_string($MaxArticles);
	
		$query = "SELECT t.normalized_text,t.normalized_topic FROM " . $prefix . 
		    "articles a, " . $prefix."articles_text t" .
		    " WHERE a.id=t.article_id " .
		    " AND a.status=1 AND a.blog_id = " . $blogId . 
		    " ORDER BY a.date DESC LIMIT 0,$MaxArticles;";
	
		$result = $this->db->Execute($query);
        if(!$result || ($result->RecordCount() == 0))
		    return false;
	
		// get the articles content
		while ($row = $result->FetchRow()) {
			$data[] = $row['normalized_topic'].' '.$row['normalized_text'];
		}	
		$data = implode(' ',$data);
		
		// Split keywords
		$words = preg_split('/\s*[\s+\.|\?|,|(|)|\-+|\'|\"|!|=|;|&#0215;|\$|\/|:|{|}]\s*/i', strtolower($data));
		$acv = array_count_values( $words );

		// Remove unwanted keywords
		foreach($acv as $k=>$v) {
            $found = array_search($k,$bannedwords);
			if(($found === FALSE || $found === NULL) && (strlen($k) >= $minWordLength)) {
				if (isset($new_acv[$k])) 
					$new_acv[$k] += $v;
				else 
					$new_acv[$k] = $v;
			}
		}
		
		// First sort the array by value, in reverse order
		arsort($new_acv);
		
		// Now limit the array to $MaxKeywords
        $new_acv = array_slice($new_acv, 0, $MaxKeywords);

            // get the highest and lowest occurrences
        $maxValue = current($new_acv);
        $minValue = end($new_acv);

		// Sort the keys alphabetically.
		ksort( $new_acv );
		
		// Normalize the max value
		$maxValue = $maxValue - $minValue;
            // avoid a divide by zero if all of the words in our group
            // occur exactly the same number of times.
        if($maxValue == 0)
            $maxValue = 1;
		
		// Create the Cloud
        $saveFile = $this->cacheFolder."/tagcloud";  
	    $fh = fopen( $saveFile, "w");

	    if ($fh) {
            $rg = $this->blogInfo->getBlogRequestGenerator();
            $baseUrl = $rg->getBaseUrl();
            
            foreach( $new_acv as $k=>$v) {
                
                $value = $v - $minValue;
                
                $size = (($value *$maxSize)/$maxValue) + $minSize;
                $weight = (($value *$maxWeight)/$maxValue) + $minWeight;
                
                if ($size > $maxSize) $size = $maxSize;
                if ($weight > $maxWeight) $weight = $maxWeight;
                $weight = floor($weight / 100) * 100;
                
                $tag = "<a rel=\"nofollow\" href=\"{$baseUrl}?searchTerms=$k&amp;op=Search&amp;blogId={$blogId}\" style=\"font-size: {$size}em; font-weight: {$weight}; line-height: 90%\" title=\"$k\">$k</a>\n";
                fwrite($fh, $tag);
           }
	    
	       fclose($fh);
           File::chMod($saveFile, 0644);
	    }
		
    }
    
    	/*
	* Return cloud of the latest articles
	*/
    function getTagCloud(){

	    $Cloud = '';
	    
        if ($this->isEnabled())
        {
            $saveFile = $this->cacheFolder."/tagcloud";  
            
    
            if(File::isReadable($saveFile)){
                $fh = fopen( $saveFile, "r");
                if ($fh)
                {
                    $Cloud = fread($fh, filesize($saveFile));
                    fclose($fh);
                }
            }
        }

        return $Cloud;
    }

    function getPluginConfigurationKeys()
    {
        lt_include( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
        lt_include( PLOG_CLASS_PATH."class/data/validator/floatvalidator.class.php" );
        lt_include( PLOG_CLASS_PATH."class/data/validator/stringvalidator.class.php" );
        
        return( Array(
                    Array( "name" => "plugin_tagcloud_enabled", "type" => "boolean" ),
                    Array( "name" => "plugin_tagcloud_max_articles",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_max_keywords",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_min_size",
                           "validator" => new FloatValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_max_size",
                           "validator" => new FloatValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_min_weight",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_max_weight",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_min_word_length",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_tagcloud_banned_keywords",
                           "validator" => new StringValidator(), "type" => "string", "allowEmpty" => true ),
                    ));
    }

}
?>