<?php

    /*
    Copyright 2006 Paul Westbrook (paul@westbrooks.org)
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    */

	lt_include( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );

	class PluginEctoCustom extends PluginBase
	{
		var $pluginEnabled;
		
		function PluginEctoCustom( $source = "" )
		{
			$this->PluginBase($source);

			$this->id      = "ectocustom";
			$this->desc    = "The Ecto Custom plugin inserts the ecto technotati tags into the custom field used by the technorati plugin.";
			$this->author  = "Paul Westbrook";
			$this->locales = Array( "en_UK" );
            $this->version = "20070302";

			if( $source == "admin" )
				$this->initAdmin();
			else
				$this->init();
		}

        function init()
        {
            // register the events we want
            $this->registerNotification( EVENT_PRE_POST_ADD );
            $this->registerNotification( EVENT_PRE_POST_UPDATE );
        }

		function initAdmin()
		{
		    $this->init();

            $this->registerAdminAction( "ectocustom", "PluginEctoCustomConfigAction" );
			$this->registerAdminAction( "updateEctoCustomConfig", "PluginEctoCustomUpdateConfigAction" );
			
			$menu =& Menu::getMenu();
			if( !$menu->entryExists( "/menu/controlCenter/manageIntegrationPlugins" ))						
				$this->addMenuEntry( "/menu/controlCenter", "manageIntegrationPlugins", "", "", true, false );			
            $this->addMenuEntry( "/menu/controlCenter/manageIntegrationPlugins", "ectocustom", "?op=ectocustom", "" );            
		}

		function register()
		{
		    $blogSettings = $this->blogInfo->getSettings();
			$this->pluginEnabled = $blogSettings->getValue( "plugin_ectocustom_enabled" );
		}

	    function isEnabled()
	    {
	        return $this->pluginEnabled;
	    }
	    
        /**
         * process the events that we have registered
         *
         * @see PluginBase::process
         * @see PluginManager
         */
        function process( $eventType, $params )
        {
            // make sure we're processing the right event!
            if( $eventType != EVENT_PRE_POST_ADD &&
                $eventType != EVENT_PRE_POST_UPDATE  )
            {
                return true;
            }
            
            // Load all of the settings for this blog
            $this->register();
            
            // make sure that the plugin is enabled
			if( !$this->isEnabled())
            {
                return true;
            }
            
            $article = $params["article"];
                        
            // Update the Blogtime png
            $params["article"] = $this->convertTagsToCustomFields($article);

            return true;
        }
        
        /**
         * strips the tags added by ecto, and adds them to the technorati custom field
         */
        function convertTagsToCustomFields( $post )
        {
            // Get the text of the post
            $text = $post->getText(false);
            
            
            // Are the tags in the post
            
            /**
             * The format is:
             <!-- technorati tags start --><p style="text-align:right;font-size:10px;">Technorati Tags: <a href="http://www.technorati.com/tag/Apple Mail" rel="tag">Apple Mail</a>, <a href="http://www.technorati.com/tag/IMAP IDLE" rel="tag">IMAP IDLE</a>, <a href="http://www.technorati.com/tag/Mac OS X" rel="tag">Mac OS X</a>, <a href="http://www.technorati.com/tag/Mail.app plugin" rel="tag">Mail.app plugin</a></p><!-- technorati tags end -->
            */
            
            $beginningTag = "<!-- technorati tags start -->";
            
            $pos = strpos($text, $beginningTag);
            if ( $pos === false )
            {
                // just return the original post
                return $post;
            }
            
            $endOfText = $pos;
            $posBeginTags = $pos + strlen($beginningTag);
            
            // Make sure the end tag is present
            $endTag = "<!-- technorati tags end -->";
            $pos = strpos($text, $endTag, $posBeginTags);
            if ( $pos === false )
            {
                // just return the original post
                return $post;
            }
            
            // Get the string with the tags
            $tagString = substr($text, $posBeginTags, $pos - $posBeginTags);
            
            // Get the text without the tags;
            $text = substr( $text, 0, $endOfText) . substr( $text, $pos + strlen($endTag));
            
            // This really should be done as a regular expression
            
            $customFieldValueText = "";
            //Break out the tags
            $tags = explode( "rel=\"tag\">", $tagString);
            // Skip over the first one
            array_shift($tags);
            foreach($tags as $tag)
            {
                $tagArray = explode( "</a>", $tag );
                
                if ($customFieldValueText != "")
                {
                    $customFieldValueText = $customFieldValueText . ",";
                }
                $customFieldValueText = $customFieldValueText . $tagArray[0];
            }

            lt_include( PLOG_CLASS_PATH."class/dao/customfields/customfields.class.php" );

            $customFields = new CustomFields();
			$blogFields = $customFields->getBlogCustomFields( $this->blogInfo->getId());

            $foundField = false;
            $fieldId = 0;
            foreach($blogFields as $blogField)
            {
               if ( $blogField->getName() == "technoratiTags" )
               {
                   $foundField = true;
                   $fieldId = $blogField->getId();
                   break;
               }
            }

            if( $foundField == false) {
                // The field doesn't exist, bail out
                return $post;
			}

            // Add the modified text back to the post
            $post->setText($text);
            lt_include( PLOG_CLASS_PATH."class/dao/customfields/customfieldvalue.class.php" );
            
            // Create a new CustomFieldValue
            $postCustomFields = $post->getCustomFields();
            
            $customFieldValue = new CustomFieldValue( $fieldId,
                                           $customFieldValueText,
                                           $post->getId(),
                                           $this->blogInfo->getId());
                                                       
            $postCustomFields["technoratiTags"] = $customFieldValue;
           
            $post->setFields( $postCustomFields );

            
            return $post;
        }
        
        function getPluginConfigurationKeys()
		{			
			return( Array(
				Array( "name" => "plugin_ectocustom_enabled", "type" => "boolean" ),
			));
		}

	}
?>