.  
 *
 * $Id$
 * 
 */
/**  
 * based upon semmelstatz
 * Copyright (c) 2005-2009 Andreas 'Redunzl' Mueller (redunzl@gmx.de)
 *    
 * @license http://www.gnu.org/licenses/gpl-2.0.html
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License (version 2) as
 * published by the Free Software Foundation.
 *
 * 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
*/
 
if(!current_user_can('manage_statz')) {
	die('Zugriff verweigert');
}
include_once plugin_dir_path(__FILE__).'includes/pChart/class/pData.class.php';
include_once plugin_dir_path(__FILE__).'includes/pChart/class/pDraw.class.php';
include_once plugin_dir_path(__FILE__).'includes/pChart/class/pImage.class.php';
### AKTUELL - Funktionen
	function sem_showWhoIsOnline() {
        global $wpdb;
		
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
		$onlinetime = $sem_options["statz_online_time"];
  
  /** @todo add show_vars to semr-config */
  $sem_options['show_utrace'] = $sem_options['show_whois'] = $sem_options['show_arin'] = true;
		
        $onlineusers = $wpdb->get_results("SELECT DISTINCT username, page, ip, time
		FROM ".$wpdb->statz." WHERE time > Now() - INTERVAL ".$onlinetime." SECOND GROUP BY ip ORDER BY page DESC");
        
        print "
";
        $iUsersOnline = (int) sem_showNumUsersOnline();
        printf("%s ".semr_i18np("Visitor online", "Visitors online", $iUsersOnline), $iUsersOnline);
        print " - ".semr_i18n("Today").": ".sem_showTodayStatz()."
";
        
        if (empty($onlineusers)) {
            print "... ".semr_i18n("no entries")."";
            print "
";
            return;
        }
        print '';
        print '';
        print '';
        print '| '.semr_i18n("Username").'';
        print ' | '.semr_i18n("Post/Page").'';
        print ' | '.semr_i18n("TCP/IP").'';
        print ' | '.semr_i18n("Time").'';
        print ' | 
';
        print '';
        print '';
            foreach ($onlineusers as $key=>$onlineuser) {
                $username = $onlineuser->username;
                $page = $onlineuser->page;
                if ($page == 0) {
                    $link = get_option('siteurl');
                    $title = semr_i18n("startpage");
                } else {
                    $link = get_permalink($page);
                    $title = get_post($page);
                    if(is_array($title)) {
                        $title = $title->post_title;
                    } else {
                        $link = null;
                        $title = semr_i18n("no page");
                    }
                }
                
                $ip = $onlineuser->ip;
                if(sem_checkIfIPisEncoded($ip) == true) $ip = sem_decodeIP($ip);
                $time = mysql2date("H:i",$onlineuser->time);
                print '':'>');
                print '| '.$username.'';
                print ' | ';
                print (is_null($link))?$title:''.$title.'';
                print '';
                print ' | ';
                if($sem_options['show_arin']) {
                    print '';
                    print ' ';
                print ' ';
                    print ' ';
                }
                if($sem_options['show_whois']) {
                    print '';
                    print '  ';
                    print ' ';
                }
                if($sem_options['show_utrace']) {
                    print '';
                    print '  ';
                    print ' ';
                }                
                print ' | '.$time.'';
                print ' | 
';
            }
        print '';
        print '
';
        print "
";
	}
	
function sem_draw24HoursGoo() {
    global $wpdb;
    $results = $wpdb->get_results("SELECT time as hours, COUNT(DISTINCT ip) as visitors
    FROM ".$wpdb->statz." WHERE time >= NOW() - INTERVAL 23 HOUR GROUP BY HOUR(time) ORDER BY time ASC");
    print '';
    print semr_i18n("Visitors: Last 24 hours").'
';
    print "";
    if(empty($results)) {
        print '
... '.  semr_i18n("no entries at all").'';
        print "
";
        return;
    }
    
    $aHours = array();
    $aVisitors = array();
    $iInterval = 86400-7200;
  
    for($i=0;$i<24;$i++) {
        $aHours[$i] = date("H", time() - $iInterval);
        $iInterval = $iInterval - 3600;
        $aVisitors[$i] = VOID;
    }
    
    $iCount = 0;
    $bFirst = true;
    $atemp = array();    
    
    foreach($results as $aResult) {
        $iDbHour = mysql2date('H', $aResult->hours);
        $iKey = array_search($iDbHour, $aHours);
        $aVisitors[$iKey] = $aResult->visitors;
    }
    $MyData = new pData();  
    $MyData->addPoints($aVisitors,"Visitors");
    $MyData->setAxisName(0,"Visitors");
    $MyData->addPoints($aHours,"Hours");
    $MyData->setAbscissa("Hours");
    $myPicture = new pImage(780,150,$MyData);    
    $myPicture->Antialias = true;    
    $myPicture->drawRectangle(0,0,779,149,array("R"=>0,"G"=>0,"B"=>0));   
    $myPicture->setFontProperties(array("FontName"=>plugin_dir_path(__FILE__)."includes/pChart/fonts/Bedizen.ttf","FontSize"=>8));    
    $myPicture->setGraphArea(30,20,760,130);
    $scaleSettings = array(
        //"DrawSubTicks"=>TRUE,
        "GridR"=>200,
        "GridG"=>200,
        "GridB"=>200
    );
    $myPicture->drawScale($scaleSettings);
    $myPicture->drawBarChart(array("DisplayValues"=>true,"DisplayColor"=>DISPLAY_MANUAL,"DisplayPos"=>LABEL_POS_OUTSIDE));
    //$myPicture->drawSplineChart();
    
    $TextSettings = array("R"=>100,"G"=>100,"B"=>100,"FontSize"=>8,"Align"=>TEXT_ALIGN_TOPRIGHT);
    $myPicture->drawText(770,5,"(c) 2011 semmelstatzR",$TextSettings);
    
    @$myPicture->Render(WP_CONTENT_DIR."/cache/24HourGoo.png"); 
    print '
';
    if(is_readable(WP_CONTENT_DIR."/cache/24HourGoo.png")) {
        print '

';
    } else if(!is_dir(WP_CONTENT_DIR."/cache")) {
        print semr_i18n('No Chart: Cannot find cache-folder!');
    } else if(!is_writable(WP_CONTENT_DIR."/cache")) {
        print semr_i18n('No Chart: Missing rights for cache-folder!');
    }
    print "
";
    print "
";
}
	
	function sem_showDailyStatz() {
        global $wpdb;
		
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
		$limit = $sem_options["statz_days_limit"];
		$daylimit = $limit - 1;
		
		$thedays = $wpdb->get_results("SELECT COUNT(ip) AS hits, COUNT(DISTINCT ip) AS visitors, COUNT(DISTINCT referer)
		AS referers, substring(time,1,10) AS date FROM ".$wpdb->statz." WHERE time >= CURDATE() - INTERVAL ".$daylimit." DAY
		GROUP BY date ORDER BY time DESC");
        
        print '';
        printf (semr_i18n("%s-Days-Statz"), $limit);
        print '
';
        if (empty($thedays)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        print "";
        print "";
        print "";
        print "| ".semr_i18n("Date")."";
        print " | ".semr_i18n("Visitors")."";
        print " | ".semr_i18n("Hits")."";
        print " | ".semr_i18n("Referer")."";
        print " | 
";
        print "";
        print "";
            foreach ($thedays as $key=>$theday) {
                $date = $theday->date;
                $date = strtotime(substr($theday->date,1,10));
                $today = time();
                $difference = ceil(($today - $date) / (60*60*24))-1;
                if($difference == 0) {
                    $date = semr_i18n("Today");
                }
                elseif($difference == 1) {
                    $date = semr_i18n("Yesterday");
                }
                elseif($difference == 2) {
                    $date = semr_i18n("2 days ago");
                }
                else {
                    $date = mysql2date("d.m.Y",$theday->date);
                }
                $hits = $theday->hits;
                $visitors = $theday->visitors;
                $referers = $theday->referers;
                print "";
                print "| $date";
                print " | $visitors";
                print " | $hits";
                print " | $referers";
                print " | 
";
            }
        print "";
        print "| ".semr_i18n("more")."...";
        print " | 
";
        print "";
        print "
";
		print "
";
	}
    
	function sem_showReferers() {
        global $wpdb, $homehost;
		
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
		$limit = $sem_options["statz_referer_limit"];
        $mask = $sem_options["statz_mask_referer"];
        
		$lastreferers = $wpdb->get_results("SELECT DISTINCT referer, time FROM ".$wpdb->statz." WHERE referer
        NOT LIKE '".$homehost."' ORDER BY time DESC  LIMIT 0, ".$limit);
        
        print "";
        printf (semr_i18n("The last %s Referrer"), $limit);
        print "
";
        if (empty($lastreferers)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        print "";
        print "";
        print "";
        print "| ".semr_i18n("Time")."";
        print " | ".semr_i18n("Referrer")."";
        print " | 
";
        print "";
        print "";
            foreach ($lastreferers as $key=>$lastreferer) {
                $referer = $lastreferer->referer;
                if(strlen($referer) >= 120) {
                    $printreferer = substr($referer, 0, 120)." ...";
                }
                else {
                    $printreferer = $referer;
                }
                $time = mysql2date("d.m.Y - H:i",$lastreferer->time);
                print "";
				print "| ".$time."";
                if($mask != true) {
                    print " | ".$printreferer."";
                }
                else {
                    $referer = htmlspecialchars($referer, ENT_QUOTES);
                    print " | ".$printreferer."";
                }
                print " | 
";
            }
        print "";
        print "
";
		print "
";
	}
	
	function sem_showKeyword() {
     global $wpdb;
     
     $sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
     $limit = $sem_options["statz_keyword_limit"];
  
    $results = $wpdb->get_results("SELECT referer, time, ip FROM $wpdb->statz WHERE referer != 'NULL' ORDER BY time DESC");
		
    print "";
    printf(semr_i18n("The last %s search terms"), $limit);
    print "
";
    if (empty($results)) {
        print '... '.  semr_i18n("no entries at all").'';
        print "
";
        return;
    }
    print "";
    print "";
    print "";
    print "| ".semr_i18n("Time")."";
    print " | ".semr_i18n("search term")."";
    print " | ".semr_i18n("TCP/IP")."";
    print " | 
";
    print "";
    print "";
    $i=0;
			foreach($results as $result) {
				$referer = $result->referer;
				$keyword = sem_getKeyword($referer);
				$ip = $result->ip;
				if(sem_checkIfIPisEncoded($ip) == true) $ip = sem_decodeIP($ip);
				$time = mysql2date('d.m.Y - H:i',$result->time);
					if($keyword) {
						print "";
						print "| ".$time."";
						print " | ".$keyword."";
						print " | ";
						
						print "     | 
";
						$i++;
					}
				if($i == $limit) break;
			}
		print "";
        print "
";
		print "
";
	}
	
	function sem_showTodayTopReads() {
        global $wpdb;
        $today = date("Y-m-d");
        $topreads = $wpdb->get_results("SELECT post_title AS posttitle, post_name as postname, guid AS postid,
        COUNT(".$wpdb->statz.".page) AS count FROM ".$wpdb->posts.", ".$wpdb->statz." WHERE
        ".$wpdb->statz.".page = ".$wpdb->posts.".ID AND time >= '$today' GROUP BY postid ORDER BY count DESC LIMIT 10");
        
        print "";
        print semr_i18n("Top 10 of todays posts & pages")."
";
        if (empty($topreads)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        print "";
        print "";
        print "";
        print "| ".semr_i18n("Post/Page")."";
        print " | ".semr_i18n("Postname")."";
        print " | ".semr_i18n("Hits")."";
        print " | 
";
        print "";
        print "";
        foreach ($topreads as $key=>$topread) {
            $posttitle = $topread->posttitle;
            $postname = $topread->postname;
            $postid = $topread->postid;
            $count = $topread->count;
            print "";
            print "| ".$posttitle."";
            print " | ".$postname."";
            print " | ".$count."";
            print " | 
";
        }
        print "";
        print "
";
        print "
";
    }
	
	function sem_showTopReads() {
        global $wpdb;
        
        $sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
        $limit = $sem_options["statz_topreads_limit"];
		
        $topreads = $wpdb->get_results("SELECT post_title AS posttitle, post_name as postname, guid AS postid,
        hits AS count FROM ".$wpdb->posts." WHERE hits != '0' GROUP BY postid ORDER BY hits DESC LIMIT 0, ".$limit);
        
        print "";
        printf (semr_i18n("Top %s of all posts & pages"), $limit);
        print "
";
        if (empty($topreads)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        print "";
        print "";
        print "";
        print "| ".semr_i18n("Post/Page")."";
        print " | ".semr_i18n("Postname")."";
        print " | ".semr_i18n("Hits")."";
        print " | 
";
        print "";
        print "";
            foreach ($topreads as $key=>$topread) {
                $posttitle = $topread->posttitle;
                $postname = $topread->postname;
                $postid = $topread->postid;
                $count = $topread->count;
                print "";
                print "| ".$posttitle."";
                print " | ".$postname."";
                print " | ".$count."";
                print " | 
";
            }
        print "";
        print "
";
        print "
";
    }
	
    function sem_showWhoWasOnlineToday() {
        global $wpdb;
        $today = date("Y-m-d");
        $todaysonlineusers = $wpdb->get_results("SELECT DISTINCT username, COUNT(username) as num FROM ".$wpdb->statz." WHERE
        time >= '$today' AND username != 'Gast' GROUP BY username ORDER BY num DESC");
        
        print '';
        print semr_i18n("Known visitors today");
        print '
';
        if (empty($todaysonlineusers)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        print "";
        print "";
        print "";
        print "| ".semr_i18n("Visitor (Hits)")."";
        print " | 
";
        print "";
        print "";
            foreach ($todaysonlineusers as $key=>$todayonlineuser) {
                $username = $todayonlineuser->username;
                $num = $todayonlineuser->num;
                print "";
                print "| ".$username." (".$num.")";
                print " | 
";
            }
        print "";
        print "
";
        print "
";
    }
	
	function sem_showTopCommented() {
        global $wpdb;
        $topcommentedposts = $wpdb->get_results("SELECT guid, id, post_title, COUNT(*) AS count FROM
        ".$wpdb->comments.",". $wpdb->posts." WHERE comment_approved = '1' AND comment_post_id = id
        GROUP BY guid ORDER BY count DESC LIMIT 0, 10");
        
        print "";
        print semr_i18n("Top 10 of all commented posts")."
";
        if (empty($topcommentedposts)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        
        print "";
        print "";
        print "";
        print "| ".semr_i18n("Post/Page")."";
        print " | ".semr_i18n("Comments")."";
        print " | 
";
        print "";
        print "";
        
        foreach ($topcommentedposts as $key => $topcommentedpost) {
            $posttitle = $topcommentedpost->post_title;
            $count = $topcommentedpost->count;
            $postid = $topcommentedpost->guid;
            print "";
            print "| ".$posttitle."";
            print " | ".$count."";
            print " | 
";
        }            
        print "";
        print "
";
        print "
";
    }
    function sem_showCommenters() {
        global $wpdb;
		
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
        $limit = $sem_options["statz_comment_limit"];
		
        $topcommenters = $wpdb->get_results("SELECT comment_author AS commenter, COUNT(comment_ID) AS count,
        comment_author_email AS email, comment_author_url AS homepage FROM " .$wpdb->comments . " WHERE
        comment_approved = '1' GROUP BY comment_author ORDER BY count DESC LIMIT 0, ".$limit);
        
        print "";
        printf(semr_i18n("Top %s of all commentators"), $limit);
        print "
";
        if (empty($topcommenters)) {
            print '... '.  semr_i18n("no entries at all").'';
            print "
";
            return;
        }
        
        print "";
        print "";
        print "";
        print "| ".semr_i18n("User")."";
        print " | ".semr_i18n("Email")."";
        print " | ".semr_i18n("Homepage")."";
        print " | ".semr_i18n("Comments")."";
        print " | 
";
        print "";
        print "";
        
        foreach ($topcommenters as $key=>$topcommenter) {
            $commenter = $topcommenter->commenter;
            $email = $topcommenter->email;
            $homepage = $topcommenter->homepage;
                if($homepage=="http://") $homepage="";
                $url=parse_url($homepage);
                $homepage = $url['host'];
            $count = $topcommenter->count;
            print "";
            print "| ".$commenter."";
            print " | ".$email."";
            print " | ".$homepage."";
            print " | ".$count."";
            print " | 
";
        }
        
        print "";
        print "
";
        print "
";
    }
    
### AKTUELL Anzeige
	print "";
		print "
";
		print "
";
		print "
SemmelstatzR > ".semr_i18n("Current Statz")."
";
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
		if ($sem_options["statz_show_useronline"]) sem_showWhoIsOnline();
		sem_draw24HoursGoo();
		if ($sem_options["statz_show_todayusers"]) sem_showWhoWasOnlineToday();
		if ($sem_options["statz_show_dailystatz"]) sem_showDailyStatz();
		if ($sem_options["statz_show_referers"]) sem_showReferers();
		if ($sem_options["statz_show_keywords"]) sem_showKeyword();
		if ($sem_options["statz_show_todayreads"]) sem_showTodayTopReads();
		if ($sem_options["statz_show_reads"]) sem_showTopReads();
		if ($sem_options["statz_show_topcommposts"]) sem_showTopCommented();
		if ($sem_options["statz_show_commenters"]) sem_showCommenters();
		sem_showCopyright();
	print "