<?php

include_once( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
include_once( PLOG_CLASS_PATH."class/plugin/pluginmanager.class.php" );
include_once( PLOG_CLASS_PATH."class/dao/articles.class.php" );
    
    /**
     * Plugin that offers features to returns the top read posts object of current blog
     */
class PluginRecommended extends PluginBase
{

    var $prefix;
    var $pluginEnabled;
    var $recommendedPosts;  
    
    function PluginRecommended(){
        $this->PluginBase();
        
        $this->id = "recommended";
        $this->author = "Jon Daley";
        $this->desc = "This plugin offers a list of recommended articles, selected by the blog owner";  
        $this->prefix = Db::getPrefix();
        
        $this->locales = Array( "en_UK" );
        $this->recommendedPosts = Array();
        
        $this->init(); 
    }

    function init(){
        include_once( PLOG_CLASS_PATH."class/template/menu/menu.class.php" );
        $this->registerAdminAction( "recommended", "PluginRecommendedConfigAction" );
        $this->registerAdminAction( "updateRecommendedConfig", 
                                    "PluginRecommendedUpdateConfigAction" );
        
        $menu =& Menu::getMenu();
        if( !$menu->entryExists( "/menu/controlCenter/manageTopPlugins" ))						
            $this->addMenuEntry( "/menu/controlCenter", "manageTopPlugins", "", "", true, false);
        $this->addMenuEntry( "/menu/controlCenter/manageTopPlugins", "Recommended", "?op=recommended", "" );            
    }
    
    function register(){
        $blogSettings = $this->blogInfo->getSettings();
        $this->pluginEnabled = $blogSettings->getValue( "plugin_recommended_enabled" );
        $this->recommendedPosts = $blogSettings->getValue( "plugin_recommended_posts" );
    }
	    
    function isEnabled(){
        return $this->pluginEnabled;
    }
 
        /**
         * Returns the posts object of current blog
         */
    function getPosts(){
        if(!$this->recommendedPosts)
            return Array();
        
        $articles = new Articles();
        $blogId = $this->blogInfo->getId();
        $query = "SELECT * FROM ".$this->prefix."articles";
        $query .= " WHERE blog_id = ".$blogId." AND status = 1";
        $count = 0;
        foreach($this->recommendedPosts as $id){
            $count++;
            if($count == 1){
                $query .= " AND id = " . $id;
            }
            else{
                $query .= " OR id = " . $id;
            }
        }
        $query .= " ORDER BY num_reads DESC";                
        
        $db =& Db::getDb();
        $result = $db->Execute( $query ); 
        
        if( !$result ) 
            return false; 
        
        $recommended = Array();
        while( $row = $result->FetchRow()) { 
            $article = $articles->mapRow( $row );
            array_push( $recommended, $article); 
        } 
        
        return $recommended; 
    }
}
?>