<?php

    include_once( PLOG_CLASS_PATH."class/security/pipelinefilter.class.php" );
    include_once( PLOG_CLASS_PATH."plugins/secret/class/dao/secretitems.class.php" );
    include_once( PLOG_CLASS_PATH."class/template/templateservice.class.php" );
    include_once( PLOG_CLASS_PATH."class/net/requestgenerator.class.php" );
    include_once( PLOG_CLASS_PATH."class/net/http/httpvars.class.php" );
    include_once( PLOG_CLASS_PATH."class/dao/articles.class.php" );
    include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
    include_once( PLOG_CLASS_PATH."class/dao/users.class.php" );
    include_once( PLOG_CLASS_PATH.'class/template/template.class.php' );

    class SecretItemFilter extends PipelineFilter 
    {

        function SecretItemFilter( $pipelineRequest )
        {
            $this->PipelineFilter( $pipelineRequest );
        }

        function filter()
        {
            // get some info
            $blogInfo = $this->_pipelineRequest->getBlogInfo();
            $blogSettings = $blogInfo->getSettings();
            $request  = $this->_pipelineRequest->getHttpRequest();
            $session  = HttpVars::getSession();

                // is the plugin enabled? If not, we can quit right away
            if( !$blogSettings->getValue( "plugin_secret_enabled" )) {
                return new PipelineResult();
            }
            
            
            // if we're not loading an article, we can ignore this 
            if( $request->getValue( "op" ) != "ViewArticle" )
                return new PipelineResult();

            // if this is already rejected, there is no reason to do anything here
            if ( $this->_pipelineRequest->getRejectedState() )
                return new PipelineResult();
                
            // get the article id from the request, since if it is available, then we know
            // that we have to ask for the password before we can let users watch it
            $articleId = $request->getValue( "articleId" );

            // If we use custom url mode, the article id is not available, we need to use
            // - articleName
            // - userId
            // - categoryId
            // - date
            // and $articles->getBlogArticleByTitle() to find the value
            if( $articleId == "" ) {
                $articleName = $request->getValue( "articleName" );
                $categoryId = $request->getValue( "postCategoryId", -1 );
                $categoryName = $request->getValue( "postCategoryName" );
                $userId = $request->getValue( "userId", -1 );
                $userName = $request->getValue( "userName" );
                $date = $request->getValue( "Date", -1 );

                // If userName available, use it to find userId
                if( $userName ) {
                    $users =& new Users();
                    $user = $users->getUserInfoFromUsername( $userName );
                    if( !$user ) {
                        return new PipelineResult();
                    }
                    // if there was a user, use his/her id
                    $userId = $user->getId();
                }
                // If categoryName available, use it to find categoryId
                if( $categoryName ) {
                    $categories =& new ArticleCategories();
                    $category = $categories->getCategoryByName($categoryName,
                                                               $blogInfo->getId());
                    if( !$category ) {
                        return new PipelineResult();
                    }
                    // if there was a user, use his/her id
                    $categoryId = $category->getId();
                }
        
                // fetch the article
                // the article identifier can be either its internal id number
                // or its mangled topic
                $articles =& new Articles();
                $article  = $articles->getBlogArticleByTitle( $articleName, $blogInfo->getId(),
                                                              false, $date, $categoryId,
                                                              $userId, POST_STATUS_PUBLISHED );

                if( $article ) {
                    $articleId = $article->getId();
                } else {
                    return new PipelineResult();
                }
            }
            
            // check if the article should be protected or not
            $secretItems = new SecretItems();

                // not protected, exit now
            if(!$secretItems->articleIsSecret($articleId))
                return new PipelineResult();
                
                // now check if the password does not already exist in the session
            $itemPassword = $request->getValue( "itemPassword" );
            
                // do we already have this information in the session?
            $sessionKey = "article_".$articleId."_auth";
            if( isset( $session[ "$sessionKey"] )) {
                if( $session[ "$sessionKey" ] != "" ) {
                    
	                    // check if the information is correct
                    if( $secretItems->authenticateItemHash( $articleId,
                                                            $session[ "$sessionKey" ] ))
                    {
	                        // if all correct, go ahead!
                        $result = new PipelineResult( true );
                        return $result;
                    }
                }
            }
            
                // if not, check if we are authenticating now...
            if( $itemPassword != "" ) {
                    // authenticate using the given password
                if( !$secretItems->authenticateItem( $articleId, $itemPassword )) {
                    $result = new PipelineResult( false, 500, "Better luck next time!" );
                }
                else {
                        // if the user authenticated correctly, then put the
                        // information in the session
                    $session = HttpVars::getSession();
                    $session[ "$sessionKey" ] = md5( $itemPassword );
                    $result = new PipelineResult( true );
                    HttpVars::setSession( $session );
                }
            }
            else {
					// prepare the view we're going to show
                include_once( PLOG_CLASS_PATH."plugins/secret/class/view/secretpluginenterpasswordview.class.php" );					
                $view = new SecretPluginEnterPasswordView( $blogInfo );
                $view->setValue( "locale", $blogInfo->getLocale() );
                $view->setValue( "params", $request->getAsArray());
                $view->setValue( "articleId", $articleId );
                $view->setValue( "url", $blogInfo->getBlogRequestGenerator());
					// and give it to the pipeline for display
                $result =  new PipelineResult( false, 500, "" );
                $result->setView( $view );
            }
                
            return $result;
        }
    }
?>
