<?php
/*
Plugin Name: Recent Comments Widget
Plugin URI: http://freepressblog.org/plugins/RecentComments
Description: This plugin will add a list of the most frequent comments posted to your blog. They are gathered in descending order (newest at the top), but then group them together by post title, so that comments from the same post are listed together. The list items will be links to the comments, and will contain the name of the commenter. Derived from the "Top/Recent Commenters" plugin by Scott Reilly (http://www.coffee2code.com/wp-plugins/)
Author: Jared Bangs
Author URI: http://freepressblog.org/
Version: 4.0
*/ 

// Put functions into one big function we'll call at the plugins_loaded
// action. This ensures that all required plugin functions are defined.
function widget_fp_recentcomments_init() {

	// Check for the required plugin functions. This will prevent fatal
	// errors occurring when you deactivate the dynamic-sidebar plugin.
	if ( !function_exists('register_sidebar_widget') )
		return;

	// This is the function that outputs our sidebar widget.
	function widget_fp_recentcomments($args) {
		
		// $args is an array of strings that help widgets to conform to
		// the active theme: before_widget, before_title, after_widget,
		// and after_title are the array keys. Default tags: li and h2.
		extract($args);

		// Each widget can store its own options. We keep strings here.
		$options = get_option('widget_fp_recentcomments');
		$title = $options['title'];
		$numberOfComments = $options['numberOfComments'];
		$numberOfWordsPerComment = $options['numberOfWordsPerComment'];
		$maxCommentsPerPost = $options['maxCommentsPerPost'];
		$maxLettersPerWord = $options['maxLettersPerWord'];

		// These lines generate our output. Widgets can be very complex
		// but as you can see here, they can also be very, very simple.
		echo $before_widget . $before_title . $title . $after_title;

		echo fp_get_recent_comments($numberOfComments, $numberOfWordsPerComment, $maxCommentsPerPost, $maxLettersPerWord) ;

		echo $after_widget;
	}


	// This is the function that outputs the form to let the users edit
	// the widget's title. It's an optional feature that users cry for.
	function widget_fp_recentcomments_control() {

		// Get our options and see if we're handling a form submission.
		$options = get_option('widget_fp_recentcomments');
		
		// Initialize defaults
		if ( !is_array($options) ) {
			$options = array('title'=>'Recent Comments', 
				'numberOfComments'=>7,
				'numberOfWordsPerComment'=>7,
				'maxCommentsPerPost'=>3,
				'maxLettersPerWord'=>0
				);
		}


		// Process the post to update the options
		if ( $_POST['fp_recentcomments-submit'] ) {

			// Remember to sanitize and format use input appropriately.
			$options['title'] = strip_tags(stripslashes($_POST['fp_recentcomments-title']));
			$options['numberOfComments'] = strip_tags(stripslashes($_POST['fp_recentcomments-numberOfComments']));
			$options['numberOfWordsPerComment'] = strip_tags(stripslashes($_POST['fp_recentcomments-numberOfWordsPerComment']));
			$options['maxCommentsPerPost'] = strip_tags(stripslashes($_POST['fp_recentcomments-maxCommentsPerPost']));
			$options['maxLettersPerWord'] = strip_tags(stripslashes($_POST['fp_recentcomments-maxLettersPerWord']));

			update_option('widget_fp_recentcomments', $options);
		}


		// Be sure you format your options to be valid HTML attributes.
		$title = htmlspecialchars($options['title'], ENT_QUOTES);
		$numberOfComments = htmlspecialchars($options['numberOfComments'], ENT_QUOTES);
		$numberOfWordsPerComment = htmlspecialchars($options['numberOfWordsPerComment'], ENT_QUOTES);
		$maxCommentsPerPost = htmlspecialchars($options['maxCommentsPerPost'], ENT_QUOTES);
		$maxLettersPerWord = htmlspecialchars($options['maxLettersPerWord'], ENT_QUOTES);
		
		// Here is our little form segment. Notice that we don't need a
		// complete form. This will be embedded into the existing form.
		echo '<p style="text-align:right;"><label for="fp_recentcomments-title">Title: <input style="width: 200px;" id="fp_recentcomments-title" name="fp_recentcomments-title" type="text" value="'.$title.'" /></label></p>';
		
		echo '<p style="text-align:right;"><label for="fp_recentcomments-numberOfComments">Number of comments to show: <input style="width: 200px;" id="fp_recentcomments-numberOfComments" name="fp_recentcomments-numberOfComments" type="text" value="'.$numberOfComments.'" /></label></p>';

		echo '<p style="text-align:right;"><label for="fp_recentcomments-numberOfWordsPerComment">Number of words per comment excerpt: <input style="width: 200px;" id="fp_recentcomments-numberOfWordsPerComment" name="fp_recentcomments-numberOfWordsPerComment" type="text" value="'.$numberOfWordsPerComment.'" /></label></p>';

		echo '<p style="text-align:right;"><label for="fp_recentcomments-maxCommentsPerPost">Max comments per post: <input style="width: 200px;" id="fp_recentcomments-maxCommentsPerPost" name="fp_recentcomments-maxCommentsPerPost" type="text" value="'.$maxCommentsPerPost.'" /></label></p>';

		echo '<p style="text-align:right;"><label for="fp_recentcomments-maxLettersPerWord">Max letters per word: <input style="width: 200px;" id="fp_recentcomments-maxLettersPerWord" name="fp_recentcomments-maxLettersPerWord" type="text" value="'.$maxLettersPerWord.'" /></label><br /><span>(0 for no limit)</span></p>';

		echo '<input type="hidden" id="fp_recentcomments-submit" name="fp_recentcomments-submit" value="1" />';
	}
	



	// This registers our widget so it appears with the other available
	// widgets and can be dragged and dropped into any active sidebars.
	register_sidebar_widget('FreePress Recent Comments', 'widget_fp_recentcomments');

	// This registers our optional widget control form. Because of this
	// our widget will have a button that reveals a 300x100 pixel form.
	register_widget_control('FreePress Recent Comments', 'widget_fp_recentcomments_control', 300, 300);
}

function fp_get_recent_comments($no_comments = 5, $comment_length = 5, $max_comments_per_post = 5, $max_letters_per_word=0) {
	
	$output = "<ul class=\"recentcomments\">";
	
	// Get a list of the recent comments from the database
	$comments = fp_get_recent_comments_query($no_comments, $max_comments_per_post);

	// Prepare two dimensional array with posts and their nested comments
    if(count($comments) > 0) {

	    $totalCommentsCounter = 0; // running count of comments processed

		foreach ($comments as $comment) {
						
			if($totalCommentsCounter < $no_comments) {
			
		        // Comment Author
				$comment_author = stripslashes($comment->comment_author);
				if ($comment_author == "") {
					$comment_author = "anonymous"; 
				}
		

				// Comment Content -> Excerpt
				$comment_content = strip_tags($comment->comment_content);
				$comment_content = stripslashes($comment_content);
				$words=split(" ",$comment_content); 
				
				if($max_letters_per_word!=0) {
						for($wordCounter=0; $wordCounter <= $comment_length; $wordCounter++) {
							if(strlen($words[$wordCounter]) > $max_letters_per_word) {
								$words[$wordCounter] = '&hellip;';
							}
							if($wordCounter +1 == count($words)) {
								break;
							}
								
						}
				}
				
				$comment_excerpt = join(" ",array_slice($words,0,$comment_length));
		
		        // Link to comment
				$permalink = get_permalink($comment->ID)."#comment-".$comment->comment_ID;
		        
				// Link to post (for titles)
				$postlink = get_permalink($comment->ID);
		
				// Assemble link
				$post_title = '<a href="' . $postlink . '">' . stripslashes($comment->post_title) . '</a>';
				$comment_ID = stripslashes($comment->comment_ID);
	
				// Only add to array if this post is still within the max comments per post
				if( count($postTitles[$post_title]) < $max_comments_per_post) {
					$postTitles[$post_title][$comment_ID] = '<li><span class="commentAuthor">' . $comment_author . ': </span>';
					$postTitles[$post_title][$comment_ID] .= '<a href="' . $permalink . '"';
					$postTitles[$post_title][$comment_ID] .= ' title="View the entire comment by ' . $comment_author.'">';
					$postTitles[$post_title][$comment_ID] .= $comment_excerpt;
					if (count($words) > $comment_length)
					{
						$postTitles[$post_title][$comment_ID] .= '&hellip;';
					}
					$postTitles[$post_title][$comment_ID] .= '</a></li>';
					
					$totalCommentsCounter = $totalCommentsCounter + 1;
				}
			}
	    }
	}
	else {
		$output .= "<!--You have no recent comments!-->";
	}

	// Prepare HTML output
	if(count($postTitles) > 0) {

		// Create an entry for each post that has recent comments
		foreach ($postTitles as $title => $commentPreview) {
	
			$output .= '<li class="recentCommentsPostTitle">' . $title . "\n";
				
				// Create a nested list of the recent comments within the current post
				$output .= '<ul>' . "\n";
				$commentsPerPostCounter = 0;
				foreach ($commentPreview as $comID => $commentPreviewHTML) {
					$output .= $commentPreviewHTML . "\n";

					$commentsPerPostCounter .= 1;
					$totalCommentsCounter .= 1;
				}
				$output .= '</ul>' . "\n";
			$output .= '</li>' . "\n";
		}
    }

	$output .= "</ul>";
	return $output;
}
function fp_get_recent_comments_query($no_comments, $max_comments_per_post) {

	global $wpdb, $tablecomments, $tableposts, $id;
	if (!isset($tablecomments)) $tablecomments = $wpdb->comments;
	if (!isset($tableposts)) $tableposts = $wpdb->posts;

	$limit = ($no_comments * $max_comments_per_post);

    $request = "SELECT ID, comment_ID, comment_content, comment_author, post_title FROM $tablecomments LEFT JOIN $tableposts ON $tableposts.ID=$tablecomments.comment_post_ID ";
	$request .= "WHERE (post_status = 'publish' OR post_status = 'static') ";
	if(!$show_pass_post) $request .= "AND post_password ='' ";

	if (get_option('WPTagboardPostID')) {
		$request .= "AND ID <> " . get_option('WPTagboardPostID') . " ";
	}

	$request .= "AND comment_approved = '1' ORDER BY comment_ID DESC LIMIT $limit";
		
	$comments = $wpdb->get_results($request);

	return $comments;
}

// Run our code later in case this loads prior to any required plugins.
add_action('plugins_loaded', 'widget_fp_recentcomments_init');

?>
