<?php

	lt_include( PLOG_CLASS_PATH."class/security/pipelinefilter.class.php" );

	/**
	 * This is a filter for the pipe line that performs exactly the same action as
	 * the code in the PluginCloseComments::process() method. The problem is that when 
	 * caching is enabled, no events are thrown and the only place where we can catch
	 * this kind of events is in here, as filters are always executed regardless
	 * of the template caching settings
	 */
	class CloseComments extends PipelineFilter
	{
    	function CloseComments( $pipelineRequest )
        {
        	$this->PipelineFilter( $pipelineRequest );
        }

        function filter()
        {
        	// get some info
            $request  = $this->_pipelineRequest->getHttpRequest();
            $blogInfo = $this->_pipelineRequest->getBlogInfo();

			$settings = $blogInfo->getSettings();
			if( !$settings->getValue( "plugin_closecomments_enabled", false )) {
				// do nothing if the plugin is disabled
				return( new PipelineResult());
			}

            if( $request->getValue( "op" ) != "AddComment" && $request->getValue( "op" ) != "ViewArticle" ) {
            	$result = new PipelineResult();
                return $result;
            }

			// otherwise let's proceed
			lt_include( PLOG_CLASS_PATH."class/dao/articles.class.php" );			
			$articles = new Articles();
			if( isset( $_REQUEST["articleId"] )) {
				$artId = $request->getValue( "articleId" );
				$article = $articles->getBlogArticle( $artId, $blogInfo->getId());
			}
			else {
				$artName = $request->getValue( "articleName" );
				$article = $articles->getBlogArticleByTitle( $artName, $blogInfo->getId());
			}
			
			if( !$article ) {
				// quit if there was no article to load
            	$result = new PipelineResult();
                return $result;
			}

			$postDate = $article->getDateObject();
			$settings = $blogInfo->getSettings();
			$period = $settings->getValue( "plugin_closecomments_period", DEFAULT_CLOSECOMMENTS_PERIOD );
			$postDate->addSeconds( $period * 24 * 3600 );
			$now = new Timestamp();
			
			//print("date+period = ".$postDate->getTimestamp()." - now = ".$now->getTimestamp()."<br/>");
			
			if( $postDate->getTimestamp() < $now->getTimestamp()) {
				//print( "Closing comments!" );
				lt_include( PLOG_CLASS_PATH."class/template/cachecontrol.class.php" );
				if( $article->getCommentsEnabled()) {
					$article->setCommentsEnabled( false );
					$articles = new Articles();
					$articles->updateArticle( $article );				
					CacheControl::resetBlogCache( $blogInfo->getId());
				}
			}
			
        	$result = new PipelineResult();
            return $result;			
		}
	}
?>