<?php

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

    
    /*
     * This plugin generates a CategoryCloud for a specific Blog
     */
    class PluginCategoryCloud extends PluginBase
    {
        
        var $pluginEnabled;
        var $cacheFolder;
        
            /*
             * Constructor
             */
        function PluginCategoryCloud($source = "") {
            
            $this->PluginBase($source);
            
            $this->id        = "categorycloud";
            $this->author    = "Mariano Draghi (cHagHi)";
            $this->desc      = "This plugin offers a CategoryCloud for a specific Blog";
            
            $this->version   = "20070511";
            $this->locales   = Array( "en_UK", "es_ES" );
            
            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( "categorycloud", "PluginCategoryCloudConfigAction" );
            $this->registerAdminAction( "updateCategoryCloudConfig", "PluginCategoryCloudUpdateConfigAction" );
            $menu =& Menu::getMenu();
            if( !$menu->entryExists( "/menu/controlCenter/manageAppearancePlugins" ))                       
                $this->addMenuEntry( "/menu/controlCenter", "manageAppearancePlugins", "", "", true, false );           
            $this->addMenuEntry( "/menu/controlCenter/manageAppearancePlugins", "CategoryCloud", "?op=categorycloud", "" );
        }
        
        function register()
        {
            $blogSettings = $this->blogInfo->getSettings();
            $this->pluginEnabled = $blogSettings->getValue( "plugin_categorycloud_enabled" );
            if(!$this->isEnabled())
                return;

            $config =& Config::getConfig();
            $this->cacheFolder = $config->getValue('temp_folder');
            $this->cacheFolder = $this->cacheFolder.'/categorycloud/'.$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;
            }

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

            return true;
        }
        


	/*
	* Return cloud of the blog categories
	*/
	function createCloud(){
        lt_include( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );

		$blogId = $this->blogInfo->getId();
        $blogSettings = $this->blogInfo->getSettings();
        
        if(!$this->isEnabled())
            return false;

   		$maxSize = $blogSettings->getValue( "plugin_categorycloud_max_size" );
		$maxWeight = $blogSettings->getValue( "plugin_categorycloud_max_weight" );

		$minSize = $blogSettings->getValue( "plugin_categorycloud_min_size" );
		$minWeight = $blogSettings->getValue( "plugin_categorycloud_min_weight" );	
		
        $categories = Array();
        $urls = Array();
        $rg = $this->blogInfo->getBlogRequestGenerator();
        $articlecategories = new ArticleCategories();
        $categoryobjects = $articlecategories->getBlogCategories( $blogId );

        if (!$categoryobjects || (count($categoryobjects) == 0))
            return false;

        foreach ($categoryobjects as $category) {
            $categories[$category->getName()] = $category->getNumPublishedArticles();
            $urls[$category->getName()] = $rg->categoryLink( $category );
        }

		// First sort the array by value, in reverse order
		arsort($categories);
		
        // get the highest and lowest occurrences
        $maxValue = current($categories);
        $minValue = end($categories);

		// Sort the keys alphabetically.
		ksort( $categories );
		
		// 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( $categories 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;
            
			$Cloud .= "<a rel=\"nofollow\" href=\"{$urls[$k]}\" style=\"font-size: {$size}em; font-weight: {$weight}; line-height: 90%\" title=\"$k\">$k</a>\n";
		}
	
        $saveFile = $this->cacheFolder."/categorycloud";  
	    
	    $fh = fopen( $saveFile, "w");
	    if ($fh)
	    {
	       fwrite($fh, $Cloud);
	       fclose($fh);
           File::chMod($saveFile, 0644);
	    }
		
    }
	
    /*
	* Return cloud for blog categories
	*/
    function getCategoryCloud(){

	    $Cloud = '';
	    
        if ($this->isEnabled())
        {
            $saveFile = $this->cacheFolder."/categorycloud";  
            
    
            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" );
        
        return( Array(
                    Array( "name" => "plugin_categorycloud_enabled", "type" => "boolean" ),
                    Array( "name" => "plugin_categorycloud_min_size",
                           "validator" => new FloatValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_categorycloud_max_size",
                           "validator" => new FloatValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_categorycloud_min_weight",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    Array( "name" => "plugin_categorycloud_max_weight",
                           "validator" => new IntegerValidator(), "type" => "integer", "allowEmpty" => true ),
                    ));
    }
	
}
        
        
?>
