<?php
/*
Plugin Name: Terong Related Links
Plugin URI: http://erwin.terong.com/2005/09/24/wp-plugin-related-posts-link/
Description: This plugin will help you displaying related permalinks. This plugin has been tested in WP 1.5.1.3
Author: Erwin Kodiat
Version: 1.1c
Author URI: http://www.terong.com/
*/

//option variables
$paging = 15;
$req_user_level = 1;
$sort_field = 'ID';
$sort_type = 'ASC';
$is_quicktags = true;

if(isset($_GET['is_popup']) && $_GET['is_popup']=='yes') {
    require("../../wp-blog-header.php");
    auth_redirect();
    if($userdata->user_level < $req_user_level) {
        print("Du hast keine Berechtigung fuer diese Aktion.");
        exit;
    }

    function get_posts_list() {
        global $wpdb, $paging, $sort_field, $sort_type;
        $current_post_id = $_GET['current_post_id'];

        if(isset($_GET['all_link']) && $_GET['all_link']=='yes') {
            //View all related links
            $searches = get_related_ids($current_post_id);
            $str .= "<p><a href='$_SERVER[PHP_SELF]?is_popup=yes&current_post_id=$current_post_id'>Aehnliche Links verwalten.</a></p>";
            $str .= "<table style='width: 700px;'>\n";
            $str .= "<tr><th scope='col'>Post ID</th><th scope='col'>Post Titel</th></tr>\n";
            $no = 1;
            foreach($searches as $s) {
                $c = $no % 2 == 1?" class='alternate'":"";
                $str .= "<tr$c><td>$s->ID</th><td><a href='".get_permalink($s->ID)."'>$s->post_title</a></td></tr>\n";
                $no++;
            }
            $str .= "</table>";
        }
        else {
            //display form and list of all posts
            $str = ""; //string to return
            $pg = isset($_GET['pg'])?$_GET['pg']:1;
            $offset = ($pg - 1) * $paging;
            $search_query = isset($_GET['s'])?$_GET['s']:"";

            if(isset($_POST['action']) && $_POST['action'] == "Update") {
                //handle update submission
                unset($_POST['action']); extract($_POST);
                $id = array_flip($id);
                $form_ids = array_flip(explode(",", $all_ids));
                foreach($form_ids as $k=>$a) $form_ids[$k] = isset($id[$k]);

                //get all related ids from db
                $searches = get_related_ids($current_post_id);
                $db_ids = $ignore_db_ids = array();
                if($searches) foreach($searches as $s) {
                    if(isset($form_ids[$s->ID])) $db_ids[$s->ID] = 1;
                    elseif($s->ID!=$current_post_id) $ignore_db_ids[$s->ID] = 1; //need to be inserted again
                }

                //delete all related data from db;
                $sql = "DELETE FROM $wpdb->postmeta WHERE post_id=$current_post_id AND meta_key IN ('related_id', 'related_post_name')";
                $wpdb->query($sql);

                $insert_ids = array();
                foreach($form_ids as $k=>$f) {
                    if(isset($db_ids[$k]) && ($f && $db_ids[$k])) $insert_ids[] = $k;
                    elseif($f)  $insert_ids[] = $k;
                }
                foreach($ignore_db_ids as $k=>$f)  $insert_ids[] = $k;

                //insert to database
                $sql = "INSERT INTO $wpdb->postmeta SET post_id=$current_post_id, meta_key='related_id', meta_value='".implode(",", $insert_ids)."'";
                $wpdb->query($sql);

                //$str .= "\n<script type=\"text/javascript\">\n<!--\n";
                //$str .= "window.opener.location.reload();\n";
                //$str .= "\n-->\n</script>\n";
            }

            //get all related links post ID
            $searches = get_related_ids($current_post_id);

            //and put them into an array
            $related_ids = array();
            if($searches) foreach($searches as $s) $related_ids[$s->ID] = 1;

            //remove ID if it is current post ID
            if(isset($related_ids[$current_post_id])) unset($related_ids[$current_post_id]);

            //get all posts limited by paging
            $additional_search_query = $search_query!=""?" AND (p.post_title LIKE '%$search_query%' OR p.post_content LIKE '%$search_query%' OR p.post_excerpt LIKE '%$search_query%')":"";
            $sql = "SELECT p.ID, p.post_title FROM $wpdb->posts p WHERE p.post_status='publish' AND p.ID!=$current_post_id $additional_search_query ORDER BY p.{$sort_field} $sort_type LIMIT $offset, $paging";
            $searches = $wpdb->get_results($sql);

            //search form
            $str .= "<form name=\"searchform\" action=\"$_SERVER[PHP_SELF]?$_SERVER[QUERY_STRING]\" method=\"get\">";
            $str .= "  <fieldset>";
            $str .= "  <legend>Suche Posts&hellip;</legend>";
            $str .= "  <input type=\"text\" name=\"s\" value=\"".(isset($_GET['s'])?$_GET['s']:"")."\" size=\"17\" />";
            $str .= "  <input type=\"submit\" value=\"Suche\"  />";
            if(isset($_GET['s'])) $str .= "  &raquo; <a href='$_SERVER[PHP_SELF]?is_popup=yes&current_post_id=$current_post_id'>Alle Posts ansehen.</a>";
            $str .= "  </fieldset>";
            $str .= "<div><input type='hidden' name='current_post_id' value='$_GET[current_post_id]' /></div>";
            $str .= "<div><input type='hidden' name='is_popup' value='yes' /></div>";
            $str .= "</form>";
            $str .= "<p>1. Auswahl treffen oder Auswahl aufheben. 2. Update Button klicken. 3. Weiterblaettern. 4. Fenster schlieszen. Fertig!<br /><br /><a href='$_SERVER[PHP_SELF]?all_link=yes&is_popup=yes&current_post_id=$current_post_id'>Alle aehnlichen Posts ansehen.</a></p>";

            //display to html
            $str .= "<form name=\"select_id\" action=\"$_SERVER[PHP_SELF]?$_SERVER[QUERY_STRING]\" method=\"post\">\n";
            $str .= "<table style='width: 700px;'>\n";
            $str .= "<tr><th scope='col'>Auswahl</th><th scope='col'>Post ID</th><th scope='col'>Post Titel</th></tr>\n";
            $no = 1;
            $js_old_ids = array(); //javascript variables
            $current_page_ids = array();
            if($searches) foreach($searches as $s) {
                $current_page_ids[] = $s->ID;
                $c = $no % 2 == 1?" class='alternate'":"";
                $checked = isset($related_ids[$s->ID])?" checked='checked'":"";
                if(isset($related_ids[$s->ID])) $js_old_ids[] = $s->ID;
                $str .= "<tr$c><td align=\"center\"><input type='checkbox' name=\"id[]\" value='$s->ID' $checked /></td><td>$s->ID</th><td><a href='".get_permalink($s->ID)."'>$s->post_title</a></td></tr>\n";
                $no++;
            }
            $str .= "</table>\n";

            //navigation ...
            $current_page = $pg;
            $num_posts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts p WHERE p.post_status='publish' $additional_search_query");
            $last_page = ceil($num_posts / $paging);
            $search_qs = $search_query!=""?"&s=".urlencode($search_query):"";
            $str_prev = $pg > 1?"<a href=\"$_SERVER[PHP_SELF]?is_popup=yes&current_post_id=".$_GET['current_post_id']."&pg=".($current_page-1)."$search_qs\" onclick=\"return checkInput(forms['select_id'])\">&laquo; vorherige Seite</a>":"";
            $str_next = $pg < $last_page?"<a href=\"$_SERVER[PHP_SELF]?is_popup=yes&current_post_id=".$_GET['current_post_id']."&pg=".($current_page+1)."$search_qs\" onclick=\"return checkInput(forms['select_id'])\">naechste Seite &raquo;</a>":"";
            $str .= "<div class=\"navigation\">";
            $str .= "<div class=\"alignleft\">$str_prev</div>";
            $str .= "<div class=\"alignright\">$str_next</div>";
            $str .= "</div>";

            //form button
            $str .= "<p class='submit'><input type='submit' name='action' value='Update' /></p>";

            //hidden values
            $str .= "<div><input type='hidden' name='all_ids' value='".implode(",", $current_page_ids)."' /></div>";
            $str .= "</form>\n";

            //writing JavaScript code
            if(count($js_old_ids) > 0) {
                $str .= "\n<script type=\"text/javascript\">\n<!--\n";
                foreach($js_old_ids as $js) $str .= "old_ids[old_ids.length] = $js;\n";
                $str .= "\n-->\n</script>\n";
            }
        }

        return $str;
    }
    printf (<<<EOF
<html>
<head>
<title>&rsaquo; Terong Related Links</title>
<link rel="stylesheet" href="../../wp-admin/wp-admin.css?version=1.5.1.3" type="text/css" />
<meta http-equiv="Content-Type" content="%s; charset=%s" />
<script type="text/javascript">
<!--
var old_ids = new Array;

function checkInput(f) {
    var new_ids = new Array;
    for(i=0; i < f.elements.length; i++) if(f.elements[i].type=='checkbox' && f.elements[i].checked) new_ids[new_ids.length] = f.elements[i].value;
    if(old_ids.toString() != new_ids.toString()) return confirm("Aenderungen verwerfen?");
}
-->
</script>
</head>
<body>
<div class="wrap">
<p class='submit'><input type='button' value='schliesze das Fenster' onclick='self.close();window.opener.location.reload()' /></p>
%s
</div>
</body>
</html>
EOF
, get_option('html_type'), get_option('blog_charset'), get_posts_list());
    exit;
}


function terong_add_quicktags() {
    global $is_quicktags, $pagenow;
    if($pagenow=="post.php" && isset($_GET['action']) && $_GET['action']=='edit') {
        ?>
        <script language="JavaScript" type="text/javascript">
        <!--
        function modal_dialog_show(url, width, height) {
            if (typeof(window.showModalDialog) != 'undefined')
        		window.showModalDialog(url, window, "dialogWidth:" + width + "px;dialogHeight:" + height + "px;edge:Raised;center:Yes;help:No;resizable:No;");
        	else {
                var left = screen.availWidth/2 - width/2;
                var top = screen.availHeight/2 - height/2;
                activeModalWin = window.open(url, "", "width="+width+"px,height="+height+",left="+left+",top="+top);
                window.onfocus = function(){if(activeModalWin.closed == false){activeModalWin.focus();};};
            }
        }
        //-->
        </script>
        <?
        if($is_quicktags) {
        ?>
        <script language="JavaScript" type="text/javascript">
        <!--
    	var obj;
    	if (obj = document.getElementById('ed_toolbar'))
    	    obj.innerHTML += '<input type="button" class="ed_button" value="Aehnliche Artikel" onclick="terong_open_window();"/>';

        function terong_open_window() {
            strFileName = "../wp-content/plugins/terong_related.php?is_popup=yes&current_post_id=<?php echo($_GET[post]); ?>";
            terong_win = modal_dialog_show(strFileName, 800, 600);
        }

        //-->
        </script>
        <?php
        }
        else {
            echo "<div id='top_right_link' style='position: absolute; top: 3px; right: 3px;'><a href='' onclick='modal_dialog_show(\"../wp-content/plugins/terong_related.php?is_popup=yes&current_post_id=$_GET[post]\", 800, 600)'>&raquo; Aehnliche Links</a></div>";
        }
    }
}

add_action('admin_footer', 'terong_add_quicktags');

function terong_related($text="") {
    if(is_single()) {
        global $wpdb, $post;
        $searches = get_related_ids($post->ID);
        if($searches) {
            $text .= "<div class=\"aehnliche\">";
            $text .= "<span>&#196;hnliche Artikel:</span><ul>";
            foreach($searches as $s) {
                if($s->ID != $post->ID) {
                    $title = trim(stripslashes($s->post_title));
                    $text .= "<li><a href='".get_permalink($s->ID)."' title=\"$title\"  rel=\"bookmark\">$title</a> |</li>";
                }
            }
            $text .= "</ul></div>";
        }
    }
    return $text;
}

add_filter('the_content', 'terong_related');

function get_related_ids($post_id) {
    global $wpdb;
    $sql = "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE meta_key in('related_post_name', 'related_id') AND post_id=$post_id";
    $searches = $wpdb->get_results($sql);
    if($searches) {
        $post_name = array();
        $post_id = array();
        foreach($searches as $s) {
            if($s->meta_key=='related_post_name') {
                $arr = explode(',', $s->meta_value);
                foreach($arr as $a) $post_name[] = ("'".trim($a)."'");

            }
            elseif($s->meta_key=='related_id') {
                $arr = explode(',', $s->meta_value);
                foreach($arr as $a) $post_id[] = ("'".trim($a)."'");
            }
        }
        $text_post_name = implode(', ', $post_name);
        $text_post_id   = implode(', ', $post_id);
        $sql = "SELECT DISTINCT post_title, ID FROM $wpdb->posts WHERE ";
        $arr_sql = array();
        if($post_name) $arr_sql[] = "post_name in($text_post_name)";
        if($post_id) $arr_sql[] = "ID in($text_post_id)";
        $sql .= implode(" OR ", $arr_sql);
        $sql .= " ORDER BY ID DESC";
        $searches = $wpdb->get_results($sql);
        return($searches);
    }
    else return array();
}

/*
Changes Log:

Version 1.1c (16 Oct 2005)
Bug fixes on conflict with other popup based plugins. Thanks to Leonid Mamchenkov

Version 1.1b (13 Oct 2005)
Add alternative links on the top right for some installation which experienced conflicts with other plugins.


Version 1.1b (13 Oct 2005)
A minor bug fix on browser detection, has been tested in Firefox 1.0.7, IE 6.0, Opera 8.0.2
Codes taken from http://webreference.com/tools/browser/javascript.html

Version 1.1a (13 Oct 2005)
Change all table name in SQL query to a generic name i.e $wpdb->posts

Version 1.1 (11 Oct 2005)
1. Check if it is single page (is_single()) then display related links.
   It is more make sense to just display related links in a full expanded text no
   matter there are any <!--more--> or not.

2. Exclude current post to be displayed in the current links even its ID included in
   the related_post_id or the post slug / post_name included in the related_post_name.

3. Add popup search form (click 'Related' quick tag button to open)

*/
?>
