<?php
/**
 * @name:        Akismet for Jlog
 * @author:      Jeena Paradies <jlog@jeenaparadies.net>
 * @version:     1.0
 * @date:        2006-12-18
 */

/*
 * This plugin requires the Akismet.class.php in the plugins directory.
 * PHP5: http://www.achingbrain.net/stuff/akismet/
 * PHP4: http://miphp.net/blog/view/php4_akismet_class
 *
 * And you need a WordPress-Api-Key: http://wordpress.com/api-keys/
 */
if(isset($_SERVER['SCRIPT_FILENAME']) AND __FILE__ == realpath( $_SERVER['SCRIPT_FILENAME'] ) AND $_GET['show'] == "spampic" ) {
  header("Content-Type: image/png");
	echo base64_decode("iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1QMBFzUfR2tAPwAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJTVDvZCVuAAABYklEQVQoz4WSPUvDUBSG35t7c9um1o+CNQZc1CJi3fzAQR3EzcXZTurgYv+OiAWn+AP0NygoCBWxxUjroCI1EkGbtLm5SR38mGx95udwzvtyCL6priyqkXW7ySnLM5VPEwBSBmUhA7NtGAfZ85IAAAIA1uToEPe84/RAZk5L9YJSCoAgCkN47jveHLvkJ+Jr2UrtiVRXlxm1rFNdH5mLJTT8hfBbqD8/XInhoXm6GzS3BtOZHS3Vh05QxsAo093686vCFbqh9XSWf0gke8CZmmdM5Tna3w8UCl0HlGIRav1pigEAOAdmZ7uvME0ABCyU8ia0X5bo+npXP4oiSBncKCKSZrPx/m+GlteAkIGpKBMTh45jXwi/2VEOhA/Hsa/bxvAeAYC7XFaPNdyTgXRmRkumoFD6e0bL/YDj2Fd+nK+NV2qP5Pc1lhfU9n1tO/ZVXQ4gJAyDsh/KIxjG/tjZpQ8An2Qliwg2VQq3AAAAAElFTkSuQmCC");
  exit;
} else {

class AkismetPlugin extends JlogPlugin {

	var $spam_count = 0;
	var $actual_spam = false;
	
	function __construct() {
		$this->file = JLOG_BASEPATH.'personal/wpapikey.inc.php';
	}

    function hook_newComment($form) {
			
			if(is_readable($this->file)) include($this->file);
			if(empty($WordPressAPIKey)) return $form;

			require_once(JLOG_BASEPATH.'plugins/Akismet.class.php');

			$akismet = new Akismet(JLOG_PATH.'/', $WordPressAPIKey);
			$akismet->setCommentAuthor($form['name']);
			$akismet->setCommentAuthorEmail($form['email']);
			$akismet->setCommentAuthorURL($form['homepage']);
			$akismet->setCommentContent($form['content']);
			$akismet->setPermalink('http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);

			if($akismet->isCommentSpam()) {
				$form['type'] = 'spam';
				$this->actual_spam = $form['sid'];
				return $form;
			}
			else return $form;
    }

		function hook_showComment($comment, $form, $nr) {
			if($form['type'] == 'spam') {
				$this->spam_count++;
				if($this->actual_spam == $form['sid'])
					return error_output(array("Your comment was marked as spam by <a href='http://akismet.com'>Akismet</a>."));
			}
			// # ist extra an meine seite angeasst
			else
				return str_replace("href='#c".$form['id']."'>".$nr."</a>", "href='#c".$form['id']."'>".((int)$nr - $this->spam_count)."</a>", $comment);
		}
		
		function hook_commentorMail($mail, $blog) {
			if($this->actual_spam) $mail['nomail'] = true;
			return $mail;
		}

		function hook_adminMail($mail, $blog) {
			if($this->actual_spam) $mail['nomail'] = true;
			return $mail;
		}

		function hook_adminContent() {

			$post = strip($_POST);
			$get = strip($_GET);
			if(!empty($post['wpapikey'])) file_put_contents($this->file, '<?php $WordPressAPIKey = "'.$post['wpapikey'].'"; ?>');
			if(is_readable($this->file)) include($this->file);
			$change2spam = (!empty($get['spam']) AND is_numeric($get['spam']));
			
			if(!empty($post['form_submit']) OR $change2spam) {
				$change = "";
				$delete = "";
				if(is_array($post['spam'])) {
					foreach($post['spam'] AS $key => $value) {
						if($value == "change") $change .= $key.",";
						if($value == "delete") $delete .= $key.",";
					}
					$change = trim($change, ',');
					$delete = trim($delete, ',');
				}

				if($change2spam) $change = $get['spam'];
				if($change OR $change2spam) {
					require_once(JLOG_BASEPATH.'plugins/Akismet.class.php');
					
					$sql = "SELECT name, email, homepage, content FROM ".JLOG_DB_COMMENTS." WHERE id IN(".$change.")";
					$comments = new Query($sql);
         	if($comments->error()) {
            echo "<pre>\n";
            echo $comments->getError();
         		echo "</pre>\n";
         		die();
	        }
					while($form = $comments->fetch()) {
						$akismet = new Akismet(JLOG_PATH.'/', $WordPressAPIKey);
						$akismet->setCommentAuthor($form['name']);
						$akismet->setCommentAuthorEmail($form['email']);
						$akismet->setCommentAuthorURL($form['homepage']);
						$akismet->setCommentContent($form['content']);
						# $akismet->setPermalink('http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
						if($change2spam) $akismet->submitSpam();
						else $akismet->submitHam();
			    }
					$sql = "UPDATE ".JLOG_DB_COMMENTS." SET type = '".($change2spam ? "spam" : "")."' WHERE id IN(".$change.")";
					$comments = new Query($sql);
         	if($comments->error()) {
            echo "<pre>\n";
            echo $comments->getError();
         		echo "</pre>\n";
         		die();
	        }					
				}
				if($delete) {
					$sql = "DELETE FROM ".JLOG_DB_COMMENTS." WHERE id IN(".$delete.")";
					$comments = new Query($sql);
         	if($comments->error()) {
            echo "<pre>\n";
            echo $comments->getError();
         		echo "</pre>\n";
         		die();
	        }					
				}
			}
				
			return "
			 <form action='' method='POST'>
			   <p><a href='http://wordpress.com/api-keys/'>WordPress API Key</a>:<br />
			     <input name='wpapikey' value='$WordPressAPIKey' /><input type='submit' value='save' />
			   </p>
			 </form>".$this->spam_list();
		}
				
		function hook_countComments($com) {
       $sql = "SELECT reference, COUNT(*) as count FROM ".JLOG_DB_COMMENTS." WHERE type <> 'pingback' AND type <> 'spam' GROUP BY reference";
       $comments = new Query($sql);
           if($comments->error()) {
              echo "<pre>\n";
              echo $comments->getError();
           		echo "</pre>\n";
           die();
        }
       $com = array();
       while($c = $comments->fetch()) $com[$c['reference']] = $c['count'];
      
			return $com;
		}
		
		function hook_commentAdminList($comment, $data) {
			if($data['type'] == 'spam') return;
			global $l;
			return str_replace("/img/JLOG_trash.png' alt='".$l['admin']['delete']."' /></a>", "/img/JLOG_trash.png' alt='".$l['admin']['delete']."' /></a> <a title='Spam' href='plugin.php?jplug=AkismetPlugin&amp;spam=".$data['id']."'><img src='".JLOG_PATH."/plugins/AkismetPlugin.jplug.php?show=spampic"."' alt='spam' /></a>", $comment);
		}

		function spam_list() {
			
			global $l;
			$get = strip($_GET);
			$yl = new Year_Links($get['y'], JLOG_START_YEAR, JLOG_PATH."/admin/plugin.php?jplug=AkismetPlugin", $l['admin']); 
			
			$output = "<p>".$yl->get_admin_linklist()."</p><form action='plugin.php?jplug=AkismetPlugin' method='POST'><table> 
		   <tr> 
		    <th></th><th>".$l['admin']['change']." (no spam)</th><th>".$l['admin']['delete']."</th><th>ID</th><th>".$l['comments_name']."</th><th>".$l['comments_posted']."</th><th>".$l['admin']['kill_c_entry']."</th> 
		   </tr>"; 

		    $sql = "SELECT 
		                    ".JLOG_DB_COMMENTS.".id AS id, 
		                    ".JLOG_DB_CONTENT.".url AS url, 
		                    UNIX_TIMESTAMP(".JLOG_DB_CONTENT.".date) AS reference_date, 
		                    UNIX_TIMESTAMP(".JLOG_DB_COMMENTS.".date) AS date, 
		                    ".JLOG_DB_COMMENTS.".name AS name, 
		                    ".JLOG_DB_CONTENT.".topic AS topic, 
		                    ".JLOG_DB_COMMENTS.".email AS email 
		              FROM ".JLOG_DB_COMMENTS.", ".JLOG_DB_CONTENT." 
		              WHERE ".JLOG_DB_COMMENTS.".reference = ".JLOG_DB_CONTENT.".id 
		              AND YEAR(".JLOG_DB_COMMENTS.".date) = '".$yl->get_selected_year()."'
		 							AND type = \"spam\"
		              ORDER BY id DESC;"; 

		    $comments = new Query($sql); 
		     if($comments->error()) { 
		        echo "<pre>\n"; 
		        echo $comments->getError(); 
		        echo "</pre>\n"; 
		        die(); 
		     }
          
		    while ($daten = $comments->fetch()) { 
		      if(!empty($daten['name'])) $daten['name'] = htmlspecialchars($daten['name'], ENT_QUOTES); 
		      else $daten['name'] = $l['comments_anonym']; 
		      if(!empty($daten['email'])) $email = "<a href='mailto:".$daten['email']."'>".$daten['name']."</a>"; 
		      else $email = $daten['name']; 

		       $output .= " 
		      <tr>
		 			 <td><input type='radio' name='spam[".$daten['id']."]' value='' checked='checked' /></td>
		 			 <td><input type='radio' name='spam[".$daten['id']."]' value='change' /></td>
		 			 <td><input type='radio' name='spam[".$daten['id']."]' value='delete' /></td>
		       <td><a href='".blog($daten['reference_date'], $daten['url'])."#c".$daten['id']."'>".$daten['id']."</a></td> 
		       <td>".$email."</td> 
		       <td>".strftime(JLOG_DATE_COMMENT, $daten['date'])."</td> 
		       <td>".$daten['topic']."</td> 
		      </tr>"; 
		    }
		
				$output .= "
				<script type='text/javascript'>
				 document.write(\"<tr><td><input name='akismet' type='radio' onclick='jlog_akismet_checkall(this, 0);' checked='checked' /></td><td><input name='akismet' type='radio' onclick='jlog_akismet_checkall(this, 1);' /></td><td><input name='akismet' type='radio' onclick='jlog_akismet_checkall(this, 2);' /></td><td colspan='4'></td></tr>\")
				 function jlog_akismet_checkall(table, column) {
					var trs = table.parentNode.parentNode.parentNode.getElementsByTagName('tr');
					for(var i=0; i<trs.length; i++) {
						if(trs[i].getElementsByTagName('input')[column]) trs[i].getElementsByTagName('input')[column].checked = 'checked';
					}
				 }
				</script>
				</table>
				";
			
				return $output."<p><input type='submit' value='GO!' name='form_submit' /></p></form>";
		}

}

}
?>
