<?php
/*
Plugin Name: Yskin's wp-statistics
Version:     3.0.1
Plugin URI:  http://yskin.net/projects/wp-statistics/
Description: 在Blog侧边栏显示一些统计信息,比如文章数、评论数、最后更新日期等。
Author:      Yskin
Author URI:  http://yskin.net/

License
=============================================================================
Copyright (C) 2006 yskin (email: yskins@gmail.com)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
/*
TODO:
隐藏显示功能。
*/

register_activation_hook(__FILE__'wp_stat_activate');

$wp_stat_sample =
'文章数:%post%
页面数:%page%
分类数:%category%
标签数:%tag%
链接数:%link%
<span title="访客/管理员:%comment_guest%/%comment_author%">评论数:%comment%</span>
TBPB数:%tbpb%
总字数:%word%
<span title="已上线<' 
'?php echo floor((time()-strtotime("2006-4-1"))/86400); ?' '>天">建站日期:2006年4月1日</span>
最早文章日期:<br />%first%
最后更新日期:<br />%last%'
;

function 
wp_stat_activate() {
    global 
$wp_stat_sample;
    if ( 
get_option('wp-statistics') === false )
        
update_option('wp-statistics'$wp_stat_sample);

    if ( 
get_option('wp-statistics-style') === false )
        
update_option('wp-statistics-style'1);
}

if ( !
function_exists('mb_strlen1') ):
function 
mb_strlen1($str) {
    
$num 0;
    for ( 
$i 0$i strlen($str); $i++ ) {
        
$ord ord($str{$i});
        if ( (
$ord 0xC0) != 0x80 $num++;
    }
    return 
$num;
}
endif;

class 
Ystat {
    var 
$cache;     //Cache
    
var $cachelen;  //Cache length
    
var $now;
    var 
$stat_code//Statistics code
    
var $style;     //Statistics code style

    
function Ystat() {
        
$this->cache wp_cache_get('ystat''plugins');
        if ( 
$this->cache == false )
            
$this->cache = array();
        
$this->cachelen count($this->cache);

        
$this->stat_code get_option('wp-statistics');
        
$this->style get_option('wp-statistics-style');
    }

    function 
show() {
        
$code $this->stat_code;

        if ( 
$this->style == ) {
            
$code '<div id="statistics">' nl2br($code) . '</div>';
        } elseif ( 
$this->style == ) {
            
$tmp "<ul>\n";
            foreach ( 
explode("\n"$code) as $line ) {
                
$line trim($line);
                if ( !empty(
$line) )
                    
$tmp .= "<li>$line</li>\n";
            }
            
$tmp .= '</ul>';
            
$code $tmp;
        }

        
$code preg_replace_callback('/%([^%]*)%/u', array(&$this'replace_stat'), $code);

        eval(
' ?>' $code '<?php ');
    }

    function 
replace_stat($matches) {
        
$stat = &$matches[1];
        return 
$this->get($stat);
    }

    function 
get($str) {
        global 
$wpdb;

        if ( isset(
$this->cache[$str]) )
            return 
$this->cache[$str];

        switch (
$str) {
            
//Posts
            
case 'post':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND (post_status = 'publish' OR post_status = 'private')");
                break;
            
//Pages
            
case 'page':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'page' AND post_status = 'publish'");
                break;
            
//Categories
            
case 'category':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->categories");
                break;
            
//Tags
            
case 'tag':
                global 
$tabletags;
                if ( 
function_exists('UTW_ShowRelatedPostsForCurrentPost') )
                    
$result $wpdb->get_var("SELECT COUNT(*) FROM $tabletags");
                else
                    
$result '未安装 UTW 插件';

                break;
            
//Links
            
case 'link':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->links WHERE link_visible = 'Y'");
                break;
            
//Comments
            
case 'comment':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1' AND comment_type != 'trackback' AND comment_type != 'pingback'");
                break;
            
//Comments by guest
            
case 'comment_guest':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1' AND comment_type != 'trackback' AND comment_type != 'pingback' AND user_id = 0");
                break;
            
//Comments by author
            
case 'comment_author':
                
$result $this->get('comment') - $this->get('comment_guest');
                break;
            
//Trackback&Pingback
            
case 'tbpb':
                
$result $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1' AND (comment_type = 'trackback' OR comment_type = 'pingback')");
                break;
            
//Word counts
            
case 'word':
                
$words $wpdb->get_results("SELECT post_content FROM $wpdb->posts WHERE (post_type = 'post' OR post_type = 'page') AND (post_status = 'publish' OR post_status = 'private')");
                
$result 0;
                
$mb_strlen function_exists('mb_strlen') ? 'mb_strlen' 'mb_strlen1';
                foreach (
$words as $word)
                    
$result += $mb_strlen(preg_replace('/\s/'''html_entity_decodestrip_tags($word->post_content) ) ), 'UTF-8');
                break;
            
//First post date
            
case 'first':
                
$result $wpdb->get_results("SELECT MIN(post_modified) AS MIN_m FROM $wpdb->posts WHERE (post_type = 'post' OR post_type = 'page') AND (post_status = 'publish' OR post_status = 'private')");
                
$result date('Y-n-j'strtotime($result[0]->MIN_m));
                break;
            
//Last Update
            
case 'last':
                
$result $wpdb->get_results("SELECT MAX(post_modified) AS MAX_m FROM $wpdb->posts WHERE (post_type = 'post' OR post_type = 'page') AND (post_status = 'publish' OR post_status = 'private')");
                
$result date('Y-n-j g:ia'strtotime($result[0]->MAX_m));
                break;
            default:
                break;
        }

        
$this->cache[$str] = $result;
        return 
$result;
    }

    
//手工析构
    
function close() {
        if (
$this->cachelen <> count($this->cache))
            
wp_cache_set('ystat'$this->cache'plugins');
    }
}

function 
ShowStatistics() {
    
$y = new Ystat(); //建立对象
    
$y->show();
    
$y->close(); //析构
}

add_action('admin_menu''wp_stat_add_option_page');

function 
wp_stat_add_option_page() {
    if ( 
function_exists('add_options_page') ) {
         
add_options_page("Yskin's wp-statistics Settings"'wp-statistics'8__FILE__'wp_stat_option_page');
    }
}

function 
wp_stat_option_page() {
    global 
$wpdb;
    if ( isset(
$_POST['Submit']) ) {
        
update_option('wp-statistics'stripslashes((string) $_POST['stat']) );
        
update_option('wp-statistics-style', (int) $_POST['style']);
?>
<div id="message" class="updated fade"><p>Yskin's wp-statistics 设置已更新...</p></div>
<?php
    
}

    
//每次进入设置页面时清除cache。
    
wp_cache_delete('ystat''plugins');

    
$stat get_option('wp-statistics');
    
$style get_option('wp-statistics-style');
    
$wp_stat = new Ystat();
?>
<div class='wrap'>
<h2 id="edit-settings">Yskin's wp-statistics 设置</h2>

<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<table width="100%" border="0" cellspacing="0" cellpadding="6">

    <tr>
    <td width="50%" valign="top">
        <h3>统计代码</h3>
        <p>代码为 HTML 格式,可以内嵌 PHP 代码,可以使用"%tag%"这样的标签。</p>
    </td>

    <td width="50%" valign="top">
        <h3>输出预览</h3>
        <p>输出预览在您点“更新”按钮后会刷新。</p>
    </td>
    </tr>

    <tr>
    <td width="50%" valign="top">
        <textarea name="stat" cols="52" rows="16"><?php echo htmlentities($statENT_QUOTES'UTF-8'?></textarea>
    </td>

    <td width="50%" valign="top">
        <div><?php $wp_stat->show(); ?></div>
    </td>
    </tr>

    <tr><td valign="top">
    <h3>如何处理每一行</h3>
    <div style="margin-left:80px">
        <label><input type="radio" name="style" value="0"<?php checked(0$style?> /> 不处理</label><br />
        <label><input type="radio" name="style" value="1"<?php checked(1$style?> /> 在行末添加&lt;br /&gt;</label><br />
        <label><input type="radio" name="style" value="2"<?php checked(2$style?> /> 在首尾添加&lt;li&gt;和&lt;/li&gt;</label>
    </div>
    </td></tr>

    </table>

    <p class="submit"><input type="submit" name="Submit" value="<?php _e('Update Options'?> &raquo;" /></p>
</form>
</div>

<?php
global $wp_stat_sample;

$wp_stat->stat_code $wp_stat_sample;
?>

<div class='wrap'>
<h2>帮助</h2>

<p>Yskin's wp-statistics 插件现在已经变得更简单易用了。您可以在后台轻松设置要输出的统计信息内容,并可以内嵌 PHP 代码。</p>
<p>本插件支持 <a href="http://automattic.com/code/widgets/">WordPress Widgets</a> 和 <a href="http://nybblelabs.org.uk/projects/sidebar-modules/">Sidebar Modules</a>,您可以很方便的通过这两个侧边栏控制插件来控制统计信息的显示。</p>
<p>请访问<a href="http://yskin.net/projects/wp-statistics/">本插件主页</a>下载最新版本以及获取更多信息。</p>

    <table width="100%" border="0" cellspacing="0" cellpadding="6">
    <tr>
    <td width="50%" valign="top">
        <h3>统计代码示例</h3>
        <p>请参考该示例以便学习如何编写示例代码。所有可以使用的标签均可在示例中找到。</p>
    </td>

    <td width="50%" valign="top">
        <h3>输出预览</h3>
        <p>示例统计代码的输出预览。</p>
    </td>
    </tr>

    <tr>
    <td width="50%" valign="top">
        <textarea name="stat" cols="52" rows="16" readonly="readonly"><?php echo htmlentities($wp_stat_sampleENT_QUOTES'UTF-8'); ?></textarea>    </td>

    <td width="50%" valign="top">
        <div><?php $wp_stat->show(); ?></div>
    </td>
    </tr>

    </table>

</div>
<?php
}

function 
widget_Ystat_init() {

    if ( !
function_exists('register_sidebar_widget') )
        return;

    function 
statistics_sidebar_module($args) {
        
extract($args);

        echo(
$before_module $before_title $title $after_title);
        
ShowStatistics();
        echo(
$after_module);
    }

    
register_sidebar_module('Statistics module''statistics_sidebar_module''sb-stat');
}

add_action('init''widget_Ystat_init');
?>