<?php

include_once( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );

    
    /*
     * This plugin generates a CategoryCloud for a specific Blog
     *
     * The plugin is based on TagCloud, by Ben Yacoub Hatem. In fact, most
     * of the admin interface and the main algorithm to build the cloud is
     * EXACTLY the same.
     */
     class PluginCategoryCloud extends PluginBase
     {
	
        var $pluginEnabled;
        var $cacheFolder;

	/*
	* Constructor
	*/
	function PluginCategoryCloud() {

		$this->PluginBase();
	
        $this->id        = "categorycloud";
        $this->author    = "Mariano Draghi (cHagHi)";
		$this->desc      = "This plugin offers a CategoryCloud for a specific Blog";

        $this->version   = '1.0';
		$this->locales   = Array( "en_UK", "es_ES" );

        $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( "categorycloud", "PluginCategoryCloudConfigAction" );
        $this->registerAdminAction( "updateCategoryCloudConfig", "PluginCategoryCloudUpdateConfigAction" );
        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", "CategoryCloud", "?op=categorycloud", "" );            
    }
    
    function register()
    {
        $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 );
        }
        
       $blogSettings = $this->blogInfo->getSettings();
       $this->pluginEnabled = $blogSettings->getValue( "plugin_categorycloud_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 CategoryCloud png
            $this->createCloud();

            return true;
        }
        


	/*
	* Return cloud of the blog categories
	*/
	function createCloud(){

		$blogId = $this->blogInfo->getId();

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

   		$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's categories
	*/
	function getCategoryCloud(){

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