<?php

	lt_include( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
	lt_include( PLOG_CLASS_PATH."class/config/config.class.php" );
	lt_include( PLOG_CLASS_PATH."plugins/ads/class/dao/adblocks.class.php" );	
	
	class PluginAds extends PluginBase
	{
		function PluginAds( $source )
		{
			$this->PluginBase( $source );
			
			$this->id = "ads";
			$this->author = "The Lifetype team";
			$this->version = "20070302";
			
			// trap this even that is particularly interesting for us...
			$this->registerNotification( EVENT_PROCESS_BLOG_TEMPLATE_OUTPUT );
			
			// register one menu entry and one action
			if( $this->getSource() == "admin" ) {
				// menu entries
				$this->addMenuEntry( "/menu/adminSettings", "Ads", "", "", Array( "manage_ad_blocks"), Array(), true );				
				$this->addMenuEntry( "/menu/adminSettings/Ads", "configureAds", "?op=configureAds", "", Array( "manage_ad_blocks" ), Array(), true );
				$this->addMenuEntry( "/menu/adminSettings/Ads", "editAdBlocks", "?op=editAdBlocks", "", Array( "manage_ad_blocks" ), Array(), true );
				$this->addMenuEntry( "/menu/adminSettings/Ads", "newAdBlock", "?op=newAdBlock", "", Array( "manage_ad_blocks" ), Array(), true );				
				
				// admin actions
				$this->registerAdminAction( "configureAds", "PluginAdsConfigureAction" );
				$this->registerAdminAction( "updateAdsSettings", "PluginAdsUpdateSettingsAction" );	
				$this->registerAdminAction( "editAdBlocks", "AdminAdBlocksAction" );					
				$this->registerAdminAction( "editAdBlock", "AdminEditAdBlockAction" );									
				$this->registerAdminAction( "updateAdBlock", "AdminUpdateAdBlockAction" );													
				$this->registerAdminAction( "newAdBlock", "AdminNewAdBlockAction" );									
				$this->registerAdminAction( "addAdBlock", "AdminAddAdBlockAction" );
				$this->registerAdminAction( "deleteAdBlock", "AdminDeleteAdBlocksAction" );
				$this->registerAdminAction( "deleteAdBlocks", "AdminDeleteAdBlocksAction" );
			}
		}
		
		function register()
		{
			// schema for the adblocks table
			$adBlocksSchema = "
		      id I(10) NOTNULL AUTOINCREMENT PRIMARY,
		 	  block_name C(125) NOT NULL DEFAULT '',
		      block_position I(5) NOTNULL DEFAULT 1,
		      block_code TEXT NOTNULL,
			  block_mode I(2) NOTNULL DEFAULT 1,
			  block_blogs TEXT NOTNULL
		    ";
		
			// create the table if it does not exist yet
			$dbPrefix = Db::getPrefix();
			$tableName = $dbPrefix."ad_blocks";

			// create the data dictionary and create the table if necessary
			$db =& Db::getDb();
            $dict = NewPDbDataDictionary( $db );
            $sqlArray = $dict->ChangeTableSQL( $tableName, $adBlocksSchema );
            $result = $dict->ExecuteSQLArray( $sqlArray );
			
			if( $result == 0 )
				throw( new Exception( "Error creating the database table!" ));
				
			// register our permissions
			// add our new permission if it doesn't exist yet
			lt_include( PLOG_CLASS_PATH."class/dao/permissions.class.php" );
			$perms = new Permissions();
			if( !$perms->getPermissionByName( "manage_ad_blocks" )) {
				$perm = new Permission( "manage_ad_blocks", "manage_ad_blocks_desc" );
				$perm->setAdminOnlyPermission( true );
				$perms->addPermission( $perm );
			}			
		}
		
		/**
		 * whether the current blog should be shown ads or not, depending on the block
		 * settings
		 *
		 * @param block and AdBlock object
		 * @param blog
		 */
		function blogShowAds( $block, $blog )
		{
			// get the mode
			$mode = $block->getMode();
			
			$show = true;
			
			//print("processing block: ".$block->getName()."<br/>");
			
			// based on the mode, check whether the blog needs ads
			if( $mode == PLUGIN_ADS_BLOGS_SHOW_ALL ) {
				// ads for everyone!
				$show = true;
			}
			elseif( $mode == PLUGIN_ADS_BLOGS_INCLUDE_LIST ) {
				// load the list of blogs and see if this one is in the list
				$blogList = $block->getBlogs();
				$show = (is_integer(array_search( $blog->getId(), $blogList )));
			}
			elseif( $mode == PLUGIN_ADS_BLOGS_EXCLUDE_LIST ) {
				// load the list of blogs and see if this one is *not* in the list
				$blogList = $block->getBlogs();
				$show = (array_search( $blog->getId(), $blogList ) === FALSE );
			}
			
			return( $show );
		}

		/**
		 * Please implement this method with your custom logic to determine where to show the ad
		 *
		 * @param content A string containing the current version of the content
		 * @param block An AdBlock object containing information about the current block
		 * @return
		 */		
		function customAdPosition( $content, $block )
		{
			return( $content );
		}
		
		/**
		 * <description>
		 *
		 * @param
		 * @return
		 */
		function process( $eventType, $params )
		{
			if( $eventType != EVENT_PROCESS_BLOG_TEMPLATE_OUTPUT ) {
				// forget about it
				return( true );
			}
			
			// check if the plugin is enabled and quit if not
			$config =& Config::getConfig();
			if( !$config->getValue( "plugin_ads_enabled" ))
				return( true );
				
			// get all the ad blocks
			$blocks = new AdBlocks();
			$allBlocks = $blocks->getAdBlocks();
			
			foreach( $allBlocks as $block ) {
				// check if the block in the loop blog affects the current blog
				if( $this->blogShowAds( $block, $this->blogInfo )) {
					
					//print("block = ".$block->getName()." - showing ad!<br/>" );
					
					// otherwise get the content and process them
					$content = $params['content'];
			
					$adBlocks = new AdBlocks();

					// get the configured ad code
					$code = $block->getCode();
					$pos = $block->getPosition();
		
					// put the ad in place
					if( $pos == PLUGIN_ADS_POSITION_TOP ) {
						$content = str_replace( "<body>", "<body>$code", $content );
					}
					elseif( $pos == PLUGIN_ADS_POSITION_BOTTOM ) {
						$content = str_replace( "</body>", "$code</body>", $content );				
					}
					else {
						$name = strtolower($block->getName());
						$customBlockClassPath = PLOG_CLASS_PATH."plugins/ads/customblocks/{$name}.class.php";
						if( !File::isReadable( $customBlockClassPath )) {
							throw( new Exception( "Cannot load class for custom block $name: $customBlockClassPath" ));
							die();
						}
						lt_include( $customBlockClassPath );
						$class = new $name();
						$content = $class->process( $content, $block, $this->blogInfo, $params );
					}
			
					$params['content'] = $content;
				}
			}
			
			return( true );
		}
	}
?>