<?php

include_once( 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(){
	
		$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();
		include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
		$this->db =& Db::getDb();
		$this->id = "tagcloud";
		
	    $this->locales = Array("en_UK");
	    
	                
        $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 );
        

    
        $this->registerAdminAction( "tagcloud", "PluginTagCloudConfigAction" );
        $this->registerAdminAction( "updateTagCloudConfig", "PluginTagCloudUpdateConfigAction" );
        include_once( PLOG_CLASS_PATH."class/template/menu/menu.class.php" );
        $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()
    {
        $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 );
        }
        
       $blogSettings = $this->blogInfo->getSettings();
       $this->pluginEnabled = $blogSettings->getValue( "plugin_tagcloud_enabled" );

    }
    

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

        /**
         * process the events that we have registered
         *
         * @see PluginBase::process
         * @see PluginManager
         */
        function process( $eventType, $params )
        {
            // make sure we're processing the right event!
            if( $eventType != EVENT_POST_POST_ADD &&
                $eventType != EVENT_POST_POST_UPDATE &&
                $eventType != EVENT_POST_POST_DELETE )
            {
                return true;
            }
            
            // Load all of the settings for this blog
            $this->register();
            
            // make sure that the plugin is enabled
			if( !$this->isEnabled())
            {
                return true;
            }
                        
            // Update the Blogtime png
            $this->createCloud();

            return true;
        }
        


	/*
	* Return cloud of the latest articles
	*/
	function createCloud(){

		$this->_prefix = Db::getPrefix();
		$blogId = $this->blogInfo->getId();
	

		$blogSettings = $this->blogInfo->getSettings();
        $pluginEnabled = $blogSettings->getValue( "plugin_tagcloud_enabled" );
        
        if (!$pluginEnabled) {
            return;
        }

        $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 " . $this->_prefix . 
		    "articles a, " . $this->_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
		$Cloud = '';
		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;
            
            $rg = $this->blogInfo->getBlogRequestGenerator();
            $baseUrl = $rg->getBaseUrl();
			$Cloud .= "<a rel=\"nofollow\" href=\"{$baseUrl}?searchTerms=$k&op=Search&blogId={$blogId}\" style=\"font-size: {$size}em; font-weight: {$weight}; line-height: 90%\" title=\"$k\">$k</a>\n";
		}
	
        $saveFile = $this->cacheFolder."/tagcloud";  
	    
	    $fh = fopen( $saveFile, "w");
	    if ($fh)
	    {
	       fwrite($fh, $Cloud);
	       fclose($fh);
           File::chMod($saveFile, 0644);
	    }
		
    }
    
    	/*
	* Return cloud of the latest articles
	*/
	function getTagCloud(){

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