<?php
/**
 * File: functions.semr.php
 *
 * @package     SemmelstatzR
 * @version     $Rev$
 * @since       1.0.0
 * @author      SEM-Team
 * @copyright   (c)2011 SEM-Team
 * @link        http://sourceforge.net/projects/semmelstatz/
 * @license     http://www.gnu.org/licenses/gpl-3.0.html
 * 
 * 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 3 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, see <http://www.gnu.org/licenses/>.  
 *
 * $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
*/
### Encodierung der IP-Adresse durch simple arithmetische Operation
    function sem_encodeIP($ip) {
        $ip_parts = split("[.]", $ip);
        $new_ip = ($ip_parts[0]+700) . "." . ($ip_parts[1]*2) . "." . ($ip_parts[2]+600) . "." . ($ip_parts[3]*3);
        return $new_ip;
    }

### Decodierung der IP-Adresse durch simple arithmetische Operation
    function sem_decodeIP($ip) {
        $ip_parts = split("[.]", $ip);
        $new_ip = ($ip_parts[0]-700) . "." . ($ip_parts[1] / 2) . "." . ($ip_parts[2]-600) . "." . ($ip_parts[3]/3);
        return $new_ip;
    }

### Ist IP-Adresse codiert?
    function sem_checkIfIPisEncoded($ip) {
        $ip_parts = split("[.]", $ip);
        if($ip_parts[0]>700) {
            return true;
        }
        else {
            return false;
        }
    }

### Auslesen der h�chsten Post-ID
    function sem_getMaxPostID() {
        global $wpdb;
        $maxpostid = $wpdb->get_var("SELECT MAX(ID) FROM ".$wpdb->posts." LIMIT 0,1");
        return $maxpostid; //Ganzzahl
    }

### Auslesen des User- bzw. Kommentarautornamen
	function sem_getUsername() {
        global $user_ID, $user_login, $isAdmin;

		get_currentuserinfo();

		if($user_ID > 0) {
		    $useronline = $user_login;

            if(current_user_can('manage_options')) {
                $isAdmin = 1;
            }
            else {
                $isAdmin = 0;
            }
        }
        elseif(isset($_COOKIE["comment_author_".COOKIEHASH])) {
            $useronline = trim($_COOKIE["comment_author_".COOKIEHASH]);
            $isAdmin = -1;
		}
		else {
			$useronline = "Gast";
			$isAdmin = -1;
		}
        return $useronline;
    }

/**
 * Check if agent is a bot
 * 
 * @deprecated use Agents-object in the future
 *
 * @param string $user_agent
 * @return boolean 
 */
function sem_AreYouBot($user_agent) {
    require_once 'class.agents.php';
    $oCheckAgent = new Agents($user_agent);
    return $oCheckAgent->isBot();
}

/**
 * Referer nach Suchmaschinen-Queries und interner Suche prüfen und Suchstring extrahieren
 * 
 * @param string $referer
 * @return string name of searchengine and keywords 
 */
function sem_getKeyword($referer) {
    if(empty($referer)) return false;
    $homehost = '%'.(substr($_SERVER['SERVER_NAME'],0,4) == 'www.')?
             substr($_SERVER['SERVER_NAME'],4) . '%':
         $_SERVER['SERVER_NAME'] . '%';
     
    $keyword = parse_url($referer);
    if(!isset($keyword['host']) || !isset($keyword['query'])) return false;

		if (preg_match("/google\./i", $keyword["host"])) {
			if (preg_match("/imgurl/i", $keyword["query"])) {
				parse_str($keyword["query"],$q);
				$keyword = substr($q["prev"],10);
			}
			else if (preg_match("/translate\./i", $keyword["host"])) {
				parse_str($keyword["query"],$q);
				$keyword = $q["q"];
			}
			else {
				parse_str($keyword["query"],$q);
				$keyword = $q["q"];
			}
			if($keyword == "") return; return "Google: ".$keyword;
		}
		elseif (preg_match("/search\.live\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "LiveSearch: ".$keyword;
		}
		elseif (preg_match("/bing\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "Bing: ".$keyword;
		}
		elseif (preg_match("/yahoo\./i", $keyword["host"])) {
			if (preg_match("/images/i", $keyword["query"])) {
				parse_str($keyword["query"],$q);
				$keyword = $q["p"];
			}
			else {
				parse_str($keyword["query"],$q);
				$keyword = $q["p"];
			}
			if($keyword == "") return; return "Yahoo: ".$keyword;
		}
		elseif (preg_match("/aol\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "AOL: ".$keyword;
		}
		elseif (preg_match("/aolsvc\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "AOL: ".$keyword;
		}
		elseif (preg_match("/search\.msn\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "MSN: ".$keyword;
		}
		elseif (preg_match("/gmx\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["su"];
			if($keyword == "") return; return "GMX: ".$keyword;
		}
		elseif (preg_match("/\.bild\.t\-/i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["query"];
			if($keyword == "") return; return "BILD: ".$keyword;
		}
		elseif (preg_match("/t\-online\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "T-Online: ".$keyword;
		}
		elseif (preg_match("/suche\.web\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["su"];
			if($keyword == "") return; return "WEB.de: ".$keyword;
		}
		elseif (preg_match("/suche\.lycos\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["query"];
			if($keyword == "") return; return "Lycos: ".$keyword;
		}
		elseif (preg_match("/altavista\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "Altavista: ".$keyword;
		}
		elseif (preg_match("/alltheweb\./i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["q"];
			if($keyword == "") return; return "alltheweb: ".$keyword;
		}
		elseif (preg_match("/technorati\.com\/search\//", $referer)) {
			$q = preg_split("/technorati\.com\/search\//", $referer,-1,PREG_SPLIT_NO_EMPTY);
			$keyword = $q[1];
			if($keyword == "") return; return "Technorati: ".$keyword;
		}
		elseif (preg_match("/".$homehost."/i", $keyword["host"])) {
			parse_str($keyword["query"],$q);
			$keyword = $q["s"];
			if($keyword == "") return; return semr_i18n("Internal search: ").$keyword;
		}
		else {
			return;
		}
    }

### Anzahl der Datens�tze in der statz-Tabelle
    function sem_showNumStatzEntries() {
        global $wpdb;
        $numstatzentries = $wpdb->get_var("SELECT COUNT(id) FROM ".$wpdb->statz);
        return $numstatzentries; // Zahl
    }

### Aufgezeichnete Tage in der statz-Tabelle
	function sem_countDaysInStatzTable() {
		global $wpdb;
		$firstdate = $wpdb->get_var("SELECT MIN(time) FROM ".$wpdb->statz." LIMIT 0,1");
        if(!$firstdate) {
            return 1;
        }
        else {
            $firstdate = strtotime($firstdate); $now = time();
            $days = (int) (($now - $firstdate) / (60*60*24)+1);
            return $days; // KOMPLETTE! Tage
        }
	}

### Wenn Tage in statz-Tabelle kleiner als Tage in Daily-Statz, dann nimm Tage in Daily-Statz
	function sem_compareLimitDays2DailyStatz () {
		global $wpdb;
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
		if (sem_countDaysInStatzTable() << $sem_options["statz_days_limit"]) {
			$sem_options["statz_days_limit"] = sem_countDaysInStatzTable();
			update_option("semmelstatzR_options", $sem_options);
		}
	}

/**
 * prints a copyright notiz
 */
function sem_showCopyright() {
    print "<p class='copyright'>semmelstatzR ". SEMMELSTATZR_VERSION .
            " happily coded by <a target='_blank' href='http://semmelstatz.sourceforge.net/'>SEM-Team<br />
                <a target='_blank' style='border:none;' href='http://sourceforge.net/projects/semmelstatz/'>
                <img src='".get_option('siteurl')."/wp-content/plugins/semmelstatzR/img/statzR.png' /></a></p>";
}

/**
 * empty statz table
 * 
 * @global type $wpdb
 * @return bool 
 */
function sem_truncateStatzTable() {
    global $wpdb;
    $wpdb->query('TRUNCATE TABLE '.$wpdb->statz);
    sem_optStatzTable();
    return ($wpdb->query("INSERT INTO `$wpdb->statz`(ip, time, referer, page, username) VALUES('127.0.0.1', NOW(),NULL,0,'statz-Tabelle geleert')"))?true:false;
}

/**
 *
 * @deprecated no need to hold unused functions in semR
 * @todo remove in next major release
 * @param int $days
 * @return boolean 
 */
function sem_delOldRecords($days) {
    return true;
}

### simpleEncoding f�r die GoogleChartAPI
	function sem_encodeChartData($values) {

		$maxValue = max($values);
		$simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		$chartData = "s:";
		  for ($i = 0; $i < count($values); $i++) {
			$currentValue = $values[$i];

			if ($currentValue > -1 && $maxValue <> 0) {
			$chartData.=substr($simpleEncoding,61*($currentValue/$maxValue),1);
			}
			  else {
			  $chartData.='_';
			  }
		  }
		return $chartData;
	}

### Datens�tze �lter als statz_recdays_limit-Tage l�schen
    function sem_delOutOfLimit() {
        global $wpdb;
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
        $today = time(); $days = $sem_options["statz_recdays_limit"];
        $enddatum = $today - ($days * 86400);
        $enddatum = date("Y-m-d", $enddatum) . " 23:59:59";
        $wpdb->query("DELETE FROM ".$wpdb->statz." WHERE time <= '".$enddatum."'");
        sem_optStatzTable();
    }

### Wenn AUTOMATISCHES LIMIT aktiviert, dann LIMITIERE und erh�he NEXT_CRON
    function sem_doCronStatzLimit() {
        sem_delOutOfLimit();
		$sem_options = get_option('semmelstatzR_options'); ### optionsarray auslesen
        $statz_next_cron = $sem_options["statz_next_cron"] + 86400;
		$sem_options["statz_next_cron"] = $statz_next_cron;
        update_option("semmelstatzR_options", $sem_options);
    }

### Konvertiert Strings von utf-8 in ISO-8859
    function sem_encodeToIso($string) {
        return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
    }

### statz-Tabelle optimieren
    function sem_optStatzTable() {
        global $wpdb;
        $wpdb->query("OPTIMIZE TABLE ".$wpdb->statz);
    }

### Unter bestimmten Voraussetzungen den Vortag in die statzhist-Tabelle schreiben
/**
 * @todo add action cache so we don't need to do it with every call
 * @global type $wpdb 
 */    
function sem_writeYesterdayToHist() {
    global $wpdb;
    if(!$wpdb->get_var("SELECT date FROM ".$wpdb->statzhist." WHERE substring(date,1,10) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")) {

        if($wpdb->get_var("SELECT COUNT(ip) FROM ".$wpdb->statz." WHERE substring(time,1,10) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")) {

            $yesterdays = $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 substring(time,1,10) = DATE_SUB(CURDATE(),
INTERVAL 1 DAY) GROUP BY date");

            foreach ($yesterdays as $yesterday) {
                $date = $yesterday->date;
                $visitors = $yesterday->visitors;
                $hits = $yesterday->hits;
                $referers = $yesterday->referers;
            }

            $sql = $wpdb->query("INSERT INTO ".$wpdb->statzhist." (date, referers, visitors, hits)
VALUES('$date', $referers, $visitors, $hits)");
        }
        else {
            $date = $wpdb->get_var("SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
            $sql = $wpdb->query("INSERT INTO ".$wpdb->statzhist." (date, referers, visitors, hits) VALUES('$date', 0, 0, 0)");
        }
    }
}

/* Summen der vergangenen Tage in die statzhist schreiben */
    function sem_writeOldDaysToHist() {
        global $wpdb;
        if(!$wpdb->get_var("SELECT date FROM ".$wpdb->statzhist." WHERE substring(date,1,10) <= DATE_SUB(CURDATE(), INTERVAL 1 DAY)")) {

            $theolddays = $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
			substring(time,1,10) <= DATE_SUB(CURDATE(), INTERVAL 1 DAY) GROUP BY date ORDER BY time ASC");

            foreach ($theolddays as $theoldday) {
                $date = $theoldday->date;
                $visitors = $theoldday->visitors; if(!$visitors) $visitors = 0;
                $hits = $theoldday->hits; if(!$hits) $hits = 0;
                $referers = $theoldday->referers; if(!$referers) $referers = 0;
                $sql = $wpdb->query("INSERT INTO ".$wpdb->statzhist." (date, referers, visitors, hits)
				VALUES('$date', $referers, $visitors, $hits)");
            }
        }
	}

/**
 * translate and return a string 
 * 
 * @uses wp-function __() and prefilled plugin gettextdomain
 * @author Ortwin Pinke
 * @since 1.0.0
 * 
 * @param string $sValue string to translate
 * @param string $sDomain gettextdomain
 * @return string translated string 
 */ 
function semr_i18n($sValue, $sDomain = "semmelstatzR") {
    return __($sValue, $sDomain);
}

/**
 * translate and echo a string
 * 
 * @uses wp-function _e() and prefilled plugin gettextdomain
 * @author Ortwin Pinke
 * @since 1.0.0
 * 
 * @param string $sValue
 * @param string $sDomain 
 * @return void
 */
function semr_i18ne($sValue, $sDomain = "semmelstatzR") {
    _e($sValue, $sDomain);
}

/**
 * translate and return a plural or singular string based on an amount
 * 
 * @uses wp-function _n() and prefilled plugin gettextdomain
 * @author Ortwin Pinke
 * @since 1.0.0
 * 
 * @param string $sSingular
 * @param string $sPlural
 * @param type $iNumber
 * @param string $sDomain
 * @return string 
 */
function semr_i18np($sSingular, $sPlural, $iNumber, $sDomain = "semmelstatzR") {
    return _n($sSingular, $sPlural, $iNumber, $sDomain);
}

/**
 *
 * @author anyexample.com
 * @license modified MIT see http://www.anyexample.com/license/
 * @link http://www.anyexample.com/programming/php/php_convert_rgb_from_to_html_hex_color.xml
 * @since 1.0.0
 * 
 * @param string $color
 * @return array 
 */
function semr_hex2rgb($color) {
    if ($color[0] == '#')
        $color = substr($color, 1);

    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0].$color[1],
                                 $color[2].$color[3],
                                 $color[4].$color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return false;

    $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

    return array($r, $g, $b);
}

/**
 *
 * @author anyexample.com
 * @license modified MIT see http://www.anyexample.com/license/
 * @link http://www.anyexample.com/programming/php/php_convert_rgb_from_to_html_hex_color.xml
 * @since 1.0.0
 * 
 * @param int $r
 * @param int $g
 * @param int $b
 * @return string 
 */
function semr_rgb2hex($r, $g=-1, $b=-1) {
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}
############################################## Ende SEMMELSTATZ-interne Funktionen
?>