<?php

    lt_include( PLOG_CLASS_PATH."class/action/blogaction.class.php" );
    lt_include( PLOG_CLASS_PATH."class/view/plugintemplatedview.class.php" );
    lt_include( PLOG_CLASS_PATH."class/data/validator/stringvalidator.class.php" );
    lt_include( PLOG_CLASS_PATH."class/data/validator/arrayvalidator.class.php" );
    lt_include( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
	lt_include( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
	lt_include( PLOG_CLASS_PATH."class/dao/customfields/customfields.class.php" );
	lt_include( PLOG_CLASS_PATH."class/dao/customfields/customfieldsvalues.class.php" );	
	lt_include( PLOG_CLASS_PATH."class/dao/articles.class.php" );
	lt_include( PLOG_CLASS_PATH."class/dao/permissions.class.php" );
	lt_include( PLOG_CLASS_PATH."class/dao/userpermissions.class.php" );
	lt_include( PLOG_CLASS_PATH."class/mail/emailservice.class.php" );
    
    /**
     * Checks an incoming submission and adds it to the database if all is correct
     */
    class AddSubmissionAction extends BlogAction
    {
        var $_userName;
        var $_userEmailAddress;
        var $_topic;
        var $_text;
        var $_categoryIds;
    
        function ShowSubmissionFormAction( $actionInfo, $request )
        {
            $this->BlogAction( $actionInfo, $request );
        }
        
        function validate()
        {
            $errors = false;
            $val1 = new StringValidator();
        
            // these two are optional
            $userName = $this->_request->getValue( "userName" );
            if($userName){
                if( !$val1->validate( $userName )) {
                    $errors["submissionUserName"] = true;
                    $message["submissionUserName"] = $this->_locale->tr("error_incorrect_user");
                }
                else{
                    $this->_userName = $userName;
                }
            }
            $userEmailAddress = $this->_request->getValue( "userEmailAddress" );
            if($userEmailAddress){
                if( !$val1->validate( $userEmailAddress )) {
                    $errors["submissionUserEmailAddress"] = true;
                    $message["submissionUserEmailAddress"] = $this->_locale->tr("error_incorrect_email_address");
                }
                else{
                    $this->_userEmailAddress = $userEmailAddress;
                }
            }
                
            // these ones are mandatory, of course...
            $this->_topic = "";
            $topic = $this->_request->getValue( "submissionTopic" );
            if( !$val1->validate( $topic )) {
                $errors["submissionTopic"] = true;
                $message["submissionTopic"] = $this->_locale->tr("error_submission_no_topic");
            }
            else{
                $this->_topic = $topic;
            }
                
            
            $this->_text = "";
            $text = $this->_request->getValue( "submissionText" );
            $val2 = new StringValidator(true);
            if( !$val2->validate( $text )) {
                $errors["submissionText"] = true;
                $message["submissionText"] = $this->_locale->tr("error_submission_no_text");
            }
            else{
                    // is this too much?  Maybe just remove javascript?
//                $this->_text = Textfilter::filterHtml($text);
                $this->_text = Textfilter::filterJavaScript($text);
            }
            
            $this->_categoryIds = "";
            $categoryIds = $this->_request->getValue( "submissionCategory" );
            $val3 = new ArrayValidator(new IntegerValidator());
            if( !$val3->validate( $categoryIds )) {
                $errors["submissionCategory"] = true;
                $message["submissionCategory"] = $this->_locale->tr("error_incorrect_category_id");
            }
            else{
                $this->_categoryIds = $categoryIds;
            }
            
            if( $errors ) {
                $this->_view = new PluginTemplatedView( $this->_blogInfo, "submissions", "submitform", SMARTY_VIEW_CACHE_DISABLED );
                $this->_view->setValue( "userName", $this->_userName );
                $this->_view->setValue( "userEmailAddress", $this->_userEmailAddress );
                $this->_view->setValue( "submissionTopic", $this->_topic );
                $this->_view->setValue( "submissionText", $this->_text );
                $this->_view->setValue( "submissionCategories", $this->_categoryIds );
                $this->_view->setValue( "message", $message );
                $this->_view->setValue( "errors", $errors );
                $this->setCommonData();
                
                return false;
            }
            
            return true;
        }
        
        function perform()
        {
			// add the post to the database, with our new status
			$articles = new Articles();
            $postText = Textfilter::xhtmlize($this->_text);
            $article  = new Article( $this->_topic, 
			                         $postText,
			                         $this->_categoryIds,
                                     $this->_blogInfo->getOwner(), 
									 $this->_blogInfo->getId(), 
									 POST_STATUS_EXTERNAL_SUBMISSION, 
									 0 );
            $article->setDateObject( new Timestamp());
            $article->setCommentsEnabled( true );
			
			// add the custom fields with the information about the submitter
			$customFields = new CustomFields();
			$customFieldValues = new CustomFieldsValues();
			$submittedBy = $customFields->getCustomFieldByName( $this->_blogInfo->getId(), "submittedBy" );
			$submittedByValue = new CustomFieldValue( $submittedBy->getId(), $this->_userName, "", -1, "", -1, $this->_blogInfo->getId(), -1 );
			$submitterAddress = $customFields->getCustomFieldByName( $this->_blogInfo->getId(), "submitterAddress" );
			$submitterAddressValue = new CustomFieldValue( $submitterAddress->getId(), $this->_userEmailAddress, "", -1, "", -1, $this->_blogInfo->getId(), -1 );
			$article->setFields( Array( $submittedByValue, $submitterAddressValue ));
			
			// add the article to the db, finally
			if( $articles->addArticle( $article )) {
			    
			    // notify registred blog authors if notifications are enabled
			    $blogSettings = $this->_blogInfo->getSettings();
			    if ($blogSettings->getValue( "plugin_submissions_notifications_enabled" ) === true) {
			        $this->notifyNewSubmission();
				}
				$this->_view = new PluginTemplatedView( $this->_blogInfo, "submissions", "accepted" );
			}
			else {
				$this->_view = new ErrorView( $this->_blogInfo );
				$this->_view->setValue( "message", "Error adding article to the database" );
			}
			
			$this->setCommonData();			
			
            return true;
        }
        
		/**
		 * Sends a notification message to the blog owner to inform him
		 * that a new article has just been submitted
		 *
		 * @private
		 */
		function notifyNewSubmission()
		{

			$user =& $this->_blogInfo->getOwnerInfo();
		
			$config =& Config::getConfig();
            $message = new EmailMessage();
            $message->setFrom( $config->getValue( "post_notification_source_address" ));
            $message->setSubject( $this->_locale->tr("plugin_submissions_notification_subject" ));
            $message->setCharset( $this->_locale->getCharset());
            $message->setBody( $this->_locale->tr("plugin_submissions_notifications_body" ) );
			
	        $service = new EmailService();

            $message->setTo( $user->getEmail());
	        $service->sendMessage( $message );

		}
        
    }
?>
