<?php
/*
Plugin Name: SEO Title Tag
Plugin URI: http://www.netconcepts.com/seo-title-tag-plugin/
Description: Search engine optimize your blog's title tags. Create a customized title tag for any post, static page, category page, UltimateTagWarrior tag page - indeed, any URL! And will auto-insert the tag name into the title on tag pages generated by UltimateTagWarrior plugin. Admin allows for mass editing of title tags.
Author: Stephan Spencer, Netconcepts
Version: 2.1.2
Author URI: http://www.netconcepts.com

Copyright (c) 2006,2007 Stephan Spencer (http://www.stephanspencer.com)
and Netconcepts (http://www.netconcepts.com)
SEO Title Tag is released under the GNU General Public
License (GPL) http://www.gnu.org/licenses/gpl.txt

This is a WordPress plugin (http://wordpress.org).

Todo:
- support meta descriptions?
- import titles by uploading a file in CSV format
- possibly rename custom option fields and table name
- move the UTW tags to an extra table (like categories)
- autocheck if plugin upgrade is available (like Podpress does)
*/

// this will create the DB table if needed.
function seo_title_tag_install()
{
    global $wpdb;

    $charset_collate = '';

    if (version_compare(mysql_get_server_info(), '4.1.0', '>=') ) {

        if (!empty($wpdb->charset)) {
            $charset_collate .= "DEFAULT CHARACTER SET $wpdb->charset";
        }

        if (!empty($wpdb->collate)) {
            $charset_collate .= " COLLATE $wpdb->collate";
        }
    }

    foreach ($wpdb->get_col("SHOW TABLES", 0) as $table ) {
        $tables[$table] = $table;
    }

    $table_name = $wpdb->prefix . "seo_title_tag_url";
    // the URL table
    if (isset($tables[$table_name]) && !empty($charset_collate)) {
        $sql = "ALTER TABLE $table_name
                CHANGE url url VARCHAR(255) NOT NULL,
                CHANGE title title VARCHAR(255) NOT NULL,
                $charset_collate";
    } else {
        $sql = "CREATE TABLE $table_name (
                  id bigint(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  url varchar(255) NOT NULL,
                  title varchar(255) NOT NULL
                ) $charset_collate;";
    }

    $q = $wpdb->query($sql);

    $table_name = $wpdb->prefix . "seo_title_tag_category";
    // the category table
    if (isset($tables[$table_name]) && !empty($charset_collate)) {
        $sql = "ALTER TABLE $table_name
                CHANGE category_id category_id VARCHAR(255) NOT NULL,
                CHANGE title title VARCHAR(255) NOT NULL,
                $charset_collate";
    } else {
        $sql = "CREATE TABLE $table_name (
                  id bigint(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  category_id varchar(255) NOT NULL,
                  title varchar(255) NOT NULL
                ) $charset_collate;";
    }

    $q = $wpdb->query($sql);

    $table_name = $wpdb->prefix . "seo_title_tag_tag";
    // the tag table
    if (isset($tables[$table_name]) && !empty($charset_collate)) {
        $sql = "ALTER TABLE $table_name
                CHANGE tag_id tag_id VARCHAR(255) NOT NULL,
                CHANGE title title VARCHAR(255) NOT NULL,
                $charset_collate";
    } else {
        $sql = "CREATE TABLE $table_name (
                  id bigint(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  tag_id varchar(255) NOT NULL,
                  title varchar(255) NOT NULL
                ) $charset_collate;";
    }

    $q = $wpdb->query($sql);

    if (! get_option("custom_title_key"))
    {
        update_option('custom_title_key', "title_tag");
    }

    if (! get_option("use_category_description_as_title"))
    {
        update_option('use_category_description_as_title', false);
    }

    if (! get_option('include_blog_name_in_titles'))
    {
        update_option('include_blog_name_in_titles', false);
    }

    if (! get_option('utw_opt_in'))
    {
        update_option('utw_opt_in', false);
    }
    elseif (0 >= seo_title_tag_version_compare('2.3'))
    {
        update_option('utw_opt_in', false);
    }

    if (! get_option('manage_elements_per_page'))
    {
        update_option("manage_elements_per_page", 20);
    }

    // Pull over any title tags from UTW
    if (0 >= seo_title_tag_version_compare('2.3'))
    {
        if (!get_option('utw_import')) {

            $sql = "SELECT
                        tag,
                        tag_pagetitle
                    FROM
                        " . $wpdb->prefix . "tags";

            $wpdb->hide_errors();
            $rs = $wpdb->get_results($sql);
            $wpdb->show_errors();

            if (is_array($rs) && 0 < count($rs)) {
                foreach ($rs as $row) {
                    $tagTitles[$row->tag] = $row->tag_pagetitle;
                }
            }

            $sql = "SELECT
                        t.term_id,
                        t.slug
                    FROM
                        " . $wpdb->terms . " t INNER JOIN " . $wpdb->term_taxonomy . " tt
                        ON t.term_id = tt.term_id
                    WHERE
                        tt.taxonomy = 'post_tag'";

            $rs = $wpdb->get_results($sql);
            if (is_array($rs) && 0 < count($rs)) {
                foreach ($rs as $row) {
                    if (isset($tagTitles[$row->slug])) {
                        $sql = "SELECT
                                    COUNT(*) as title_count
                                FROM
                                    " . $wpdb->prefix . "seo_title_tag_tag
                                WHERE
                                    tag_id = {$row->term_id}
                                LIMIT 1";

                        $rs2 = $wpdb->get_results($sql);
                        if (is_array($rs2) && 0 == $rs2[0]->title_count) {
                            $sql = "INSERT INTO
                                        " . $wpdb->prefix . "seo_title_tag_tag
                                    SET
                                        tag_id = {$row->term_id},
                                        title = '" . $wpdb->escape($tagTitles[$row->slug]) . "'";

                            $wpdb->query($sql);
                        }
                    }
                }
            }

            update_option('utw_import', true);
        }
    }
}

function seo_title_tag_get_categories()
{
    global $wpdb, $wp_version;

    if (0 < seo_title_tag_version_compare('2.3')) {
        $results = $wpdb->get_results("SELECT * FROM " . $wpdb->categories . " ORDER BY cat_name");
    } else {
        $results = $wpdb->get_results("
            SELECT
                tt.term_id as cat_ID,
                t.name as cat_name,
                t.slug as category_nicename,
                tt.description as category_description,
                tt.parent as category_parent,
                tt.count as category_count
            FROM
                " . $wpdb->term_taxonomy . " tt
                INNER JOIN " . $wpdb->terms . " t
                ON tt.term_id = t.term_id
            WHERE
                tt.taxonomy = 'category'
            ORDER BY
                t.name"
        );
    }

    return $results;
}

function seo_title_tag_get_tags()
{
    global $wpdb, $wp_version;

    if (0 < seo_title_tag_version_compare('2.3')) {
        $results = $wpdb->get_results("SELECT * FROM " . $wpdb->categories . " WHERE 0 = 1 ORDER BY cat_name");
    } else {
        $results = $wpdb->get_results("
            SELECT
                tt.term_id,
                t.name,
                t.slug,
                tt.description,
                tt.parent,
                tt.count
            FROM
                " . $wpdb->term_taxonomy . " tt
                INNER JOIN " . $wpdb->terms . " t
                ON tt.term_id = t.term_id
            WHERE
                tt.taxonomy = 'post_tag'
            ORDER BY
                t.name"
        );
    }

    return $results;
}

// this is called on plugin activation.
add_action('activate_seo-title-tag/seo-title-tag.php','seo_title_tag_install');
add_action('admin_head','seo_admin_head');

function seo_admin_head() {
    //$s =bloginfo('wpurl');
    print '<link rel="stylesheet" type="text/css" href="'.get_option('siteurl').'/wp-content/plugins/seo-title-tag/admin.css" />';

}

// function that matches $url against the DB including optimizations. Returns the matching title.
function get_seo_url_title($url)
{
    global $wpdb; //, $wp_rewrite;

    /*
    this could be useful to extend the match against the URL.

    $rewrite_rules = $wp_rewrite->wp_rewrite_rules();

    foreach ($rewrite_rules as $regex => $value)
    {
    if(preg_match($regexm,$url,$matches))
    {
    //echo eval($value);
    }
    }
    */

    $table_name = $wpdb->prefix . "seo_title_tag_url";
    $condition = "(url LIKE '".$wpdb->escape($url)."'";

    if(preg_match('/^\/(.+)$/',$url,$matches))
    {
        $condition .= " OR url LIKE '".$wpdb->escape($matches[1])."'";
    }

    if(preg_match('/^\/{0,1}index.php\?{0,1}(.+)$/',$url,$matches))
    {
        $condition .= " OR url LIKE '".$wpdb->escape($matches[1])."'";
    }

    $condition .= ')';

    $sql = "SELECT title from ".$table_name." WHERE ".$condition;
    $temp = $wpdb->get_row($sql);

    return $temp->title;
}

// main function. Prints out the title for the page.
function seo_title_tag()
{
    global $cat, $cache_categories, $wp_query, $wp_version, $utw, $tabletags, $wpdb;

    // the url to match against
    $local_url = $_SERVER['REQUEST_URI'];
    // IIS on Windows fix
    if (! $local_url)
    {
        $local_url = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
    }

    // the title to print
    $title = '';
    // if the title is a url match.
    $is_url_title = false;

    if(get_option("custom_title_key")) {
        $custom_title_key = get_option("custom_title_key");
        $home_page_title = get_option("home_page_title");
        $home_page_title = htmlspecialchars(stripslashes($home_page_title));
        $error_page_title = get_option("error_page_title");
        $error_page_title = htmlspecialchars(stripslashes($error_page_title));
        $separator = get_option("separator");
        $separator = htmlspecialchars(stripslashes($separator));
        $use_category_description_as_title = get_option("use_category_description_as_title");
        $include_blog_name_in_titles = get_option("include_blog_name_in_titles");
        $short_blog_name = get_option("short_blog_name");
        if (0 < seo_title_tag_version_compare('2.3')) {
            $utw_opt_in = get_option("utw_opt_in");
        } else {
            $utw_opt_in = false;
        }
        $short_blog_name = htmlspecialchars(stripslashes($short_blog_name));
        $manage_elements_per_page = get_option("manage_elements_per_page");
    } else {
        $custom_title_key = "title_tag";
        $use_category_description_as_title = false;
        $include_blog_name_in_titles = false;
        $utw_opt_in = false;
        $manage_elements_per_page = 20;
    }

    if(empty($separator)) {
        $separator = "&raquo;";
    }

    // check if we are on the home page / Posts Page.
    // Note WP 2.1.x thinks that a static homepage (i.e. the Front Page) is not is_home
    if(is_home())
    {
        if ($home_page_title)
        {
            $title =  $home_page_title;
        }
        elseif ($temp = get_seo_url_title($local_url))
        {
            $is_url_title = true;
            $title = $temp;
        }
        else
        {
            $title = get_bloginfo('name');
        }
    }
    else
    {
        if(is_single() || is_page())
        {
            $post = $wp_query->post;
            $post_custom = get_post_custom($post->ID);
            $custom_title_value = $post_custom["$custom_title_key"][0];
            $custom_title_value = trim(strip_tags($custom_title_value));

            if ($custom_title_value)
            {
                $title = $custom_title_value;
                if ($post->ID == get_option('page_on_front')) {
                    $include_blog_name_in_titles = false;
                }
            }
            elseif ($temp = get_seo_url_title($local_url))
            {
                $is_url_title = true;
                $title = $temp;
            }
            else
            {
                $title = wp_title(' ', false);

                if(wp_title(' ', false) == ' ')
                {
                    $separator = "";
                }
            }
        }
        elseif(is_category())
        {
            $category = $wp_query->get_queried_object();
            $temp_category_title = '';

            if ($use_category_description_as_title)
            {
                $temp_category_title = trim(strip_tags($category->category_description));
            }
            else
            {
                if (!empty($category->cat_ID)) {
                    $table_name = $wpdb->prefix . "seo_title_tag_category";
                    $temp = $wpdb->get_results("SELECT title from ".$table_name." where category_id = ".$category->cat_ID);

                    if (is_array($temp) && isset($temp[0]))
                    {
                        $temp_category_title = $temp[0]->title;
                    }
                }
            }

            if($temp_category_title)
            {
                $title = $temp_category_title;
            }
            elseif ($temp = get_seo_url_title($local_url))
            {
                $is_url_title = true;
                $title = $temp;
            }
            else
            {
                $title = single_cat_title('',false);
            }

        }
        elseif(is_search())
        {
            if ($temp = get_seo_url_title($local_url))
            {
                $is_url_title = true;
                $title = $temp;
            }
            else
            {
                $title = "Search results";
                if (isset($_GET['s'])) { $title .= " for " . $_GET['s']; }
            }
        } elseif (function_exists('is_tag') && is_tag()) {

            if ($utw_opt_in && (0 < seo_title_tag_version_compare('2.3'))) {
                // UTW opt-in has been activated, so look for tag page titles
                $current_uri = $_SERVER['REQUEST_URI'];

                // check for multiple tags (using the 'and' or 'or' feature)
                $and_occurences = substr_count($current_uri, '+');
                $or_occurences = substr_count($current_uri, '|');
                $segments = explode("/", $current_uri);

                $tag = $segments[2];

                if (empty($tag))
                {
                    $tag = $_GET['tag'];
                    $and_occurences = substr_count($tag, '+');
                    $or_occurences = substr_count($tag, '|');
                }

                if($and_occurences == 0 && $or_occurences == 0){

                    // we are browsing a single tag, so look for a tag page title
                    $q_tagtitle = 'SELECT tag_pagetitle FROM '.$tabletags.' WHERE tag = \''.strtolower($wpdb->escape($tag)).'\'';
                    $tagtitle = $wpdb->get_row($q_tagtitle, ARRAY_A);

                    if ($tagtitle['tag_pagetitle']){
                        // a tag title exists, so use it
                        $title = $tagtitle['tag_pagetitle'];
                    }
                    elseif ($temp = get_seo_url_title($local_url))
                    {
                        $is_url_title = true;
                        $title = $temp;
                    } else {
                        // use the default
                        if (is_object($utw) && method_exists($utw, 'GetFormat')) {
                            $format = $utw->GetFormat('tagsettextonly', '');
                            $title = $utw->FormatTags($utw->GetCurrentTagSet(), $format, 0);
                        }
                    }
                }
                elseif ($temp = get_seo_url_title($local_url))
                {
                    $is_url_title = true;
                    $title = $temp;
                }
                else
                {
                    $format = $utw->GetFormat('tagsettextonly', '');
                    $title = $utw->FormatTags($utw->GetCurrentTagSet(), $format, 0);
                }
            }
            elseif (0 >= seo_title_tag_version_compare('2.3'))
            {
                $tags = explode(' ', $wp_query->query_vars['tag']);
                foreach (array_keys($tags) as $k) {
                    $sql = "SELECT
                                t.term_id
                            FROM
                                " . $wpdb->terms . " t INNER JOIN " . $wpdb->term_taxonomy . " tt
                                ON t.term_id = tt.term_id
                            WHERE
                                t.slug = '" . $wpdb->escape($tags[$k]) . "' AND
                                tt.taxonomy = 'post_tag'
                            LIMIT 1";

                    $temp = $wpdb->get_results($sql);
                    if (is_array($temp) && isset($temp[0])) {
                        $tags[$k] = $temp[0]->term_id;
                    } else {
                        unset($tags[$k]);
                    }
                }

                $temp_tag_title = '';

                if (is_array($tags) && 1 == count($tags)) {
                    $table_name = $wpdb->prefix . "seo_title_tag_tag";
                    $temp = $wpdb->get_results("SELECT title from " . $table_name . " where tag_id = " . $tags[0]);

                    if (is_array($temp) && isset($temp[0]))
                    {
                        $temp_tag_title = $temp[0]->title;
                    }
                }

                if (!empty($temp_tag_title))
                {
                    $title = $temp_tag_title;
                }
                elseif ($temp = get_seo_url_title($local_url))
                {
                    $is_url_title = true;
                    $title = $temp;
                }
                else
                {
                    $title = single_tag_title('',false);
                }
            }
            else
            {
                $format = $utw->GetFormat('tagsettextonly', '');
                $title = $utw->FormatTags($utw->GetCurrentTagSet(), $format, 0);
            }

        } elseif(is_404()) {
            if ($error_page_title)
            {
                $title = $error_page_title;
            }
            elseif ($temp = get_seo_url_title($local_url))
            {
                $is_url_title = true;
                $title = $temp;
            }
            else
            {
                $title = get_bloginfo('name');
            }
        }
        elseif ($temp = get_seo_url_title($local_url))
        {
            $is_url_title = true;
            $title = $temp;
        }
        else
        {
            $title = wp_title(' ', false);
            if(wp_title(' ', false) == ' ') {
                $separator = "";
            }
        }

        if($include_blog_name_in_titles)
        {
            if ($separator)
            {
                $title .= " $separator ";
            }

            if($short_blog_name)
            {
                $title .= $short_blog_name;
            }
            else
            {
                $title .= get_bloginfo('name');
            }
        }
        elseif(empty($title))
        {
            $title = get_bloginfo('name');  // this is so the page has a title, because otherwise it would have been untitled
        }
    }

    // if this is no url matched title we check if we are in paging mode and add the page number.
    if (! $is_url_title)
    {
        if (preg_match('/(paged=|page=|page\/)(\d+)/',$local_url,$matches))
        {
            $title .= ' ('.$matches[2].')';
        }
    }

    echo wp_specialchars(trim($title), true);
}

function seo_title_tag_options_page()
{
    if (function_exists('add_options_page'))
    {
        add_options_page('SEO Title Tag', 'SEO Title Tag', 10, basename(__FILE__), 'seo_title_tag_options_subpanel');
        add_management_page('Title Tags', 'Title Tags', 10, 'manage_seo_title_tags', 'manage_seo_title_tags');
    }
}

add_action('admin_menu', 'seo_title_tag_options_page');

function seo_title_tag_options_subpanel() {
    global $wp_version;

    if (isset($_POST['info_update'])) {
        if ($_POST['custom_title_key'] != "")  {
            update_option('custom_title_key',$_POST['custom_title_key']);
        }
        update_option('home_page_title',$_POST['home_page_title']);
        update_option('error_page_title',$_POST['error_page_title']);
        update_option('separator',$_POST['separator']);
        update_option('use_category_description_as_title',$_POST['use_category_description_as_title']);
        update_option('include_blog_name_in_titles',$_POST['include_blog_name_in_titles']);
        update_option('short_blog_name',$_POST['short_blog_name']);
        if (0 < seo_title_tag_version_compare('2.3')) {
            update_option('utw_opt_in', $_POST['utw_opt_in']);
        } else {
            update_option('utw_opt_in', false);
        }
        update_option("manage_elements_per_page", $_POST['manage_elements_per_page']);
        echo '<div class="updated"><p>Options saved.</p></div>';
    }
    if(get_option("custom_title_key")) {
        // the name of the custom title
        $custom_title_key = get_option("custom_title_key");
        $home_page_title = get_option("home_page_title");
        $home_page_title = htmlspecialchars(stripslashes($home_page_title));
        $error_page_title = get_option("error_page_title");
        $error_page_title = htmlspecialchars(stripslashes($error_page_title));
        $separator = get_option("separator");
        $separator = htmlspecialchars(stripslashes($separator));
        $use_category_description_as_title = get_option("use_category_description_as_title");
        // shall we always print out the blog name at the end of the title?
        $include_blog_name_in_titles = get_option("include_blog_name_in_titles");
        $short_blog_name = get_option("short_blog_name");
        $short_blog_name = htmlspecialchars(stripslashes($short_blog_name));
        // use UTW
        if (0 < seo_title_tag_version_compare('2.3')) {
            $utw_opt_in = get_option("utw_opt_in");
        } else {
            $utw_opt_in = false;
        }
        // how many elements do we show per page in the manage page
        $manage_elements_per_page = get_option("manage_elements_per_page");
    } else {
        $custom_title_key = "title_tag";
        $use_category_description_as_title = false;
        $include_blog_name_in_titles = false;
        $manage_elements_per_page = 20;
    };
 ?>

        <div class="wrap">
        <a href="http://www.netconcepts.com"><img width="233" height="36" alt="visit netconcepts" align="right" src="<?php echo get_option('siteurl'); ?>/wp-content/plugins/seo-title-tag/nclogo.jpg"/></a>
        <h2>SEO Title Tag Options</h2><div class="wrap">
        <form name="stto_main" method="post">
        <fieldset class="options">
        <table class="optiontable">
        <tr valign="top">
        <th scope="row">Key name for custom field:</th>
        <td><input name="custom_title_key" readonly value="<?php echo $custom_title_key; ?>" size="20" class="code" /></td>
        </tr>
        <tr valign="top">
        <th scope="row">Number of Posts per page in mass mode edit:</th>
        <td><input name="manage_elements_per_page" value="<?php echo $manage_elements_per_page; ?>" size="5" class="code" /></td>
        </tr>
        <tr valign="top"><?php if ('page' == get_option('show_on_front')) { ?>
        <th scope="row"><a href="<?php echo get_permalink(get_option('page_for_posts')); ?>">Posts Page</a> title tag (leave blank to use blog name):</th>
    <?php } else { ?>
        <th scope="row">Home page title tag (leave blank to use blog name):</th>
    <?php } ?>
        <td><input name="home_page_title" value="<?php echo $home_page_title; ?>" size="60" class="code" /></td>
        </tr>
        <tr valign="top">
        <th scope="row">404 Error title tag (leave blank to use blog name):</th>
        <td><input name="error_page_title" value="<?php echo $error_page_title; ?>" size="60" class="code" /></td>
        </tr>
        <tr valign="top">
        <th scope="row">Use category descriptions as titles on category pages:</th>
        <td>
        <label><input name="use_category_description_as_title"  type="radio" value="0"  <?php if(!$use_category_description_as_title) { echo 'checked="checked"'; } ?>
          /> No</label><br />
        <label><input name="use_category_description_as_title" type="radio" value="1" <?php if($use_category_description_as_title) { echo 'checked="checked"'; } ?>
          /> Yes</label>
        </td>
        </tr>
        <tr valign="top">
        <th scope="row">Include blog name in titles:</th>
        <td>
        <label><input name="include_blog_name_in_titles"  type="radio" value="0"  <?php if(!$include_blog_name_in_titles) { echo 'checked="checked"'; } ?>
          /> No</label><br />
        <label><input name="include_blog_name_in_titles" type="radio" value="1" <?php if($include_blog_name_in_titles) { echo 'checked="checked"'; } ?>
          /> Yes</label>
        </td>
        </tr>
        </table>
        </fieldset>
        <fieldset class="options">
        <h3>Complete the following if "Yes" selected above:</h3>
        <table class="optiontable">
        <tr valign="top">
        <th scope="row">
        Separator (leave blank to use "&raquo;"):</th>
        <td><input name="separator" value="<?php echo $separator; ?>" size="10" class="code" /></td>
        </tr>
        <tr valign="top">
        <th scope="row">Short blog name (overrides blog name in title tags):</th>
        <td><input name="short_blog_name" value="<?php echo $short_blog_name; ?>" size="60" class="code" /></td>
        </tr>
        </table>
        </fieldset>

        <?php if (0 < seo_title_tag_version_compare('2.3')): ?>

        <fieldset class="options">
        <h3>Do you wish to use SEO Title Tag in conjunction with <a href="http://www.neato.co.nz/ultimate-tag-warrior/" title="Ultimate Tag Warrior" target="_blank">Ultimate Tag Warrior</a>?:</h3>
        <table class="optiontable">
        <tr valign="top">
        <th scope="row">
        Yes, I want to use this for my UTW tag pages:</th>
        <td><input type="checkbox" name="utw_opt_in" value="1" class="code" <?php if($utw_opt_in){ echo "checked "; } ?>/>
                <?php if($utw_opt_in) { ?> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;<a href="edit.php?page=manage_seo_title_tags&title_tags_type=utw">Go to the management page for Tag page titles &raquo;</a><?php } ?></td>
        </tr>
        <tr>
                <td colspan="2" class="option-notes"><p><strong>Note:</strong> This will require you to have the <a href="http://www.neato.co.nz/ultimate-tag-warrior/" title="Ultimate Tag Warrior" target="_blank">Ultimate Tag Warrior</a> plugin installed and activated. It is strongly recommended that the URL rewriting option of UTW be turned on. It will give you the ability to add custom titles for when browsing individual tag pages (e.g. http://yoursite.com/tag/tagname).
                        If this option is selected, a separate management subtab called "<a href="edit.php?page=manage_seo_title_tags&title_tags_type=utw">UTW Tags</a>" will be added to the <a href="edit.php?page=manage_seo_title_tags">Title Tag management page</a> for maintaining the titles. Managing tag conjunction pages (e.g. http://yoursite.com/tag/tagname+anothertag) should be done via the <a href="edit.php?page=manage_seo_title_tags&title_tags_type=urls">URLs</a> subtab in the <a href="edit.php?page=manage_seo_title_tags">Title Tag management page</a>.</p></td>
        </tr>
        </table>
        </fieldset>

        <?php endif; ?>

        <p class="submit">
        <input type="hidden" name="action" value="update" />
        <input type="hidden" name="page_options" value="custom_title_key, home_page_title,separator,use_category_description_as_title,include_blog_name_in_titles,short_blog_name<?php echo ((0 < seo_title_tag_version_compare('2.3')) ? ',utw_opt_in' : ''); ?>"/>
        <input type="submit" name="info_update" value="<?php _e('Update Options', 'Localization name') ?> &raquo;" />
        </p>

        </form>
        </div>
<?php
}

// TODO: rebuild to use the dbDelta function
function install_utw_support() {
    global $wpdb, $tabletags;

    // check if utw is running
    if($tabletags) {

        // this is a bit of a dirty hack, but I couldn't find a better way of doing it.
        $column_query = "SELECT tag_pagetitle FROM " . $tabletags;
        $wpdb->hide_errors();
        $query = $wpdb->query($column_query);

        if (!$query) {
            // tag title column does not exist, so create it
            echo 'Field does not exist';
            $sql = 'ALTER TABLE ' . $tabletags . ' ADD tag_pagetitle varchar(255)';
            $wpdb->query($sql);
        }
    }

}

function seo_edit_page_form()
{
    global $post;

    $custom_title_value = get_post_meta($post->ID, get_option("custom_title_key"), true);

        ?>
        <fieldset id="seodiv" class="dbx-box">
        <h3 class="dbx-handle">Title Tag (optional)
        </h3>
        <div><input type="text" name="<?php echo get_option("custom_title_key") ?>" value="<?php echo wp_specialchars($custom_title_value, true) ?>" id="<?php echo get_option("custom_title_key") ?>" size="80" /></div><br />
<!--    <input name='updatemeta' type='submit' class='updatemeta' value='Update' /> -->
        </fieldset><br />
        <?php
}

function seo_update_title_tag($id)
{
    $value = $_POST[get_option("custom_title_key")];

    if(! empty($value))
    {
        $meta_value = update_post_meta($id, get_option("custom_title_key"), $value);

        if(! $meta_value)
        {
            add_post_meta($id, get_option("custom_title_key"), $value);
        }
    }
}

add_action('edit_post', 'seo_update_title_tag');
add_action('save_post', 'seo_update_title_tag');
add_action('publish_post', 'seo_update_title_tag');
add_action('edit_page_form', 'seo_edit_page_form');
add_action('edit_form_advanced', 'seo_edit_page_form');
add_action('simple_edit_form', 'seo_edit_page_form');

// This fixes how wordpress 2.3 only shows the first tag name when you view
// Taxonomy Intersections and Unions
if (0 >= seo_title_tag_version_compare('2.3'))
{
    function seo_title_tag_filter_single_tag_title($prefix = '', $display = true )
    {
        global $wp_query, $wpdb;

        $tags = explode(' ', str_replace(',', ' ,', $wp_query->query_vars['tag']));

        $tag_title = '';
        foreach (array_keys($tags) as $k) {
            if (0 == $k) {
                $prefix = '';
            } elseif (',' == $tags[$k][0]) {
                $prefix = ' or ';
                $tags[$k] = substr($tags[$k], 1);
            } else {
                $prefix = ' and ';
            }

            $sql = "SELECT
                        t.name
                    FROM
                        " . $wpdb->terms . " t INNER JOIN " . $wpdb->term_taxonomy . " tt
                        ON t.term_id = tt.term_id
                    WHERE
                        t.slug = '" . $wpdb->escape($tags[$k]) . "' AND
                        tt.taxonomy = 'post_tag'
                    LIMIT 1";

            $temp = $wpdb->get_results($sql);
            if (is_array($temp) && isset($temp[0])) {
                $tag_title .= $prefix . $temp[0]->name;
            }
        }

        return $tag_title;
    }

    add_filter('single_tag_title', 'seo_title_tag_filter_single_tag_title', 1, 2);
}

function manage_seo_title_tags()
{
    global $utw, $wpdb, $tabletags, $tablepost2tag, $install_directory, $wp_version;

    $search_value = '';
    $search_query_string = '';

    if (isset($_POST['action']) and ($_POST['action'] == 'pages'))
    {
        foreach ($_POST as $name => $value)
        {
            if(preg_match('/^tagtitle_(\d+)$/',$name,$matches))
            {
                $value = stripslashes(strip_tags($value));

                $meta_value = update_post_meta($matches[1], get_option("custom_title_key"), $value);

                if($meta_value != $value)
                {
                    add_post_meta($matches[1], get_option("custom_title_key"), $value);
                }

            }
        }

        echo '<div class="updated"><p>The custom page titles have been updated.</p></div>';
    }
    elseif (isset($_POST['action']) and ($_POST['action'] == 'posts'))
    {
        foreach ($_POST as $name => $value)
        {
            if(preg_match('/^tagtitle_(\d+)$/',$name,$matches))
            {
                $value = stripslashes(strip_tags($value));

                $meta_value = update_post_meta($matches[1], get_option("custom_title_key"), $value);

                if($meta_value != $value)
                {
                    add_post_meta($matches[1], get_option("custom_title_key"), $value);
                }
            }
        }

        echo '<div class="updated"><p>The custom post titles have been updated.</p></div>';
    }
    elseif (isset($_POST['action']) && ($_POST['action'] == 'categories'))
    {
        foreach ($_POST as $name => $value)
        {
            if(preg_match('/^title_(\d+)$/',$name,$matches))
            {
                $title = stripslashes(strip_tags($_POST['title_'.$matches[1]]));
                $title = $wpdb->escape($title);

                if (get_option("use_category_description_as_title"))
                {
                    if (0 < seo_title_tag_version_compare('2.3')) {
                        $table_name = $wpdb->prefix . "categories";
                        $temp = $wpdb->get_row("SELECT cat_ID from ".$table_name." where cat_ID = " . $matches[1]);

                        if ($temp->cat_ID == $matches[1])
                        {
                            $wpdb->query("UPDATE ".$table_name." SET category_description = '".$title."' where cat_ID = ".$matches[1]);
                        }
                    } else {
                        $temp = $wpdb->get_row("SELECT term_id from " . $wpdb->term_taxonomy . " where term_id = " . $matches[1]);

                        if ($temp->term_id == $matches[1])
                        {
                            $wpdb->query("UPDATE " . $wpdb->term_taxonomy . " SET description = '" . $title . "' where term_id = " . $matches[1]);
                        }
                    }
                }
                else
                {
                    $table_name = $wpdb->prefix . "seo_title_tag_category";
                    $temp = $wpdb->get_results("SELECT category_id from ".$table_name." where category_id = ".$matches[1]);
                    if (isset($temp[1]))
                    {
                        $wpdb->query("DELETE FROM ".$table_name." where category_id = ".$matches[1]);
                        unset($temp);
                    }
                    elseif (isset($temp[0]))
                    {
                        $temp = $temp[0];
                    }

                    if ((isset($temp)) and ($temp->category_id == $matches[1]) and (! empty($title)))
                    {
                        $wpdb->query("UPDATE ".$table_name." SET title = '".$title."' where category_id = ".$matches[1]);
                    }
                    elseif (! empty($title))
                    {
                        $wpdb->query("INSERT INTO ".$table_name." (category_id,title) values('".$matches[1]."','".$title."')");
                    }
                    else
                    {
                        $wpdb->query("DELETE FROM ".$table_name." where category_id = ".$matches[1]);
                    }
                }
            }
        }

        echo '<div class="updated"><p>The custom Category titles have been saved.</p></div>';
    }
    elseif (isset($_POST['action']) and ($_POST['action'] == 'urls'))
    {
        $table_name = $wpdb->prefix . "seo_title_tag_url";

        foreach ($_POST as $name => $value)
        {
            if(preg_match('/^url_(\d+)$/',$name,$matches))
            {
                $url = stripslashes($value);
                $url = $wpdb->escape($url);

                $title = stripslashes(strip_tags($_POST['title_'.$matches[1]]));
                $title = $wpdb->escape($title);

                if((! empty($url)) and (! empty($title)))
                {
                    $wpdb->query("UPDATE ".$table_name." SET url = '".$url."', title = '".$title."' where id = ".$matches[1]);
                }
                elseif(empty($url) and empty($title))
                {
                    $wpdb->query("DELETE FROM ".$table_name." where id = ".$matches[1]);
                }
            }
            elseif (preg_match('/^url_new_(\d+)$/',$name,$matches))
            {
                $url = stripslashes($value);
                $url = $wpdb->escape($url);

                $title = stripslashes(strip_tags($_POST['title_new_'.$matches[1]]));
                $title = $wpdb->escape($title);

                if((! empty($url)) and (! empty($title)))
                {
                    $wpdb->query("INSERT INTO ".$table_name." (url,title) values('".$url."','".$title."')");
                }
            }
        }

        echo '<div class="updated"><p>The custom URLs and URL titles have been saved.</p></div>';
    }
    elseif (isset($_POST['action']) and ($_POST['action'] == 'utw'))
    {
        foreach ($_POST as $name => $value)
        {
            if(preg_match('/^utw_(\d+)$/',$name,$matches))
            {
                $value = stripslashes(strip_tags($value));

                $wpdb->query("UPDATE ".$tabletags." SET tag_pagetitle = '".$wpdb->escape($value)."' where tag_ID = ".$matches[1]);
            }
        }

        echo '<div class="updated"><p>The custom titles have been updated.</p></div>';
    }
    elseif (isset($_POST['search_value']))
    {
        $search_value = $_POST['search_value'];
    }
    elseif (isset($_POST['action']) && ($_POST['action'] == 'tags'))
    {
        foreach ($_POST as $name => $value)
        {
            if(preg_match('/^title_(\d+)$/',$name,$matches))
            {
                $title = stripslashes(strip_tags($_POST['title_'.$matches[1]]));
                $title = $wpdb->escape($title);

                $table_name = $wpdb->prefix . "seo_title_tag_tag";
                $temp = $wpdb->get_results("SELECT tag_id from " . $table_name . " where tag_id = " . $matches[1]);
                if (isset($temp[1]))
                {
                    $wpdb->query("DELETE FROM " . $table_name ." where tag_id = " . $matches[1]);
                    unset($temp);
                }
                elseif (isset($temp[0]))
                {
                    $temp = $temp[0];
                }

                if ((isset($temp)) and ($temp->tag_id == $matches[1]) and (! empty($title)))
                {
                    $wpdb->query("UPDATE " . $table_name . " SET title = '" . $title . "' where tag_id = " . $matches[1]);
                }
                elseif (!empty($title))
                {
                    $wpdb->query("INSERT INTO " . $table_name . " (tag_id, title) values ('" . $matches[1] . "', '" . $title . "')");
                }
                else
                {
                    $wpdb->query("DELETE FROM " . $table_name . " where tag_id = " . $matches[1]);
                }
            }
        }

        echo '<div class="updated"><p>The custom Tag titles have been saved.</p></div>';
    }

    if (! isset($_POST['search_value']))
    {
        $search_value = $_GET['search_value'];
    }

    $title_tags_type = $_GET['title_tags_type'];
    $page_no = $_GET['page_no'];
    $manage_elements_per_page = get_option("manage_elements_per_page");
    $element_count = 0;

    if(empty($manage_elements_per_page))
    {
        $manage_elements_per_page = 15;
    }

    $_SERVER['QUERY_STRING'] = preg_replace('/&title_tags_type=[^&]+/','',$_SERVER['QUERY_STRING']);
    $_SERVER['QUERY_STRING'] = preg_replace('/&page_no=[^&]+/','',$_SERVER['QUERY_STRING']);
    $_SERVER['QUERY_STRING'] = preg_replace('/&search_value=[^&]*/','',$_SERVER['QUERY_STRING']);
    $search_query_string = '&search_value='.$search_value;

    if (!$page_no)
    {
        $page_no = 0;
    }

    //do the nav menu items for the subsubmenu
    print '<ul id="subsubmenu">';
    print '<li '.is_current($_REQUEST['title_tags_type'],'pages').'><a href="edit.php?'.$_SERVER['QUERY_STRING'].'&title_tags_type=pages">Pages</a></li>';
    print '<li '.is_current($_REQUEST['title_tags_type'],'posts').'><a href="edit.php?'.$_SERVER['QUERY_STRING'].'&title_tags_type=posts">Posts</a></li>';
    print '<li '.is_current($_REQUEST['title_tags_type'],'categories').'><a href="edit.php?'.$_SERVER['QUERY_STRING'].'&title_tags_type=categories">Categories</a></li>';
    print '<li '.is_current($_REQUEST['title_tags_type'],'urls').'><a href="edit.php?'.$_SERVER['QUERY_STRING'].'&title_tags_type=urls">URLs</a></li>';

    if (get_option("utw_opt_in") && (0 < seo_title_tag_version_compare('2.3')))
    {
        if(function_exists('is_tag'))
        {
            // install required table column if not already added
            install_utw_support();
            print '<li '.is_current($_REQUEST['title_tags_type'],'utw').
            '><a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].
            '&title_tags_type=utw">UTW Tags</a></li>';
        }
    } elseif (0 >= seo_title_tag_version_compare('2.3')) {
        print '<li '.is_current($_REQUEST['title_tags_type'],'tags').'><a href="edit.php?'.$_SERVER['QUERY_STRING'].'&title_tags_type=tags">Tags</a></li>';
    }

    print '</ul>';

        ?>

        <div class="wrap"><div><a href="http://www.netconcepts.com"><img width="233" height="36" alt="visit netconcepts" align="right" src="<?php echo get_option('siteurl'); ?>/wp-content/plugins/seo-title-tag/nclogo.jpg" /></a></div>
        <h2>SEO Title Tags</h2>

        <p><a href="options-general.php?page=seo-title-tag.php">Edit main SEO Title plugin options &raquo;</a></p>
        <br />

        <fieldset class="options"><legend>Edit title tags</legend>

        <form name="searchform" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                <fieldset>
                <input type="text" name="search_value" value="<?php if (isset($search_value)) echo wp_specialchars($search_value, true); ?>" size="17" />
                <input type="submit" name="submit" value="<?php _e('Search') ?>"  />
                </fieldset>
        </form>
        <?php

        if((empty($title_tags_type)) or ($title_tags_type == 'pages'))
        {
                ?>
                <p>Use the form below to enter or update a custom page title.<br /></p>
                <?php
                $pages = get_pages( 'sort_column=menu_order' );

                if (!empty($search_value))
                {
                    $new_pages = array();

                    foreach ($pages as $page)
                    {
                        if (preg_match('/'.$search_value.'/',$page->post_title))
                        {
                            array_push($new_pages, $page);
                        }
                        else
                        {
                            $page_custom = get_post_custom($page->ID);

                            if (preg_match('/'.$search_value.'/',$page_custom[get_option("custom_title_key")][0])
                            || preg_match('/'.$search_value.'/',$page->post_content)
                            || preg_match('/'.$search_value.'/',$page->post_cexcerpt)
                            )
                            {
                                array_push($new_pages, $page);
                            }
                        }
                    }

                    $pages = $new_pages;
                }

                $element_count = count($pages);

                if (($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no)))
                {
                    if ($page_no > 0)
                    {
                        $pages = array_splice($pages, ($page_no * $manage_elements_per_page));
                    }

                    $pages = array_slice($pages, 0, $manage_elements_per_page);
                }

                if ($pages)
                {
                        ?>
                        <form name="pages-form" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                        <input type="hidden" name="action" value="pages" />
                        <table class="widefat">
                        <thead>
                        <tr>
                        <th scope="col">ID</th>
                        <th scope="col">Title</th>
                        <th scope="col">Custom Title</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php

                        if ((($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no))) or (! empty($search_value)))
                        {
                            manage_seo_title_tags_recursive('pages',0,0,$pages,false);
                        }
                        else
                        {
                            manage_seo_title_tags_recursive('pages',0,0,$pages);
                        }

                        echo '</tbody></table><br /><input type="submit" value="Submit" /></form>';
                }
                else
                {
                    echo '<p><b>No pages found!</b></p>';
                }
        }
        elseif ($title_tags_type == 'posts')
        {
                ?>
                <p>Use the form below to enter or update a custom post title.<br /></p>
                <?php

                if (0 > seo_title_tag_version_compare('2.1')) {
                    $posts = get_posts('numberposts=all&orderby=post_date&order=DESC');
                } elseif (0 > seo_title_tag_version_compare('2.0')) {
                    $posts = get_posts('numberposts=' . $manage_elements_per_page . '&orderby=post_date&order=DESC');
                }

                if ((empty($posts)) or (count($posts) < 1))
                {
                    $posts = $wpdb->get_results('SELECT * FROM '.$wpdb->posts.' ORDER BY post_date DESC');
                    $new_posts;

                    foreach ($posts as $post)
                    {
                        if (isset($post->post_type) and ($post->post_type != 'post'))
                        {
                            continue;
                        }

                        $new_posts[] = $post;
                    }

                    $posts = $new_posts;
                }

                if (!empty($search_value))
                {
                    $new_posts = array();

                    foreach ($posts as $post)
                    {
                        if (preg_match('/'.$search_value.'/',$post->post_title))
                        {
                            array_push($new_posts, $post);
                        }
                        else
                        {
                            $post_custom = get_post_custom($post->ID);

                            if (preg_match('/'.$search_value.'/',$post_custom[get_option("custom_title_key")][0])
                            || preg_match('/'.$search_value.'/',$post->post_content)
                            || preg_match('/'.$search_value.'/',$post->post_excerpt))
                            {
                                array_push($new_posts, $post);
                            }
                        }
                    }

                    $posts = $new_posts;
                }

                $element_count = count($posts);

                if (($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no)))
                {
                    if($page_no > 0)
                    {
                        $posts = array_splice($posts, ($page_no * $manage_elements_per_page));
                    }

                    $posts = array_slice($posts, 0, $manage_elements_per_page);
                }

                if ($posts)
                {
                        ?>
                        <form name="posts-form" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                        <input type="hidden" name="action" value="posts" />
                        <table class="widefat">
                        <thead>
                        <tr>
                        <th scope="col">ID</th>
                        <th scope="col">Title</th>
                        <th scope="col">Custom Title</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        manage_seo_title_tags_recursive('posts',0,0,$posts);

                        echo '</table><br /><input type="submit" value="Submit" /></form>';
                }
                else
                {
                    echo '<p><b>No posts found!</b></p>';
                }
        }
        elseif ($title_tags_type == 'categories')
        {

                ?>
                <p>Use the form below to enter or update a custom Category title.<br /></p>
                <?php
                // replaced because this seems to be only valid in WP 2.1
                //$categories = get_categories( 'hide_empty=0' );
                $categories = seo_title_tag_get_categories();
                $table_name = $wpdb->prefix . "seo_title_tag_category";
                $category_titles;

                if (get_option("use_category_description_as_title"))
                {
                    foreach ($categories as $category)
                    {
                        $category_titles[$category->cat_ID] = $category->category_description;
                    }
                }
                elseif (!empty($search_value))
                {
                    $sql = 'SELECT * from ' . $table_name
                         . ' WHERE title LIKE "%' . $wpdb->escape($search_value) . '%" ';
                        // OR wp_posts LIKE "%'.$wpdb->escape($search_value).'%"';

                    $category_titles = $wpdb->get_results($sql);

                    $category_titles_new = array();

                    foreach ($category_titles as $category_title)
                    {
                        $category_titles_new[$category_title->category_id] = $category_title->title;
                    }

                    // lets rebuild the categories killing all items that don't have this category ID
                    if (count($category_titles_new) > 0) {
                        foreach($categories as $key => $value)
                        {
                            if (!isset($category_titles_new[$value->cat_ID])) {
                                unset($categories[$key]);
                            }
                        }
                    } else {
                        $categories = array();
                    }

                    $category_titles = $category_titles_new;
                }
                else
                {
                    // defult filling of the category titles field.
                    $sql = 'SELECT category_id, title from ' . $table_name;

                    $category_titles = $wpdb->get_results($sql);

                    $category_titles_new = array();

                    if ($category_titles)
                    {
                        foreach ($category_titles as $category_title)
                        {
                            $category_titles_new[$category_title->category_id] = $category_title->title;
                        }

                        $category_titles = $category_titles_new;
                    }

                }

                $element_count = count($categories);

                if (($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no)))
                {
                    if($page_no > 0)
                    {
                        $categories = array_splice($categories, ($page_no * $manage_elements_per_page));
                    }

                    $categories = array_slice($categories, 0, $manage_elements_per_page);
                }

                if($categories) {
                ?>
                <form name="categories-form" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                <input type="hidden" name="action" value="categories" />
                <table class="widefat">
                <thead>
                <tr>
                <th scope="col">ID</th>
                <th scope="col">Category</th>
                <th scope="col">Custom Title</th>
                </tr>
                </thead>
                <tbody>
                <?php

                foreach ($categories as $category)
                {
                        $category_value = $category_titles[$category->cat_ID];

                        if (get_magic_quotes_runtime())
                        {
                            $category_value = stripslashes($category_value);
                        }
                        ?>
                        <tr>
                        <td><a href="<?php echo get_category_link($category->cat_ID) ?>"><?php echo $category->cat_ID ?></a></td>
                        <td><?php echo $category->cat_name ?></td>
                        <td><input type="text" name="title_<?php echo $category->cat_ID ?>" value="<?php echo wp_specialchars($category_value, true); ?>" size="70" /></td>
                        <?php
                }

                echo '</table><br /><input type="submit" value="Submit" /></form>';

                } else { //End of check for categories
                    print "<b>No Categories found!</b>";
                }
        }
        elseif ($title_tags_type == 'urls')
        {
                ?>
                <p>Use the form below to enter or update a title tag for any URL, including archives pages, tag conjunction pages, etc.</p><p>In the URL field, leave off the http:// and your domain and your blog's directory (if you have one). e.g. <i>tag/seo+articles</i> is okay; <i>http://www.netconcepts.com/tag/seo+articles</i> is NOT.<br /></p>
                <?php
                $table_name = $wpdb->prefix . "seo_title_tag_url";
                $urls;

                $sql = 'SELECT id, url, title from '.$table_name;

                if(! empty($search_value))
                {
                    $sql .= ' WHERE url LIKE "%'.$wpdb->escape($search_value).'%" OR title LIKE "%'.$wpdb->escape($search_value).'%"';
                }

                $sql .= ' ORDER BY title';

                $urls = $wpdb->get_results($sql);

                $element_count = count($urls);

                if (($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no)))
                {
                    if($page_no > 0)
                    {
                        $urls = array_splice($urls, ($page_no * $manage_elements_per_page));
                    }

                    $urls = array_slice($urls, 0, $manage_elements_per_page);
                }

                ?>
                <form name="urls-form" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                <input type="hidden" name="action" value="urls" />
                <table class="widefat">
                <thead>
                <tr>
                <th scope="col">ID</th>
                <th scope="col">URL</th>
                <th scope="col">Custom Title</th>
                </tr>
                </thead>
                <tbody>
                <?php

                if (is_array($urls))
                {
                    foreach ($urls as $url)
                    {
                        $url_value = $url->title;

                        if (get_magic_quotes_runtime())
                        {
                            $url_value = stripslashes($url_value);
                        }
                        ?>
                        <tr>
                        <td><a href="/<?php echo preg_replace('/^\//','',$url->url) ?>"><?php echo $url->id ?></a></td>
                        <td><input type="text" title="<?php echo wp_specialchars($url->url, true) ?>" name="url_<?php echo $url->id ?>" value="<?php echo wp_specialchars($url->url, true) ?>" size="40" /></td>
                        <td><input type="text" title="<?php echo wp_specialchars($url->title, true) ?>" name="title_<?php echo $url->id ?>" value="<?php echo wp_specialchars($url_value, true); ?>" size="70" /></td>
                        <?php
                    }
                }

                for ($n = 0;$n < 5;$n++)
                {
                        ?>
                        <tr>
                        <td>New (<?php echo ($n + 1) ?>)</td>
                        <td><input type="text" name="url_new_<?php echo $n ?>" value="" size="40" /></td>
                        <td><input type="text" name="title_new_<?php echo $n ?>" value="" size="70" /></td>
                        <?php
                }

                echo '</table><br /><input type="submit" value="Submit" /></form>';
        }
        elseif ($title_tags_type == 'utw')
        {
                ?>
                <p>Use the form below to enter or update a custom UTW Tag title.<br /></p>
                <?php
                $sql = 'SELECT tag_ID,tag,tag_pagetitle FROM '.$tabletags;

                if(! empty($search_value))
                {
                    $sql .= ' WHERE tag LIKE "%'.$wpdb->escape($search_value).'%" OR tag_pagetitle LIKE "%'.$wpdb->escape($search_value).'%"';
                }

                $sql .= ' ORDER BY tag';

                $tags = $wpdb->get_results($sql);

                $element_count = count($tags);

                if (($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no)))
                {
                    if($page_no > 0)
                    {
                        $tags = array_splice($tags, ($page_no * $manage_elements_per_page));
                    }

                    $tags = array_slice($tags, 0, $manage_elements_per_page);
                }

                ?>
                <form name="utw-form" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                <input type="hidden" name="action" value="utw" />
                <table class="widefat">
                <thead>
                <tr>
                <th scope="col">ID</th>
                <th scope="col">UTW Tag</th>
                <th scope="col">Custom Title</th>
                </tr>
                </thead>
                <tbody>
                <?php

                foreach ($tags as $tag)
                {
                        $tag_value = $tag->tag_pagetitle;

                        if (get_magic_quotes_runtime())
                        {
                            $tag_value = stripslashes($tag_value);
                        }
                        ?>
                        <tr>
                        <td><a href="<?php echo $utw->FormatTag($tag, "%tagurl%") ?>"><?php echo $tag->tag_ID ?></a></td>
                        <td><?php echo $utw->FormatTag($tag, "%tagdisplay%") ?></td>
                        <td><input type="text" name="utw_<?php echo $tag->tag_ID ?>" value="<?php echo wp_specialchars($tag_value, true) ?>" size="70" /></td>
                        <?php
                }

                echo '</table><br /><input type="submit" value="Submit" /></form>';
        }
        elseif ($title_tags_type == 'tags')
        {

                ?>
                <p>Use the form below to enter or update a custom Tag title.<br /></p>
                <?php
                $tags = seo_title_tag_get_tags();
                $table_name = $wpdb->prefix . "seo_title_tag_tag";
                $tag_titles = array();

                if (!empty($search_value))
                {
                    $sql = 'SELECT * from ' . $table_name
                         . ' WHERE title LIKE "%' . $wpdb->escape($search_value) . '%" ';

                    $tag_titles = $wpdb->get_results($sql);

                    $tag_titles_new = array();

                    foreach ($tag_titles as $tag_title)
                    {
                        $tag_titles_new[$tag_title->tag_id] = $tag_title->title;
                    }

                    // lets rebuild the tags killing all items that don't have this tag ID
                    if (count($tag_titles_new) > 0) {
                        foreach($tags as $key => $value)
                        {
                            if (!isset($tag_titles_new[$value->term_id])) {
                                unset($tags[$key]);
                            }
                        }
                    } else {
                        $tags = array();
                    }

                    $tag_titles = $tag_titles_new;
                }
                else
                {
                    // defult filling of the category titles field.
                    $sql = 'SELECT tag_id, title from ' . $table_name;

                    $tag_titles = $wpdb->get_results($sql);

                    $tag_titles_new = array();

                    if ($tag_titles)
                    {
                        foreach ($tag_titles as $tag_title)
                        {
                            $tag_titles_new[$tag_title->tag_id] = $tag_title->title;
                        }

                        $tag_titles = $tag_titles_new;
                    }

                }

                $element_count = count($tags);

                if (($element_count > $manage_elements_per_page) and (($page_no != 'all') or empty($page_no)))
                {
                    if($page_no > 0)
                    {
                        $tags = array_splice($tags, ($page_no * $manage_elements_per_page));
                    }

                    $tags = array_slice($tags, 0, $manage_elements_per_page);
                }

                if($tags) {
                ?>
                <form name="tags-form" action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
                <input type="hidden" name="action" value="tags" />
                <table class="widefat">
                <thead>
                <tr>
                <th scope="col">ID</th>
                <th scope="col">Tag</th>
                <th scope="col">Custom Title</th>
                </tr>
                </thead>
                <tbody>
                <?php

                foreach ($tags as $tag)
                {
                        $tag_value = $tag_titles[$tag->term_id];

                        if (get_magic_quotes_runtime())
                        {
                            $tag_value = stripslashes($tag_value);
                        }
                        ?>
                        <tr>
                        <td><a href="<?php echo get_tag_link($tag->term_id) ?>"><?php echo $tag->term_id ?></a></td>
                        <td><?php echo $tag->name ?></td>
                        <td><input type="text" name="title_<?php echo $tag->term_id ?>" value="<?php echo wp_specialchars($tag_value, true); ?>" size="70" /></td>
                        <?php
                }

                echo '</table><br /><input type="submit" value="Submit" /></form>';

                } else { //End of check for tags
                    print "<b>No Tags found!</b>";
                }
        }
        else
        {
            echo '<p>unknown title tags type!</p>';
        }

        ?>

        </fieldset>

        <?php
        if($element_count > $manage_elements_per_page)
        {
            if(($page_no == 'all') and (! empty($page_no)))
            {
                echo 'View All&nbsp;&nbsp;';
            }
            else
            {
                echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&page_no=all&title_tags_type='.$title_tags_type.$search_query_string.'">View All</a>&nbsp;&nbsp;';
            }
        }

        if($element_count > $manage_elements_per_page)
        {
            for ($p = 0; $p < (int) ceil($element_count / $manage_elements_per_page); $p++)
            {
                if ($page_no == $p)
                {
                    echo ($p + 1).'&nbsp;';
                }
                else
                {
                    echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&page_no='.$p.'&title_tags_type='.$title_tags_type.$search_query_string.'">'.($p + 1).'</a> ';
                }
            }
        }
        ?>
        </div>
        <?php
}

function manage_seo_title_tags_recursive($type, $parent = 0, $level = 0, $elements = 0, $hierarchical = true)
{
    if (! $elements)
    {
        return;
    }

    foreach($elements as $element)
    {
        if (($element->post_parent != $parent) and $hierarchical)
        {
            continue;
        }

        $element_custom = get_post_custom($element->ID);

        //if(! empty($element_custom[get_option("custom_title_key")][0]))
        //{
        //}

        $pad = str_repeat( '&#8212; ', $level );
        $element_value = $element_custom[get_option("custom_title_key")][0];

        if (get_magic_quotes_runtime())
        {
            $element_value = stripslashes($element_value);
        }
                ?>
                <tr>
                <td><a href="<?php echo get_permalink($element->ID) ?>"><?php echo $element->ID ?></a></td>
                <td><?php echo $pad.$element->post_title ?></td>
                <td><input type="text" title="<?php echo wp_specialchars($element->post_title, true) ?>" name="tagtitle_<?php echo $element->ID ?>" id="tagtitle_<?php echo $element->ID ?>" value="<?php echo wp_specialchars($element_value, true); ?>" size="80" /></td>
                <!-- <td><?php //echo $element->post_type ?></td> -->
                <?php

                if ($hierarchical)
                {
                    manage_seo_title_tags_recursive($type, $element->ID,$level + 1, $elements);
                }
    }
}

// returns class=current if the strings exist and match else nothing.
// Used down on the top nav to select which page is selected.
function is_current($aRequestVar,$aType) {
    if(!isset($aRequestVar) || empty($aRequestVar)) { return; }
    //do the match
    if($aRequestVar == $aType) { return 'class=current'; }
}

// Returns < 0 if test version is less than wp version
//         > 0 if test version is greater than wp version
//         and 0 if they are equal.
function seo_title_tag_version_compare($test_version)
{
    $wp_version = get_bloginfo('version');
    return version_compare($test_version, $wp_version);
    /*
    $a_test_version = explode('.', $test_version);

    $wp_version = get_bloginfo('version');
    $a_wp_version = explode('.', $wp_version);

    $subvs = (count($a_test_version) > count($a_wp_version) ? count($a_test_version) : count($a_wp_version));

    for ($i = 0; $i < $subvs; $i++) {
        if (empty($a_test_version[$i])) {
            $a_test_version[$i] = 0;
        }

        if (empty($a_wp_version[$i])) {
            $a_wp_version[$i] = 0;
        }

        if ($a_test_version[$i] < $a_wp_version[$i]) {
            return -1;
        } elseif ($a_test_version[$i] > $a_wp_version[$i]) {
            return 1;
        }
    }

    return 0;
    */
}
?>
