<?php

/*
=============================================================
	Tag Module for pMachine ExpressionEngine
	- by Solspace
-------------------------------------------------------------
	http://www.solspace.com/
-------------------------------------------------------------
	Copyright (c) 2006 - 2009 Solspace.com
=============================================================
	THIS IS COPYRIGHTED SOFTWARE. PLEASE
	READ THE LICENSE AGREEMENT.
	http://www.solspace.com/software/
-------------------------------------------------------------
	This software is based upon and derived from
	pMachine ExpressionEngine software protected under
	copyright dated 2004 - 2005. Please see
	www.pmachine.com/expressionengine/license.html
-------------------------------------------------------------
	USE THIS SOFTWARE AT YOUR OWN RISK. SOLSPACE ASSUMES
	NO WARRANTY OR LIABILITY FOR THIS SOFTWARE AS DETAILED
	IN THE SOLSPACE LICENSE AGREEMENT.
=============================================================
	File:			mcp.tag.php
-------------------------------------------------------------
	Version:		1.1.2
-------------------------------------------------------------
	Compatibility:	EE 1.5.2
-------------------------------------------------------------
	Purpose:		Content tagging module
=============================================================
*/

if ( ! defined('EXT'))
{
    exit('Invalid file request');
}

// -------------------------------------------
//	Begin class
// -------------------------------------------

class Tag_CP
{
    var $version			= '1.1.2';
    var $old_version		= '';
    var $module_name		= 'Tag';
    var $site_name			= '';
    var $cp					= '';
    var $js_dir				= '';
    var $weblog				= 'weblog';
    var $Weblog				= 'Weblog';
    var $base				= '';
    var $tag_id				= '';
    var $entry_id			= '';
    var $pref_id			= '';
    var $parse				= 'linebreak';
    var $nav				= array();
    var $show_nav			= TRUE;
    var $need_upgrade		= FALSE;
    
    // -------------------------------------------
    //   Constructor
    // -------------------------------------------
    
    function Tag_CP( $switch = TRUE )
    {
        global $DB, $IN, $PREFS;
        
        $this->base			= BASE.AMP.'C=modules'.AMP.'M=tag'.AMP;
        
        $this->base_short	= 'C=modules'.AMP.'M=tag'.AMP;
    	
    	$this->site_name	= $PREFS->ini('site_name');
        
        $this->Weblog		= ucfirst( $PREFS->ini('weblog_nomenclature') );
        
        $this->weblog		= strtolower( $this->Weblog );
    	
		// ----------------------------------------
		//  Sometimes people forget to include a
		//	trailing backslash in their site prefs,
		//	so we correct it.
		// ----------------------------------------
    	
		$site				= ( substr( $PREFS->ini('site_url'), -1, 1 ) == "/" ) ? $PREFS->ini('site_url'): $PREFS->ini('site_url')."/";
		
		$this->cp			= $site.$PREFS->ini('system_folder')."/";

		// ----------------------------------------
		//  Check extension
		// ----------------------------------------
		
		if ( ! $this->handle_extension() ) return FALSE;

		// ----------------------------------------
		//  Get old version
		// ----------------------------------------
		
		$query	= $DB->query("SELECT module_version FROM exp_modules WHERE module_name = '".$this->module_name."' LIMIT 1");

		if ( $query->num_rows == 0 )
		{
			$this->old_version	= '0';
		}
		else
		{
			$this->old_version	= $query->row['module_version'];
		}

		// ----------------------------------------
		//  Functions
		// ----------------------------------------
        
        if ( $switch )
        {
            switch( $IN->GBL('P') )
            {
                case 'documentation'				:  $this->documentation();
                    break;
                case 'module_upgrade'				:  $this->module_upgrade();
                    break;
                case 'manage_tags'					:  $this->manage_tags();
                    break;
                case 'delete_tag_confirm'			:  $this->delete_tag_confirm();
                    break;
                case 'delete_tag'					:  $this->delete_tag();
                    break;
                case 'manage_bad_tags'				:  $this->manage_bad_tags();
                    break;
                case 'delete_bad_tag_confirm'		:  $this->delete_bad_tag_confirm();
                    break;
                case 'delete_bad_tag'				:  $this->delete_bad_tag();
                    break;
                case 'edit_bad_tag_form'			:  $this->edit_bad_tag_form();
                    break;
                case 'edit_bad_tag'					:  $this->edit_bad_tag();
                    break;
                case 'bad_tag'						:  $this->bad_tag();
                    break;
                case 'manage_prefs'					:  $this->manage_prefs();
                    break;
                case 'update_parse_pref'			:  $this->update_parse_pref();
                    break;
                case 'delete_pref_confirm'			:  $this->delete_pref_confirm();
                    break;
                case 'delete_pref'					:  $this->delete_pref();
                    break;
                case 'edit_pref_form'				:  $this->edit_pref_form();
                    break;
                case 'edit_pref'					:  $this->edit_pref();
                    break;
                default       						:  $this->home();
                    break;
            }
        }
    }
    
    // End constructor
    

	// -------------------------------------------
	//	Begin content wrapper
	// -------------------------------------------
    //	This is a helper function that builds the
    //	control panel output. Each function that
    //	generates a UI will call this function.

    function content_wrapper($title = '', $crumb = '', $content = '')
    {
        global $DSP, $IN, $LANG, $PREFS;
                        		
        $DSP->title		= $title;
        
        $DSP->crumb		= $DSP->anchor($this->base, $LANG->line('tag'));

		$DSP->crumb		.= $DSP->build_crumb($crumb);
		
		$js_dir			= $PREFS->ini('tag_module_js_directory');
		
		$DSP->body		.= "<script type=\"text/javascript\" src=\"".$js_dir."prototype.js\"></script>";
		
		$DSP->body		.= "<script type=\"text/javascript\" src=\"".$js_dir."tag.js\"></script>";
		
		$nav = $this->nav(
							array(
									'documentation'			=> array('P' => 'documentation'),
									'manage_tags'			=> array('P' => 'manage_tags'),
									'manage_bad_tags'		=> array('P' => 'manage_bad_tags'),
									'manage_prefs'			=> array('P' => 'manage_prefs'),
								)
						);

		if ($nav != '')
		{
			$DSP->body	.= $nav;
		}
		
		if ($IN->GBL('msg') == FALSE)
		{
			if ($this->show_nav == TRUE)
			{
				$DSP->body	.= $DSP->qdiv('', NBS);
			}
			
			$DSP->body	.= $DSP->qdiv('itemWrapper', $content);
		}
		else
		{
			$DSP->body	.= $content;
		}						
    }
    
    // End content wrapper
    
    
	// -------------------------------------------
	//	Navigation tabs
	// -------------------------------------------
	//	Takes an array as input and creates the
	//	navigation tabs from it. This functiion is
	//	called by the one above.

    function nav( $nav_array )
    {
        global $IN, $DSP, $LANG;
        
        if ( $this->show_nav == FALSE )
        {
        	return '';
        }
        
		// -------------------------------------------
		//	Build menus
		// -------------------------------------------
		//	Equalize the text length. We do this so
		//	that the tabs will all be the same length.
		
		$temp		= array();
		
		foreach ($nav_array as $k => $v)
		{
			$temp[$k]	= $LANG->line($k);
		}
		
		$temp		= $DSP->equalize_text($temp);

        $page		= $IN->GBL('P');
        
        $highlight	= array(
        					'documentation'					=> 'documentation',
        					'manage_tags'					=> 'manage_tags',
        					'delete_tag_confirm'			=> 'manage_tags',
        					'delete_tag'					=> 'manage_tags',
        					'manage_bad_tags'				=> 'manage_bad_tags',
        					'delete_bad_tag_confirm'		=> 'manage_bad_tags',
        					'delete_bad_tag'				=> 'manage_bad_tags',
        					'edit_bad_tag_form'				=> 'manage_bad_tags',
        					'edit_bad_tag'					=> 'manage_bad_tags',
        					'bad_tag'						=> 'manage_tags',
        					'manage_prefs'					=> 'manage_prefs',
        					'update_parse_pref'				=> 'manage_prefs',
        					'delete_pref_confirm'			=> 'manage_prefs',
        					'delete_pref'					=> 'manage_prefs',
        					'edit_pref_form'				=> 'manage_prefs',
        					'edit_pref'						=> 'manage_prefs',
							);
       

        if ( isset($highlight[$page]) )
        {
        	$page	= $highlight[$page];
        }
        
            
        $r		= <<<EOT
        
        <script type="text/javascript"> 
        <!--

		function styleswitch(link)
		{                 
			if (document.getElementById(link).className == 'altTabs')
			{
				document.getElementById(link).className = 'altTabsHover';
			}
		}
	
		function stylereset(link)
		{                 
			if (document.getElementById(link).className == 'altTabsHover')
			{
				document.getElementById(link).className = 'altTabs';
			}
		}
		
		-->
		</script>
		
		
EOT;
    
		$r		.= $DSP->table_open( array('width' => '100%') );

		$nav	= array();
		
		foreach ( $nav_array as $key => $val )
		{
			$url	= '';
		
			if ( is_array($val) )
			{
				$url	= $this->base;		
			
				foreach ( $val as $k => $v )
				{
					$url	.= $k.'='.$v;
				}					
			}

			$url	= ( $url == '' ) ? $val: $url;

			$div	= ( ( ( ! $page ) ? 'home': $page ) == $key ) ? 'altTabSelected': 'altTabs';
			$linko	= '<div class="'.$div.'" id="'.$key.'"  onClick="navjump(\''.$url.'\');" onmouseover="styleswitch(\''.$key.'\');" onmouseout="stylereset(\''.$key.'\');">'.$temp[$key].'</div>';
					
			$nav[]	= array( 'text' => $DSP->anchor( $url, $linko ) );
		}

		$r		.= $DSP->table_row( $nav );		
		$r		.= $DSP->table_close();

		return $r;          
    }
    // End nav


	// -------------------------------------------
	//	Upgrade check
	// -------------------------------------------
    //	We need to make sure that our version is
    //	current, if not, prompt upgrade.
	
	function upgrade_check()
	{
		global $DB, $DSP, $IN, $LANG;
		
		$r		= "";
		
		$link	= ' <a href="'.$this->base.'P=module_upgrade'.AMP.'msg=upgrade_successful">'.$LANG->line('upgrade_now').'</a>';
		
		$msg	= $DSP->qdiv(
							'itemWrapperTop',
							$DSP->qdiv(
										'successBox',
										$DSP->qdiv(
													'success',
													$LANG->line('upgrade_message').$link
													)
										)
							);		

		// -------------------------------------------
		//	Do we need to upgrade?
		// -------------------------------------------
		
		$query	= $DB->query("SELECT module_version FROM exp_modules WHERE module_name = '".$this->module_name."' LIMIT 1");

		if ( $query->row['module_version'] < $this->version )
		{
			$this->need_upgrade	= TRUE;
			$r = $msg;
		}
	
		return $r;
	}
	//	End upgrade check


	// -------------------------------------------
	//	Js directory check
	// -------------------------------------------
    //	We need to make sure that our JS files can
    //	be accessed.
	
	function js_dir_check()
	{
		global $DSP, $IN, $LANG, $PREFS;
		
		$r		= "";
		
		$link	= ' <a href="'.$this->base.'P=manage_prefs">'.$LANG->line('check_js_dir').'</a>';
		
		$msg	= $DSP->qdiv(
							'itemWrapperTop',
							$DSP->qdiv(
										'successBox',
										$DSP->qdiv(
													'success',
													$LANG->line('cannot_find_js').$link
													)
										)
							);		

		// -------------------------------------------
		//	Do we need to upgrade?
		// -------------------------------------------

		if ( ! $this->url_exists( $PREFS->ini('tag_module_js_directory').'prototype.js' ) AND ! $this->need_upgrade )
		{
			$r = $msg;
		}
	
		return $r;
	}
	//	End js directory check


	// -------------------------------------------
	//	Header and message handler
	// -------------------------------------------
    //	The content wrapper function above
    //	automatically positions the page heading
    //	on the top right-hand side, and any
    //	"success" messages on the left side.
    //	This function lets us override that
    //	behavior in case we want to show something
    //	else on the left side of the page.  We use
    //	this in two or three instances.
	
	function header_and_msg( $msg = '' )
	{
		global $IN, $DSP, $LANG;
		
		$r	= '';
		
		if ($msg == '' AND $IN->GBL('msg') == FALSE)
		{
			return '';
		}
        
		// -------------------------------------------
		//	Page header and message handler
		// -------------------------------------------
        
        if ( $msg != '' )
        {
			$r	.= $DSP->qdiv('successBox', $DSP->qdiv('success', $msg));
        }
	
		return $r;
	}
	//	End header and message handler
	
	
	// -------------------------------------------
	//	Spacer
	// -------------------------------------------
	
	function spacer ()
	{
		global $DSP;
		
		return $DSP->qdiv( '', NBS );
	}
	
	//	End spacer
	
	
	// -------------------------------------------
	//	Home
	// -------------------------------------------
	
    function home( $message = '' )
    {
    	global $DSP, $LANG;
    	
		// -------------------------------------------
		//  Start page
		// -------------------------------------------
                        
        $title	= $LANG->line('home');
	
		$crumb	= array(
						$title => ''
					  );
		
        $r		= $this->header_and_msg($message);
					  
		$r		.= $this->upgrade_check();
		
		$r		.= $this->js_dir_check();
					  
		$r		.= $this->stats();

		// -------------------------------------------
		//	Return the output
		// -------------------------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
    }
    
    //	End home
	
	
	// -------------------------------------------
	//	Documentation
	// -------------------------------------------
	
    function documentation( $message = '' )
    {
    	global $DSP, $LANG;
    	
        $r 		= $this->header_and_msg( $message );
    	
		$title	= $LANG->line('documentation');
	
		$crumb	= array(
						$title => ''
					  );
		
		$r		.= $LANG->line('no_documentation');

		// -------------------------------------------
		//	Return the output
		// -------------------------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
    }
    
    //	End documentation
    
    
	// -------------------------------------------
    //  Stats
	// -------------------------------------------
    
    function stats($message = '')
    {
    	global $DB, $DSP, $LANG;
    	
        $r		= '';
        
        $rows	= array();
					  
		// ------------------------------------
		//  Query
		// ------------------------------------
		
		$tags		= $DB->query( "SELECT COUNT(*) AS count FROM exp_tag_tags" );
		
		$t_entries	= $DB->query( "SELECT COUNT(*) AS count FROM exp_tag_entries GROUP BY entry_id" );

		$t_entries	= ( $t_entries->num_rows > 0 ) ? $t_entries->num_rows: 0;
		
		$entries	= $DB->query( "SELECT COUNT(*) AS count FROM exp_weblog_titles" );
		
		$p_entries	= ( $entries->row['count'] != 0 ) ? round( $t_entries / $entries->row['count'] * 100, 2): 0;
		
		$top5		= $DB->query( "SELECT t.tag_name, COUNT(t.tag_name) AS count FROM exp_tag_tags AS t LEFT JOIN exp_tag_entries AS e ON e.tag_id = t.tag_id GROUP BY e.tag_id ORDER BY count DESC LIMIT 5" );

		$ranked		= '';

		if ( $top5->num_rows > 0 )
		{
			foreach ( $top5->result as $row )
			{
				$ranked	.= $row['tag_name'].", ";
			}
			
			$ranked	= substr( $ranked, 0, -2 );
		}
		
		// ------------------------------------
		//  Start
		// ------------------------------------

		$r		.= $DSP->table_open(array('class' => 'tableBorder', 'width' => '100%'));
		
		$top[]	= array(
						'text'	=> $LANG->line('tags'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('total_entries_tagged'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('percent_entries_tagged'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('top_5'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '40%'
					);

		$r		.= $DSP->table_row( $top );
		
		// ------------------------------------
		//  Main stats
		// ------------------------------------
		
		unset($rows);

		$rows[]		= $tags->row['count'];

		$rows[]		= $t_entries;

		$rows[]		= $p_entries.NBS.'%';

		$rows[]		= $ranked;
		
		$r			.= $DSP->table_qrow( 'tableCellOne', $rows);

        $r			.=	$DSP->table_c();
        
        return $r;
    }
    
    //	End stats
    
    
	// -------------------------------------------
    //  Tags
	// -------------------------------------------
    
    function tags($message = '')
    {
    	global $DB, $DSP, $IN, $LANG, $LOC;
                
        $row_limit		= 50;
        $paginate		= '';
        $row_count		= 0;
        $r				= '';
        
        $bad			= array();
					  
		// ------------------------------------
		//  Bad tags query
		// ------------------------------------
		
		$badq	= $DB->query("SELECT tag_name FROM exp_tag_bad_tags");
		
		if ( $badq->num_rows > 0 )
		{
			foreach( $badq->result as $b )
			{
				$bad[]	= $b['tag_name'];
			}
		}
					  
		// ------------------------------------
		//  Query
		// ------------------------------------
		
		$c		= array();
		
		$cq		= $DB->query( "SELECT tag_id, COUNT(*) AS count FROM exp_tag_entries GROUP BY tag_id" );

		foreach( $cq->result as $row )
		{
			$c[$row['tag_id']]	= $row['count'];
		}
		
		$sql	= "SELECT t.*, m.screen_name FROM exp_tag_tags AS t LEFT JOIN exp_members AS m ON m.member_id = t.author_id ORDER BY t.tag_name ASC";
		
		$query	= $DB->query($sql);
		
		if ( $query->num_rows == 0 )
		{
			$r	.=	$DSP->qdiv('itemWrapper', $DSP->qdiv('highlight', $LANG->line('no_tags')));
				
			// -----------------------------
			//	Return the finalized output
			// ----------------------------- 
			
			return $r;
		}
		
		// ------------------------------------
		//  Paginate
		// ------------------------------------
    
		if ( $query->num_rows > $row_limit )
		{
			$row_count		= ( ! $IN->GBL('row')) ? 0 : $IN->GBL('row');
						
			$url			= $this->base.'P=manage_tags';
			
			$paginate		= $DSP->pager(
											$url,
											$query->num_rows, 
											$row_limit,
											$row_count,
											'row'
										);
			 
			$sql			.= " LIMIT ".$row_count.", ".$row_limit;
			
			$query			= $DB->query($sql);    
		}
    
        $r					.=	$DSP->toggle();
        
        $DSP->body_props	.= ' onload="magic_check()" ';
        
        $r					.= $DSP->magic_checkboxes();
        
        $form_url			= $this->base_short.'P=delete_tag_confirm';
        
        $r					.=	$DSP->form_open(array('action' => $form_url, 'name' => 'target', 'id' => 'target'));

		$r					.= $DSP->table_open(array('class' => 'tableBorder', 'width' => '100%'));
		
		$top[] = array(
						'text'	=> NBS,
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '3%'
					);
		
		$top[]	= array(
						'text'	=> $DSP->input_checkbox('toggleflag', '', '', "onclick=\"toggle(this);\"").NBS.NBS.$LANG->line('delete'),
						'class'	=> 'tableHeadingAlt',
						'width'	=> '10%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('tag'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '15%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('count'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '10%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('author'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '10%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('entry_date'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('edit_date'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('bad_tag'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '12%'
					);

		$r		.= $DSP->table_row( $top );
		
		$row_count++;
		
		$i = 0;
		
		foreach ( $query->result as $row )
		{
			unset($rows);
			
			$rows[]		= $row_count;
			
			$rows[]		= $DSP->input_checkbox('toggle[]', $row['tag_id'], '', "id='delete_box_".$row['tag_id']."'");
			
			$rows[]		= $row['tag_name'];

			$rows[]		= ( isset ( $c[$row['tag_id']] ) ) ? $c[$row['tag_id']]: '0';

			$rows[]		= $row['screen_name'];
			
			$rows[]		= $LOC->set_human_time( $row['entry_date'] );
			
			$rows[]		= ( $row['edit_date'] > 0 ) ? $LOC->set_human_time( $row['edit_date'] ): '';

			if ( in_array( $row['tag_name'], $bad ) )
			{
				$rows[]		= $LANG->line('bad_tag');
			}
			else
			{
				$rows[]		= $DSP->anchor( $this->base.'P=bad_tag'.AMP.'tag_name='.$row['tag_name'], $LANG->line('bad_tag'), 'title="'.$LANG->line('bad_tag_explained').'"' );
			}
			
			
			$r			 .= $DSP->table_qrow( ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo', $rows);
			$row_count++;
		}
		
		
		$foot[] = NBS;
		
		$foot[] = $DSP->input_checkbox('toggleflag', '', '', "onclick=\"toggle(this);\"").NBS.NBS.'<b>'.$LANG->line('delete').'</b>';

		$foot[] = NBS;

		$foot[] = NBS;

		$foot[] = NBS;

		$foot[] = NBS;

		$foot[] = NBS;

		$foot[] = NBS;
				
		$r		.= $DSP->table_qrow( ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo', $foot);

        $r		.=	$DSP->table_c(); 

    	if ($paginate != '')
    	{
    		$r .= $DSP->qdiv('itemWrapper', $paginate.BR.BR);
    	}
    	
		$r		.=	$DSP->qdiv('itemWrapperTop', $DSP->input_submit($LANG->line('delete')));             
        
        $r		.=	$DSP->form_close();
        
        return $r;
    }
    
    //	End tags
    
    
	// -------------------------------------------
    //  Manage Tags
	// -------------------------------------------
    
    function manage_tags($message = '')
    {
        global $DSP, $LANG;
    	
		// -------------------------------------------
		//  Start page
		// -------------------------------------------
                        
        $title	= $LANG->line('manage_tags');

		$crumb	= $LANG->line('manage_tags');
		
        $r		= $this->header_and_msg($message);

        $r		.= $DSP->qdiv('tableHeading', $LANG->line('manage_tags'));
        
		// -------------------------------------------
		//  Contents
		// -------------------------------------------
        
        $r		.= $this->stats();
        
        $r		.= $this->spacer();
        
        $r		.= $this->tags();
				
		// -------------------------------------------
		//	Return the finalized output
		// -------------------------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
	}
    // End manage tags
  
    
    // -------------------------------------------
    //   Delete Tag - Confirm
    // -------------------------------------------    

    function delete_tag_confirm()
    {
        global $IN, $DSP, $LANG;
        
        if ( ! $IN->GBL('toggle', 'POST'))
        { 
            return $this->manage_tags();
        }
        
        $title	= $LANG->line('tag_delete_confirm');
        
		$crumb 	= $DSP->anchor($this->base, $LANG->line('manage_tags'));

		$crumb	.= $DSP->crumb_item($LANG->line('tag_delete_confirm'));

        $r		= $DSP->form_open(array('action' => $this->base_short.'P=delete_tag'));
        
        $i		= 0;
        
        foreach ( $_POST as $key => $val )
        {        
            if ( strstr( $key, 'toggle' ) AND ! is_array( $val ) AND is_numeric( $val ) )
            {
                $r	.=	$DSP->input_hidden('delete[]', $val);
                
                $i++;
            }        
        }
        
		$r		.= $DSP->qdiv('alertHeading', $LANG->line('tag_delete_confirm'));
		
		$r		.= $DSP->div('box');
		
		if ( $i == 1 )
		{
			$replace[]	= $i; $replace[]	= 'tag';
		}
		else
		{
			$replace[]	= $i; $replace[]	= 'tags';
		}
		
		$search	= array( '%i%', '%tags%' );
		
		$r		.= $DSP->qdiv('defaultBold', str_replace( $search, $replace, $LANG->line('tag_delete_question') ) );
		
		$r		.= $DSP->qdiv('alert', BR.$LANG->line('action_can_not_be_undone'));
		
		$r		.= $DSP->qdiv('', BR.$DSP->input_submit($LANG->line('delete')));
		
		$r		.= $DSP->qdiv('alert',$DSP->div_c());
		
		$r		.= $DSP->div_c();
		
		$r		.= $DSP->form_close();
				
		// -----------------------------
		//	Return the finalized output
		// -----------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
    }
    // End delete tag confirm
  
    
    // -------------------------------------------
    //   Delete Tag
    // -------------------------------------------    

    function delete_tag()
    {
        global $DB, $DSP, $IN, $LANG, $SESS;
        
        $sql	= array();       
        
        if ( ! $IN->GBL('delete', 'POST'))
        {
            return $this->home();
        }

        $ids	= array();
                
        foreach ($_POST as $key => $val)
        {        
            if (strstr($key, 'delete') AND ! is_array($val) AND is_numeric($val))
            {
                $ids[] = "tag_id = '".$val."'";
            }        
        }
        
        $IDS			= implode(" OR ", $ids);
        
        $query			= $DB->query("SELECT tag_id FROM exp_tag_tags WHERE ".$IDS);
        
		// -------------------------------------------
		//	Delete tags
		// -------------------------------------------
		
		foreach ( $query->result as $row )
		{			
			$sql[]	= "DELETE FROM exp_tag_tags WHERE tag_id = '".$row['tag_id']."'";

			$sql[]	= "DELETE FROM exp_tag_entries WHERE tag_id = '".$row['tag_id']."'";
		}
		
		foreach ( $sql as $q )
		{
			$DB->query($q);
		}
    
        $message = ($query->num_rows == 1) ? str_replace( '%i%', $query->num_rows, $LANG->line('tag_deleted') ) : str_replace( '%i%', $query->num_rows, $LANG->line('tags_deleted') );

        return $this->manage_tags($message);
    }
    
    //	End delete tag
  
    
    // -------------------------------------------
    //   Bad Tag quick submit
    // -------------------------------------------    

    function bad_tag()
    {
        global $DB, $DSP, $IN, $LANG, $LOC, $SESS;
        
        $tag_name	= '';
				
		// -------------------------------------------
		//	Validate
		// -------------------------------------------
        
        if ( ! $tag_name = $IN->GBL('tag_name') )
        {
			return $DSP->error_message($LANG->line('tag_name_required'));
        }
        
		// -------------------------------------------
		//	Clean tag
		// -------------------------------------------
		
		$tag_name	= strtolower( $DB->escape_str( $tag_name ) );		
        
		// -------------------------------------------
		//	Check for duplicate
		// -------------------------------------------
		
		$query	= $DB->query("SELECT tag_name FROM exp_tag_bad_tags WHERE tag_name = '".$tag_name."'");

		if ( $query->num_rows > 0 )
		{
			return $DSP->error_message( str_replace( '%tag_name%', $tag_name, $LANG->line('bad_tag_exists') ) );
		}
				
		// -------------------------------------------
		//	Add
		// -------------------------------------------
		
		$DB->query( $DB->insert_string('exp_tag_bad_tags', array( 'tag_name' => $tag_name, 'author_id' => $SESS->userdata['member_id'], 'entry_date' => $LOC->now ) ) );

		$message	= str_replace( '%tag_name%', $IN->GBL('tag_name'), $LANG->line('bad_tag_added') );

        return $this->manage_tags($message);
    }
    
    //	End bad tag quick submit
    
    
	// -------------------------------------------
    //  Bad Tags
	// -------------------------------------------
    
    function bad_tags($message = '')
    {
    	global $DB, $DSP, $IN, $LANG, $LOC;
                
        $row_limit		= 50;
        $paginate		= '';
        $row_count		= 0;
        $r				= '';
					  
		// ------------------------------------
		//  Query
		// ------------------------------------
		
		$sql	= "SELECT t.*, m.screen_name FROM exp_tag_bad_tags AS t LEFT JOIN exp_members AS m ON m.member_id = t.author_id ORDER BY t.tag_name ASC";
		
		$query	= $DB->query($sql);
		
		if ( $query->num_rows == 0 )
		{
			$r	.=	$DSP->qdiv('tableCellOne', $DSP->qdiv('highlight', $LANG->line('no_bad_tags')));
				
			// -----------------------------
			//	Return the finalized output
			// ----------------------------- 
			
			return $r;
		}
		
		// ------------------------------------
		//  Paginate
		// ------------------------------------
    
		if ( $query->num_rows > $row_limit )
		{
			$row_count		= ( ! $IN->GBL('row')) ? 0 : $IN->GBL('row');
						
			$url			= $this->base.'P=manage_bad_tags';
			
			$paginate		= $DSP->pager(
											$url,
											$query->num_rows, 
											$row_limit,
											$row_count,
											'row'
										);
			 
			$sql			.= " LIMIT ".$row_count.", ".$row_limit;
			
			$query			= $DB->query($sql);    
		}
    
        $r					.=	$DSP->toggle();
        
        $DSP->body_props	.= ' onload="magic_check()" ';
        
        $r					.= $DSP->magic_checkboxes();
        
        $form_url			= $this->base_short.'P=delete_bad_tag_confirm';
        
        $r					.=	$DSP->form_open(array('action' => $form_url, 'name' => 'target', 'id' => 'target'));

		$r					.= $DSP->table_open(array('class' => 'tableBorder', 'width' => '100%'));
		
		$top[] = array(
						'text'	=> NBS,
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '3%'
					);
		
		$top[]	= array(
						'text'	=> $DSP->input_checkbox('toggleflag', '', '', "onclick=\"toggle(this);\"").NBS.NBS.$LANG->line('delete'),
						'class'	=> 'tableHeadingAlt',
						'width'	=> '10%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('tag'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('author'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '25%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('entry_date'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '42%'
					);

		$r		.= $DSP->table_row( $top );
		
		$row_count++;
		
		$i = 0;
		
		foreach ( $query->result as $row )
		{
			unset($rows);
			
			$rows[]		= $row_count;
			
			$rows[]		= $DSP->input_checkbox('toggle[]', $row['tag_id'], '', "id='delete_box_".$row['tag_id']."'");
			
			$rows[]		= $DSP->anchor( $this->base.'P=edit_bad_tag_form'.AMP.'tag_id='.$row['tag_id'], $row['tag_name'] );

			$rows[]		= $row['screen_name'];
			
			$rows[]		= $LOC->set_human_time( $row['entry_date'] );
			
			$r			 .= $DSP->table_qrow( ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo', $rows);
			$row_count++;
		}
		
		
		$foot[] = NBS;
		
		$foot[] = $DSP->input_checkbox('toggleflag', '', '', "onclick=\"toggle(this);\"").NBS.NBS.'<b>'.$LANG->line('delete').'</b>';

		$foot[] = NBS;

		$foot[] = NBS;

		$foot[] = NBS;
				
		$r		.= $DSP->table_qrow( ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo', $foot);

        $r		.=	$DSP->table_c(); 

    	if ($paginate != '')
    	{
    		$r .= $DSP->qdiv('itemWrapper', $paginate.BR.BR);
    	}
    	
		$r		.=	$DSP->qdiv('itemWrapperTop', $DSP->input_submit($LANG->line('delete')));             
        
        $r		.=	$DSP->form_close();
        
        return $r;
    }
    
    //	End bad tags
    
    
	// -------------------------------------------
    //  Manage Bad Tags
	// -------------------------------------------
    
    function manage_bad_tags($message = '')
    {
        global $DSP, $LANG;
    	
		// -------------------------------------------
		//  Start page
		// -------------------------------------------
                        
        $title	= $LANG->line('manage_bad_tags');

		$crumb	= $LANG->line('manage_bad_tags');
		
        $r		= $this->header_and_msg($message);
        
		$r		.= $DSP->right_crumb($LANG->line('add_bad_tag'), $this->base.'P=edit_bad_tag_form');

        $r		.= $DSP->qdiv('tableHeading', $LANG->line('manage_bad_tags'));
        
		// -------------------------------------------
		//  Contents
		// -------------------------------------------
        
        $r		.= $this->bad_tags();
				
		// -------------------------------------------
		//	Return the finalized output
		// -------------------------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
	}
    // End manage bad tags
  
    
    // -------------------------------------------
    //   Delete Bad Tag - Confirm
    // -------------------------------------------    

    function delete_bad_tag_confirm()
    {
        global $IN, $DSP, $LANG;
        
        if ( ! $IN->GBL('toggle', 'POST'))
        { 
            return $this->manage_tags();
        }
        
        $title	= $LANG->line('bad_tag_delete_confirm');
        
		$crumb 	= $DSP->anchor($this->base, $LANG->line('manage_bad_tags'));

		$crumb	.= $DSP->crumb_item($LANG->line('bad_tag_delete_confirm'));

        $r		= $DSP->form_open(array('action' => $this->base_short.'P=delete_bad_tag'));
        
        $i		= 0;
        
        foreach ( $_POST as $key => $val )
        {        
            if ( strstr( $key, 'toggle' ) AND ! is_array( $val ) AND is_numeric( $val ) )
            {
                $r	.=	$DSP->input_hidden('delete[]', $val);
                
                $i++;
            }        
        }
        
		$r		.= $DSP->qdiv('alertHeading', $LANG->line('bad_tag_delete_confirm'));
		
		$r		.= $DSP->div('box');
		
		if ( $i == 1 )
		{
			$replace[]	= $i; $replace[]	= 'tag';
		}
		else
		{
			$replace[]	= $i; $replace[]	= 'tags';
		}
		
		$search	= array( '%i%', '%tags%' );
		
		$r		.= $DSP->qdiv('defaultBold', str_replace( $search, $replace, $LANG->line('bad_tag_delete_question') ) );
		
		$r		.= $DSP->qdiv('alert', BR.$LANG->line('action_can_not_be_undone'));
		
		$r		.= $DSP->qdiv('', BR.$DSP->input_submit($LANG->line('delete')));
		
		$r		.= $DSP->qdiv('alert',$DSP->div_c());
		
		$r		.= $DSP->div_c();
		
		$r		.= $DSP->form_close();
				
		// -----------------------------
		//	Return the finalized output
		// -----------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
    }
    // End delete tag confirm
  
    
    // -------------------------------------------
    //   Delete Tag
    // -------------------------------------------    

    function delete_bad_tag()
    {
        global $DB, $DSP, $IN, $LANG, $SESS;
        
        $sql	= array();       
        
        if ( ! $IN->GBL('delete', 'POST'))
        {
            return $this->home();
        }

        $ids	= array();
                
        foreach ($_POST as $key => $val)
        {        
            if (strstr($key, 'delete') AND ! is_array($val) AND is_numeric($val))
            {
                $ids[] = "tag_id = '".$val."'";
            }        
        }
        
        $IDS			= implode(" OR ", $ids);
        
        $query			= $DB->query("SELECT tag_id FROM exp_tag_bad_tags WHERE ".$IDS);
        
		// -------------------------------------------
		//	Delete tags
		// -------------------------------------------
		
		foreach ( $query->result as $row )
		{			
			$sql[]	= "DELETE FROM exp_tag_bad_tags WHERE tag_id = '".$row['tag_id']."'";
		}
		
		foreach ( $sql as $q )
		{
			$DB->query($q);
		}
    
        $message = ($query->num_rows == 1) ? str_replace( '%i%', $query->num_rows, $LANG->line('bad_tag_deleted') ) : str_replace( '%i%', $query->num_rows, $LANG->line('bad_tags_deleted') );

        return $this->manage_bad_tags($message);
    }
    
    //	End delete tag
    
    
    // -------------------------
    //  Edit bad tag form
    // -------------------------
    
    function edit_bad_tag_form()
    {
        global $IN, $DSP, $DB, $LANG;
        
        $tag_name			= '';
        
        $edit_bad_tag_mode	= ( $IN->GBL('tag_id') ) ? 'edit_bad_tag': 'add_bad_tag';
    	
		// -------------------------
		//  Start page
		// -------------------------    	
                        
        $title	= $LANG->line( $edit_bad_tag_mode );
        
		$crumb 	= $DSP->anchor($this->base.'P=edit_bad_tag', $LANG->line('manage_bad_tags'));

		$crumb	.= $DSP->crumb_item($LANG->line( $edit_bad_tag_mode ));
		
        $r		= $this->header_and_msg();
					  
		// ------------------------------------
		//  Query
		// ------------------------------------
		
		if ( $IN->GBL('tag_id') )
		{
			$sql	= "SELECT * FROM exp_tag_bad_tags WHERE tag_id = '".$IN->GBL('tag_id')."' LIMIT 1";
			
			$query				= $DB->query($sql);
			
			$this->tag_id		= $query->row['tag_id'];
			
			$tag_name			= $query->row['tag_name'];
		}
		
		// -----------------------------
		//	Start table
		// -----------------------------

        $r		.= $DSP->qdiv('tableHeading', $LANG->line( $edit_bad_tag_mode ));
				
		// -----------------------------
		//	Start form
		// -----------------------------
        
        $form_url	= $this->base_short.'P=edit_bad_tag';
        
        $r			.=	$DSP->form_open(array('action' => $form_url, 'name' => 'target', 'id' => 'target'));

		$r			.=	$DSP->input_hidden('tag_id', $this->tag_id, '', '', 'input', '');

        $r			.=	$DSP->table('tableBorder', '0', '0', '100%').
						$DSP->tr().
						$DSP->table_qcell('tableHeadingAlt', array('&nbsp;', '&nbsp;')).
						$DSP->tr_c();
		
		$style		='tableCellOne';
		
		// -----------------------------
		//	Start tag name
		// -----------------------------
				  
		$r			.= $DSP->tr();
		
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $LANG->line('tag_name')), '30%');
			
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $DSP->qdiv('itemWrapper', $DSP->input_text('tag_name', $tag_name, '35', '40', 'input', '45%'))), '70%');

		$r			.= $DSP->tr_c();
		
		// -----------------------------
		//	End table
		// -----------------------------
		
        $r			.= $DSP->table_c();        
    	
    	$button		= ( $tag_name == '' ) ? $LANG->line('add') : $LANG->line('update');
    	
		$r			.=	$DSP->qdiv('itemWrapperTop', $DSP->input_submit($button));             
        
        $r			.=	$DSP->form_close();
				
		// -----------------------------
		//	Return the finalized output
		// -----------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
	}
    // End edit bad tag form
  
    
    // -------------------------------------------
    //   Edit Bad Tag
    // -------------------------------------------    

    function edit_bad_tag()
    {
        global $DB, $DSP, $IN, $LANG, $LOC, $SESS;
        
        $tag_id		= '';
        
        $tag_name	= '';
        
        $update		= ( $this->tag_id = $IN->GBL('tag_id') ) ? TRUE: FALSE;
				
		// -------------------------------------------
		//	Validate
		// -------------------------------------------
        
        if ( ! $tag_name = $IN->GBL('tag_name') )
        {
			return $DSP->error_message($LANG->line('tag_name_required'));
        }
        
		// -------------------------------------------
		//	Check for duplicate
		// -------------------------------------------
		
        if ( ! $update )
        {
			$query	= $DB->query("SELECT tag_name FROM exp_tag_bad_tags WHERE tag_name = '".$tag_name."' LIMIT 1");

			if ( $query->num_rows > 0 )
			{
				return $DSP->error_message( str_replace( '%tag_name%', $tag_name, $LANG->line('bad_tag_exists') ) );
			}
		}
        
		// -------------------------------------------
		//	Clean tag
		// -------------------------------------------
		
		$tag_name	= strtolower( $DB->escape_str( $tag_name ) );		
				
		// -------------------------------------------
		//	Update or Create
		// -------------------------------------------
		
		if ( $update )
		{			
			$DB->query( $DB->update_string('exp_tag_bad_tags', array( 'tag_name' => $tag_name, 'author_id' => $SESS->userdata['member_id'], 'edit_date' => $LOC->now ), array( 'tag_id' => $this->tag_id ) ) );

			$message	= $LANG->line('bad_tag_updated');
		}
		else
		{			
			$DB->query( $DB->insert_string('exp_tag_bad_tags', array( 'tag_name' => $tag_name, 'author_id' => $SESS->userdata['member_id'], 'entry_date' => $LOC->now ) ) );

			$message	= str_replace( '%tag_name%', $tag_name, $LANG->line('bad_tag_added') );
		}

        return $this->manage_bad_tags($message);
    }
    
    //	End edit bad tag
    
    
	// -------------------------------------------
    //  Parse Prefs
	// -------------------------------------------
    
    function parse_prefs($message = '')
    {
    	global $DSP, $IN, $LANG, $PREFS;
    	
    	$rows			= array();
    	
    	$parse			= array( 'linebreak', 'comma', 'semicolon', 'colon' );
    	
    	$this->parse	= ( $IN->GBL('parse_pref') ) ? $IN->GBL('parse_pref'): $PREFS->ini('tag_module_parse');
    	
    	$js_dir			= ( $IN->GBL('js_dir') ) ? $IN->GBL('js_dir'): $PREFS->ini('tag_module_js_directory');
    	
		// -------------------------------------------
		//  Start
		// -------------------------------------------

        $r			= $DSP->qdiv('tableHeading', $LANG->line('manage_general_prefs'));
        
        $form_url	= $this->base_short.'P=update_parse_pref';
        
        $r			.=	$DSP->form_open(array('action' => $form_url, 'name' => 'parse_pref_form', 'id' => 'parse_pref_form'));

		$r			.= $DSP->table_open(array('class' => 'tableBorder', 'width' => '100%'));
    	
		// -------------------------------------------
		//  Table header
		// -------------------------------------------
		
		$top[]		= array(
						'text'		=> $LANG->line('parse_pref'),
						'class'		=> 'tableHeadingAlt',
						'width'		=>  '100%',
						'colspan'	=> '2'
					);

		$r			.= $DSP->table_row( $top );
    	
		// -------------------------------------------
		//  Select field
		// -------------------------------------------

		$selects	= '';

		$selects	.= $DSP->input_select_header('parse_pref');
		
		foreach( $parse as $p )
		{
			$selected	= ( $p == $this->parse ) ? 'y': '';
			
			$selects	.= $DSP->input_select_option( $p, ucfirst($p), $selected);
		}

		$selects	.= $DSP->input_select_footer();
		
		unset($rows);
		
		$rows[]		= array(
						array(
							'text'	=> $LANG->line('parse_pref'),
							'class'	=> 'tableCellOne',
							'width'	=>  '30%'
						),
						array(
							'text'	=> $selects,
							'class'	=> 'tableCellOne',
							'width'	=>  '70%'
						)
					);
		
		$rows[]		= array(
						array(
							'text'	=> $LANG->line('js_dir'),
							'class'	=> 'tableCellOne'
						),
						array(
							'text'	=> $DSP->input_text('js_dir', $js_dir, '60', '150', 'input', '100%'),
							'class'	=> 'tableCellOne'
						)
					);
		
		$rows[]		= array(
						array(
							'text'	=> '',
							'class'	=> 'tableCellOne'
						),
						array(
							'text'	=> $DSP->input_submit($LANG->line('submit')),
							'class'	=> 'tableCellOne'
						)
					);
					
		foreach ( $rows as $row )
		{
			$r			.= $DSP->table_row( $row );
		}

        $r		.=	$DSP->table_c();            
        
        $r		.=	$DSP->form_close();
        
        $r		.= $DSP->qdiv('', NBS);
        
        return $r;
    }
    
    //	End parse prefs
    
    
	// -------------------------------------------
    //  Prefs
	// -------------------------------------------
    
    function prefs($message = '')
    {
    	global $DB, $DSP, $IN, $LANG, $LOC;
                
        $row_limit		= 50;
        $paginate		= '';
        $row_count		= 0;
        
		// ------------------------------------
		//  Start tables
		// ------------------------------------

        $r				= $DSP->qdiv('tableHeading', $LANG->line('manage_weblog_prefs'));

		// ------------------------------------
		//  Query
		// ------------------------------------
		
		$sql	= "SELECT p.*, w.blog_title FROM exp_tag_prefs AS p LEFT JOIN exp_weblogs AS w ON w.weblog_id = p.weblog_id ORDER BY w.blog_title DESC";
		
		$query	= $DB->query($sql);
		
		if ( $query->num_rows == 0 )
		{
			$r	.=	$DSP->qdiv('tableCellOne', $DSP->qdiv('highlight', $LANG->line('no_prefs')));
				
			// -----------------------------
			//	Return the finalized output
			// ----------------------------- 
			
			return $r;
		}
		
		// ------------------------------------
		//  Paginate
		// ------------------------------------
    
		if ( $query->num_rows > $row_limit )
		{
			$row_count		= ( ! $IN->GBL('row')) ? 0 : $IN->GBL('row');
						
			$url			= $this->base.'P=manage_prefs';
			
			$paginate		= $DSP->pager(
											$url,
											$query->num_rows, 
											$row_limit,
											$row_count,
											'row'
										);
			 
			$sql			.= " LIMIT ".$row_count.", ".$row_limit;
			
			$query			= $DB->query($sql);    
		}
    
        $r					.=	$DSP->toggle();
        
        $DSP->body_props	.= ' onload="magic_check()" ';
        
        $r					.= $DSP->magic_checkboxes();
        
        $form_url			= $this->base_short.'P=delete_pref_confirm';
        
        $r					.=	$DSP->form_open(array('action' => $form_url, 'name' => 'target', 'id' => 'target'));

		$r					.= $DSP->table_open(array('class' => 'tableBorder', 'width' => '100%'));
		
		$top[] = array(
						'text'	=> NBS,
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '3%'
					);
		
		$top[]	= array(
						'text'	=> $DSP->input_checkbox('toggleflag', '', '', "onclick=\"toggle(this);\"").NBS.NBS.$LANG->line('delete'),
						'class'	=> 'tableHeadingAlt',
						'width'	=> '15%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('pref_name'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '20%'
					);
		
		$top[]	= array(
						'text'	=> $LANG->line('blog_title'),
						'class'	=> 'tableHeadingAlt',
						'width'	=>  '62%'
					);

		$r		.= $DSP->table_row( $top );
		
		$row_count++;
		
		$i = 0;
		
		foreach ( $query->result as $row )
		{
			unset($rows);
			
			$rows[]		= $row_count;
			
			$rows[]		= $DSP->input_checkbox('toggle[]', $row['pref_id'], '', "id='delete_box_".$row['pref_id']."'");
			
			$rows[]		= $DSP->anchor( $this->base.'P=edit_pref_form'.AMP.'pref_id='.$row['pref_id'], $row['pref_name'] );
			
			$rows[]		= $row['blog_title'];
			
			$r			 .= $DSP->table_qrow( ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo', $rows);
			$row_count++;
		}
		
		
		$foot[] = NBS;
		
		$foot[] = $DSP->input_checkbox('toggleflag', '', '', "onclick=\"toggle(this);\"").NBS.NBS.'<b>'.$LANG->line('delete').'</b>';

		$foot[] = NBS;

		$foot[] = NBS;
				
		$r		.= $DSP->table_qrow( ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo', $foot);

        $r		.=	$DSP->table_c(); 

    	if ($paginate != '')
    	{
    		$r .= $DSP->qdiv('itemWrapper', $paginate.BR.BR);
    	}
    	
		$r		.=	$DSP->qdiv('itemWrapperTop', $DSP->input_submit($LANG->line('delete')));             
        
        $r		.=	$DSP->form_close();
        
        return $r;
    }
    
    //	End prefs
  
    
    // -------------------------------------------
    //   Update parse pref
    // -------------------------------------------    

    function update_parse_pref()
    {
        global $DSP, $IN, $LANG, $PREFS;
        
        if ( ! $IN->GBL('parse_pref') )
        {
            return $this->home();
        }
        
		// ----------------------------------------
		//	Update parse pref
		// ----------------------------------------
		
		if ( ! class_exists('Admin'))
		{
			require PATH_CP.'cp.admin'.EXT;
		}
		
		if ( $PREFS->ini('tag_module_parse') != $IN->GBL('parse_pref') )
		{
			Admin::update_config_file( array( 'tag_module_parse' => $IN->GBL('parse_pref') ) );
		}
        
		// ----------------------------------------
		//	Update js directory
		// ----------------------------------------
		
		if ( $IN->GBL('js_dir') AND $PREFS->ini('tag_module_js_directory') != $IN->GBL('js_dir') )
		{
			
			if ( ! $this->url_exists( $IN->GBL('js_dir').'prototype.js' ) )
			{
				return $DSP->error_message($LANG->line('cannot_find_js'));
			}
			
			Admin::update_config_file( array( 'tag_module_js_directory' => $IN->GBL('js_dir') ) );
		}
    
        $message = $LANG->line('general_prefs_updated');

        return $this->manage_prefs($message);
    }
    
    //	End update parse pref
    
    
	// -------------------------------------------
    //  Manage Prefs
	// -------------------------------------------
    
    function manage_prefs($message = '')
    {
        global $DB, $DSP, $LANG;
    	
		// -------------------------------------------
		//  Start page
		// -------------------------------------------
                        
        $title	= $LANG->line('manage_prefs');

		$crumb	= $LANG->line('manage_prefs');
		
        $r		= $this->header_and_msg($message);
        
        $a		= $DB->query( "SELECT count(*) AS count FROM exp_weblogs" );
        
        $b		= $DB->query( "SELECT count(*) AS count FROM exp_tag_prefs" );
        
        if ( $a->row['count'] != $b->row['count'] )
        {
			$r		.= $DSP->right_crumb($LANG->line('create_pref'), $this->base.'P=edit_pref_form');
        }
        
		// -------------------------------------------
		//  Contents
		// -------------------------------------------
        
        $r		.= $this->parse_prefs();
        
        $r		.= $this->prefs();
				
		// -------------------------------------------
		//	Return the finalized output
		// -------------------------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
	}
    // End manage prefs
  
    
    // -------------------------------------------
    //   Delete Pref - Confirm
    // -------------------------------------------    

    function delete_pref_confirm()
    {
        global $IN, $DSP, $LANG;
        
        if ( ! $IN->GBL('toggle', 'POST'))
        { 
            return $this->manage_prefs();
        }
        
        $title	= $LANG->line('pref_delete_confirm');
        
		$crumb 	= $DSP->anchor($this->base, $LANG->line('manage_prefs'));

		$crumb	.= $DSP->crumb_item($LANG->line('pref_delete_confirm'));

        $r		= $DSP->form_open(array('action' => $this->base_short.'P=delete_pref'));
        
        $i		= 0;
        
        foreach ( $_POST as $key => $val )
        {        
            if ( strstr( $key, 'toggle' ) AND ! is_array( $val ) AND is_numeric( $val ) )
            {
                $r	.=	$DSP->input_hidden('delete[]', $val);
                
                $i++;
            }        
        }
        
		$r		.= $DSP->qdiv('alertHeading', $LANG->line('pref_delete_confirm'));
		
		$r		.= $DSP->div('box');
		
		if ( $i == 1 )
		{
			$replace[]	= $i; $replace[]	= 'preference';
		}
		else
		{
			$replace[]	= $i; $replace[]	= 'preferences';
		}
		
		$search	= array( '%i%', '%preferences%' );
		
		$r		.= $DSP->qdiv('defaultBold', str_replace( $search, $replace, $LANG->line('pref_delete_question') ) );
		
		$r		.= $DSP->qdiv('alert', BR.$LANG->line('action_can_not_be_undone'));
		
		$r		.= $DSP->qdiv('', BR.$DSP->input_submit($LANG->line('delete')));
		
		$r		.= $DSP->qdiv('alert',$DSP->div_c());
		
		$r		.= $DSP->div_c();
		
		$r		.= $DSP->form_close();
				
		// -----------------------------
		//	Return the finalized output
		// -----------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
    }
    // End delete pref confirm
  
    
    // -------------------------------------------
    //   Delete Pref
    // -------------------------------------------    

    function delete_pref()
    {
        global $DB, $DSP, $IN, $LANG, $SESS;
        
        $sql	= array();       
        
        if ( ! $IN->GBL('delete', 'POST'))
        {
            return $this->home();
        }

        $ids	= array();
                
        foreach ($_POST as $key => $val)
        {        
            if (strstr($key, 'delete') AND ! is_array($val) AND is_numeric($val))
            {
                $ids[] = "pref_id = '".$val."'";
            }        
        }
        
        $IDS			= implode(" OR ", $ids);
        
        $query			= $DB->query("SELECT pref_id FROM exp_tag_prefs WHERE ".$IDS);
        
		// -------------------------------------------
		//	Delete prefs
		// -------------------------------------------
		
		foreach ( $query->result as $row )
		{			
			$sql[]	= "DELETE FROM exp_tag_prefs WHERE pref_id = '".$row['pref_id']."'";
		}
		
		foreach ( $sql as $q )
		{
			$DB->query($q);
		}
    
        $message = ($query->num_rows == 1) ? str_replace( '%i%', $query->num_rows, $LANG->line('pref_deleted') ) : str_replace( '%i%', $query->num_rows, $LANG->line('prefs_deleted') );

        return $this->manage_prefs($message);
    }
    
    //	End delete pref
    
    
    // -------------------------
    //  Edit pref form
    // -------------------------
    
    function edit_pref_form()
    {
        global $IN, $DSP, $DB, $LANG;
        
        $weblog_id				= '';
        
        $field_id				= '';
        
        $blog_title				= '';
        
        $pref_name				= '';
        
        $edit_pref_mode	= ( $IN->GBL('pref_id') ) ? 'edit_pref': 'create_pref';
    	
		// -------------------------
		//  Start page
		// -------------------------    	
                        
        $title	= $LANG->line( $edit_pref_mode );
        
		$crumb 	= $DSP->anchor($this->base.'P=manage_prefs', $LANG->line('manage_prefs'));

		$crumb	.= $DSP->crumb_item($LANG->line( $edit_pref_mode ));
		
        $r		= $this->header_and_msg();
					  
		// ------------------------------------
		//  Query
		// ------------------------------------
		
		if ( $IN->GBL('pref_id') )
		{
			$sql	= "SELECT * FROM exp_tag_prefs WHERE pref_id = '".$IN->GBL('pref_id')."' LIMIT 1";
			
			$query				= $DB->query($sql);
			
			$this->pref_id		= $query->row['pref_id'];
			
			$weblog_id			= $query->row['weblog_id'];
			
			$field_id			= $query->row['field_id'];
			
			$pref_name			= $query->row['pref_name'];
		}
		
		// -----------------------------
		//	Start table
		// -----------------------------

        $r		.= $DSP->qdiv('tableHeading', $LANG->line( $edit_pref_mode ));
				
		// -----------------------------
		//	Start form
		// -----------------------------
        
        $form_url	= $this->base_short.'P=edit_pref';
        
        $r			.=	$DSP->form_open(array('action' => $form_url, 'name' => 'target', 'id' => 'target'));

		$r			.=	$DSP->input_hidden('pref_id', $this->pref_id, '', '', 'input', '');

        $r			.=	$DSP->table('tableBorder', '0', '0', '100%').
						$DSP->tr().
						$DSP->table_qcell('tableHeadingAlt', array('&nbsp;', '&nbsp;')).
						$DSP->tr_c();
		
		$style		='tableCellOne';
		
		// -----------------------------
		//	Start pref name
		// -----------------------------
				  
		$r			.= $DSP->tr();
		
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $LANG->line('pref_name')), '30%');
			
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $DSP->qdiv('itemWrapper', $DSP->input_text('pref_name', $pref_name, '35', '40', 'input', '45%'))), '70%');

		$r			.= $DSP->tr_c();
		
		// -----------------------------
		//	Start weblog
		// -----------------------------
		
		$prefs		= array();
		
		$weblogs	= array();
		
		$str		= '';
		
		$p			= $DB->query( "SELECT * FROM exp_tag_prefs" );
		
		if ( $p->num_rows > 0 )
		{
			foreach( $p->result as $row )
			{
				$prefs[]	= $row['weblog_id'];
			}
		}
		
		$blogs		= $DB->query( "SELECT weblog_id, blog_title, field_group FROM exp_weblogs ORDER BY blog_title" );
				  
		$r			.= $DSP->tr();
		
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $LANG->line('weblog')), '30%');

		$selects	= '';

		$selects	.= $DSP->input_select_header('weblog_id');
		
		$selects	.= $DSP->input_select_option( '', '', '');
		
		if ( $blogs->num_rows > 0 )
		{
			foreach( $blogs->result as $blog )
			{
				if ( $this->pref_id == '' AND ! in_array( $blog['weblog_id'], $prefs ) )
				{					
					$selects	.= $DSP->input_select_option( $blog['weblog_id'], $blog['blog_title']);
				}
				elseif ( $this->pref_id != '' )
				{
					$selected	= ( $weblog_id == $blog['weblog_id'] ) ? 'y': '';
					
					$selects	.= $DSP->input_select_option( $blog['weblog_id'], $blog['blog_title'], $selected);
				}
			}
		}

		$selects	.= $DSP->input_select_footer();
		
		$selects	= str_replace( "name='weblog_id'", "name='weblog_id' id='weblog_id_field' onchange=\"weblog_field('weblog_id_field');\"", $selects );
			
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $DSP->qdiv('itemWrapper', $selects)), '70%');

		$r			.= $DSP->tr_c();
		
		// -----------------------------
		//	Start fields
		// -----------------------------
		
		$sub		= $DB->query( "SELECT w.weblog_id, g.field_id, g.group_id, g.field_label FROM exp_weblogs AS w LEFT JOIN exp_weblog_fields AS g ON g.group_id = w.field_group ORDER BY g.field_order" );

		foreach ( $sub->result as $field )
		{
			$fields[$field['weblog_id']][$field['field_id']]	= $field['field_label'];
		}
				  
		$r			.= $DSP->tr();
		
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $LANG->line('tag_field')), '30%');

		$field_block	= '';

		foreach ( $fields as $g => $group )
		{
			$selects		= '';
	
			$selects		.= $DSP->input_select_header('field_id[]');
			
			$selects		.= $DSP->input_select_option( '', '', '');
				
			foreach ( $group as $key => $val )
			{
				$selected	= ( $key == $field_id ) ? 'y': '';
				
				$selects	.= $DSP->input_select_option( $key, $val, $selected);
			}
		
			$selects		.= $DSP->input_select_footer();
			
			$display		= ( $g != $weblog_id ) ? 'style="display:none;"': 'style="display:block;"';
			
			$field_block	.= $DSP->qdiv('field_group', $selects, 'field_groups_'.$g, $display );
		}
			
		$r			.= $DSP->table_qcell($style, $DSP->qdiv('defaultBold', $field_block, 'field_block'), '70%');

		$r			.= $DSP->tr_c();
		
		// -----------------------------
		//	End table
		// -----------------------------
		
        $r			.= $DSP->table_c();        
    	
    	$button		= ( $pref_name == '' ) ? $LANG->line('create') : $LANG->line('update');
    	
		$r			.=	$DSP->qdiv('itemWrapperTop', $DSP->input_submit($button));             
        
        $r			.=	$DSP->form_close();
				
		// -----------------------------
		//	Return the finalized output
		// -----------------------------
		
		return $this->content_wrapper($title, $crumb, $r);
	}
    // End edit pref form
  
    
    // -------------------------------------------
    //   Edit Pref
    // -------------------------------------------    

    function edit_pref()
    {
        global $DB, $DSP, $IN, $LANG;
        
        $field_id	= '';
        
        $update		= ( $this->pref_id = $IN->GBL('pref_id') ) ? TRUE: FALSE;
				
		// -------------------------------------------
		//	Validate
		// -------------------------------------------
        
        if ( ! $IN->GBL('pref_name') )
        {
			return $DSP->error_message($LANG->line('pref_name_required'));
        }
        
        if ( $IN->GBL('weblog_id') == '' )
        {
			return $DSP->error_message($LANG->line('weblog_required'));
        }
        
        foreach ( $_POST['field_id'] as $field )
        {
        	if ( $field != '' )
        	{
				$field_id	= $field;
        	}
        }
        
        if ( $field_id == '' )
        {
			return $DSP->error_message($LANG->line('field_required'));
        }
        
		// -------------------------------------------
		//	Check for duplicate
		// -------------------------------------------
		
        if ( ! $update )
        {
			$query	= $DB->query("SELECT w.blog_title FROM exp_weblogs AS w LEFT JOIN exp_tag_prefs AS p ON p.weblog_id = w.weblog_id WHERE p.weblog_id = '".$IN->GBL('weblog_id', 'POST')."' LIMIT 1");

			if ( $query->num_rows > 0 )
			{
				return $DSP->error_message( $this->nomenclature( str_replace( '%blog_title%', $query->row['blog_title'], $LANG->line('weblog_exists') ) ) );
			}
		}
		
				
		// -------------------------------------------
		//	Update or Create
		// -------------------------------------------
		
		if ( $update )
		{			
			$DB->query( $DB->update_string('exp_tag_prefs', array( 'pref_name' => $IN->GBL('pref_name'), 'weblog_id' => $IN->GBL('weblog_id'), 'field_id' => $field_id ), array( 'pref_id' => $this->pref_id ) ) );

			$message	= $LANG->line('weblog_pref_updated');
		}
		else
		{			
			$DB->query( $DB->insert_string('exp_tag_prefs', array( 'pref_name' => $IN->GBL('pref_name'), 'weblog_id' => $IN->GBL('weblog_id'), 'field_id' => $field_id ) ) );

			$message	= $LANG->line('weblog_pref_created');
		}

        return $this->manage_prefs($message);
    }
    
    //	End edit pref
    
    	
	// -------------------------------------------
	//	Nomenclature helper
	// -------------------------------------------
    
    function nomenclature( $txt = '' )
    {
    	$swap_in	= array( '%weblog%', '%Weblog%' );
    	
    	$swap_out	= array( $this->weblog, $this->Weblog );
    	
    	return $txt	= str_replace( $swap_in, $swap_out, $txt );
    }
    
    //	End nomenclature helper
	
	
	// ----------------------------------------
    //  Handle extension
	// ----------------------------------------
	
	function handle_extension()
	{
		global $DB, $DSP, $LANG, $PREFS;
		
		// ----------------------------------------
		//  Check for and enable the extension
		// ----------------------------------------
		
		if ( ! file_exists(PATH.'extensions/ext.tag_submit.php') )
		{
			return $DSP->error_message($LANG->line('extension_not_found'));
		}
		elseif ( $PREFS->ini('allow_extensions') != 'y' )
		{
			return $DSP->error_message( str_replace( "%link", $DSP->anchor( BASE.AMP."C=admin".AMP."M=utilities".AMP."P=extensions_manager", $LANG->line('enable_extensions') ), $LANG->line('extension_not_enabled') ) );
		}
		else
		{
			$query	= $DB->query("SELECT enabled FROM exp_extensions WHERE class = 'tag_submit' LIMIT 1");

			if ( $query->num_rows == 0 )
			{
				$data[]	= array(
								'class'		=> 'tag_submit',
								'method'	=> 'parse',
								'hook'		=> 'submit_new_entry_end',
								'priority'	=> '5',
								'version'	=> '1.0.0',
								'enabled'	=> 'y'
								);
				$data[]	= array(
								'class'		=> 'tag_submit',
								'method'	=> 'delete',
								'hook'		=> 'delete_entries_start',
								'priority'	=> '5',
								'version'	=> '1.0.0',
								'enabled'	=> 'y'
								);
								
				foreach ( $data as $d )
				{
					$DB->query( $DB->insert_string( 'exp_extensions', $d ) );
				}
				
			}
			elseif ( $query->row['enabled'] == 'n' )
			{
				$DB->query( $DB->update_string( 'exp_extensions', array( 'enabled' => 'y' ), array( 'class' => 'tag_submit' ) ) );
			}
			
			return TRUE;
		}
	}
	
	//	End handle extension
    
    
	// -------------------------------------------
	//	Module upgrade
	// -------------------------------------------

    function module_upgrade()
    {
    	global $DB, $LANG, $PREFS;
    	
    	$sql	= array();
    	
		// ----------------------------------------
		//	Start page
		// ----------------------------------------
                        
        $title	= $LANG->line('upgrade');

		$crumb	= $LANG->line('upgrade');
    	
		// ----------------------------------------
		//	Should we proceed?
		// ----------------------------------------

		if ( $this->old_version >= $this->version )
		{
			return $this->home();
		}
		
		// ----------------------------------------
		//  Check for and enable the extension
		// ----------------------------------------
		
		if ( ! $this->handle_extension() ) return;
        
		// ----------------------------------------
		//	Add config file pref if not exists
		// ----------------------------------------
		
		if ( ! class_exists('Admin'))
		{
			require PATH_CP.'cp.admin'.EXT;
		}
		
		if ( ! $PREFS->ini('tag_module_parse') )
		{
			Admin::append_config_file( array( 'tag_module_parse' => 'linebreak' ) );
		}
		
		if ( ! $PREFS->ini('tag_module_js_directory') )
		{
			Admin::append_config_file( array( 'tag_module_js_directory' => $this->cp.'modules/tag/js/' ) );
		}
		
		// ----------------------------------------
		//  Create bad tag table if absent
		// ----------------------------------------
		
		if ( ! $DB->table_exists('exp_tag_bad_tags') )
		{
			$sql	= array_merge( $sql, $this->sql_bad_tags() );
		}
    	
		// ----------------------------------------
		//	Check for columns in tags table
		// ----------------------------------------
		
		$query		= $DB->query("DESCRIBE exp_tag_entries");
		
		$ip_address	= FALSE;
		$remote		= FALSE;
		
		foreach( $query->result as $row )
		{			
			//	Check for 'remote' column
			if ( $row['Field'] == 'remote' )
			{
				$remote		= TRUE;
			}
			
			//	Check for 'remote' column
			if ( $row['Field'] == 'ip_address' )
			{
				$ip_address	= TRUE;
			}
		}
		
		//	Add in missing columns
		
		if ( ! $remote )
		{
			$sql[]	= "ALTER TABLE exp_tag_entries ADD remote char(1) NOT NULL default 'n' AFTER author_id";
		}
		
		if ( ! $ip_address )
		{
			$sql[]	= "ALTER TABLE exp_tag_entries ADD ip_address varchar(16) NOT NULL default '0' AFTER author_id";
		}
		
		// ----------------------------------------
		//  Execute inserts
		// ----------------------------------------

        foreach ($sql as $query)
        {
            $DB->query($query);
        }
    	
		// ----------------------------------------
		//	Upgrade the module
		// ----------------------------------------
		
		$DB->query( "UPDATE exp_modules SET module_version = '".$this->version."' WHERE module_name = '".$this->module_name."'" );
				
		// ----------------------------------------
		//	Return output
		// ----------------------------------------
		
		return $this->home( $LANG->line('upgrade_successful') );
    }
    
    //	End upgrade
    
    
	// ----------------------------------------
    //  Check file
	// ----------------------------------------
	
	function url_exists($url)
	{
		$handle = @fopen($url, "r");
		
		if ($handle === false) return false;
		fclose($handle);
		return true;
	}
	
	//	End check file
    

	// ----------------------------------------
    //  SQL for tags table creation
	// ----------------------------------------
    
    function sql_tags()
    {
    	$sql	= array();

        $sql[]	=	"CREATE TABLE exp_tag_tags (
					tag_id int(10) unsigned NOT NULL auto_increment,
					tag_alpha char(1) NOT NULL,
					tag_name varchar(150) NOT NULL,
					author_id int(10) unsigned NOT NULL,
					entry_date int(10) NOT NULL,
					edit_date int(10) NOT NULL default '0',
					PRIMARY KEY (tag_id),
					KEY (tag_name)
					)";
					
		return $sql;
    }
    
    //	End SQL for tags table creation
    

	// -------------------------------------------
    //  SQL for bad tags table creation
    // -------------------------------------------
    
    function sql_bad_tags()
    {
    	$sql	= array();

        $sql[]	=	"CREATE TABLE exp_tag_bad_tags (
					tag_id int(10) unsigned NOT NULL auto_increment,
					tag_name varchar(150) NOT NULL,
					author_id int(10) unsigned NOT NULL,
					entry_date int(10) NOT NULL,
					edit_date int(10) NOT NULL default '0',
					PRIMARY KEY (tag_id),
					KEY (tag_name)
					)";
					
		return $sql;
    }
    
    //	End SQL for bad tags table creation
    

	// -------------------------------------------
    //  SQL for entries table creation
    // -------------------------------------------
    
    function sql_entries()
    {
    	$sql	= array();

        $sql[]	=	"CREATE TABLE exp_tag_entries (
					entry_id int(10) unsigned NOT NULL,
					tag_id int(10) unsigned NOT NULL,
					weblog_id smallint(3) unsigned NOT NULL,
					author_id int(10) unsigned NOT NULL,
					ip_address varchar(16) NOT NULL default '0',
					remote char(1) NOT NULL default 'n',
					KEY (entry_id),
					KEY (tag_id)
					)";
					
		return $sql;
    }
    
    //	End SQL for entries table creation
    

	// -------------------------------------------
    //  SQL for tag stats creation
    // -------------------------------------------
    
    function sql_stats()
    {
    	$sql	= array();

        $sql[]	=	"CREATE TABLE exp_tag_stats (
					tag_id int(10) unsigned NOT NULL,
					weblog_id smallint(3) unsigned NOT NULL,
					count int(10) unsigned NOT NULL,
					PRIMARY KEY (tag_id),
					KEY (weblog_id),
					KEY (count)
					)";
					
		return $sql;
    }
    
    //	End SQL for tag stats creation
    

	// -------------------------------------------
    //  SQL for prefs creation
    // -------------------------------------------
    
    function sql_prefs()
    {
    	$sql	= array();

        $sql[]	=	"CREATE TABLE exp_tag_prefs (
					pref_id smallint(3) unsigned NOT NULL auto_increment,
					pref_name varchar(150) NOT NULL,
					weblog_id smallint(3) unsigned NOT NULL,
					field_id smallint(5) unsigned NOT NULL,
					PRIMARY KEY (pref_id),
					KEY (weblog_id),
					KEY (field_id)
					)";
					
		return $sql;
    }
    
    //	End SQL for prefs creation


	// -------------------------------------------
	//	Module installer
	// -------------------------------------------

    function tag_module_install()
    {
        global $DB;
        
		// -------------------------------------------
		//	Add config file pref
		// -------------------------------------------
		
		if ( ! class_exists('Admin'))
		{
			require PATH_CP.'cp.admin'.EXT;
		}
		
		Admin::append_config_file( array( 'tag_module_parse' => 'linebreak' ) );
		Admin::append_config_file( array( 'tag_module_js_directory' => $this->cp.'modules/tag/js/' ) );
		
		// -------------------------------------------
		//	Add DB stuff
		// -------------------------------------------
        
        $sql[]	=	"INSERT INTO exp_modules (module_id, module_name, module_version, has_cp_backend) VALUES ('', '$this->module_name', '$this->version', 'y')";

        $sql[]	=	"INSERT INTO exp_actions (action_id, class, method) VALUES ('', 'Tag', 'insert_tags')";

		$sql	=	array_merge( $sql, $this->sql_tags(), $this->sql_bad_tags(), $this->sql_entries(), $this->sql_prefs() );

        foreach ($sql as $query)
        {
            $DB->query($query);
        }
        
        return true;
    }
    //	End installer
    
    
	// -------------------------------------------
	//	Module de-installer
	// -------------------------------------------

    function tag_module_deinstall()
    {
        global $DB;
        
		// -------------------------------------------
		//	Remove the config file pref
		// -------------------------------------------
		
		if ( ! class_exists('Admin'))
		{
			require PATH_CP.'cp.admin'.EXT;
		}
		
		Admin::append_config_file( array(), array( 'tag_module_parse' ) );
		
		// -------------------------------------------
		//	Delete DB stuff
		// -------------------------------------------
        
        $query	= $DB->query("SELECT module_id FROM exp_modules WHERE module_name = '$this->module_name'");

        $sql[]	=	"DELETE FROM exp_modules WHERE module_name = '$this->module_name'";
        
        $sql[]	=	"DELETE FROM exp_actions WHERE class = '$this->module_name'";
        
        $sql[]	=	"DROP TABLE IF EXISTS exp_tag_tags";
        
        $sql[]	=	"DROP TABLE IF EXISTS exp_tag_bad_tags";
        
        $sql[]	=	"DROP TABLE IF EXISTS exp_tag_entries";
        
        $sql[]	=	"DROP TABLE IF EXISTS exp_tag_prefs";
                    
        foreach ($sql as $query)
        {
            $DB->query($query);
        }

        return true;
    }
    
    // End de-installer
    
}

//	End class
?>