<?php

/*
Plugin Name: Comment favicons
Plugin URI: http://selfdestruct.net/
Description: Fetch the favicon of each commenting user (provided they set it up at their websites). This is based on <a href="http://slunj.carotena.net/projects/mtplugins/mticon.php">MTIcon plugin</a> by <a href="http://victor.carotena.net/weblog/">Victor Jalencas</a>.
Version: 1.2
Author: Toni Viemerö
Author URI: http://selfdestruct.net/
*/

function comment_fetch_favicon($comment_ID) {
    global 
$wpdb;

    
$imgpath get_settings('fileupload_realpath');
    
$url $wpdb->get_var("SELECT comment_author_url FROM {$wpdb->comments} WHERE comment_ID = {$comment_ID}");
    if (!empty(
$url) && preg_match('/^http:\/\//'$url)) {
        if (!
file_exists($imgpath .'/favicons/favicon_'sha1($url))) {
            
$page file($url);
            foreach (
$page as $line) {
                if (
preg_match('/"shortcut icon".*?href="(.*?)"/i'$line$match)) {
                    if (
preg_match('/^http:\/\//'$match[1])) {
                        
$favicon file_get_contents($match[1]);
                    } else {
                        
$favicon file_get_contents($url .'/'$match[1]);
                    }
                    
$format  '.'substr($match[1], -3);
                    
file_put_contents($imgpath .'/favicons/favicon_'sha1($url), $favicon);
                    
file_put_contents($imgpath .'/favicons/favicon_'sha1($url) . $format$favicon);
                    
system("/usr/local/bin/convert -resize 16x16 +profile \"*\" "$imgpath ."/favicons/favicon_"sha1($url) . $format ." "$imgpath ."/favicons/favicon_"sha1($url) .".jpg");
                    @
unlink($imgpath ."/favicons/favicon_"sha1($url) . $format);
                }
            }
        }
    }
    return 
$comment_ID;
}

function 
comment_favicon() {
    global 
$comment;

    
$imgpath get_settings('fileupload_realpath');
    
$imgurl  get_settings('fileupload_url');
    
$url     apply_filters('comment_url'$comment->comment_author_url);
    if (empty(
$url)) { 
        return 
false;
    } else {
        if (
file_exists($imgpath .'/favicons/favicon_'sha1($url) .'.jpg')) {
            echo (
'<img src="'$imgurl .'/favicons/favicon_'sha1($url) .'.jpg" alt="'$url .' favicon" class="favicon" />');
        } else {
            return 
false;
        }
    }
}

if(!
function_exists('_file_put_contents')) {
    function 
_file_put_contents($filename$data$file_append false) {
        
$fp fopen($filename, (!$file_append 'w+' 'a+'));
        if(!
$fp) {
            
trigger_error('file_put_contents cannot write in file.'E_USER_ERROR);
            return;
        }
        
fputs($fp$data);
        
fclose($fp);
    }
}


add_action('comment_post''comment_fetch_favicon');