<?php

/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2005 Radek HULÁN
  * http://hulan.cz/contact/
  *
  * ----------------------------------------------------------------
  * 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.
**/

class NP_Referrer extends NucleusPlugin {

var $searchengines,$count;

	function init() {
		$this->searchengines = explode(",",$this->getOption('searchengines').",216.239,alltheweb,vindex,metacrawler,mamma.com,excite,hotbot,drs.yahoo");
	}

	function getEventList() { 
		return array('PostPluginOptionsUpdate'); 
	}

	function event_PostPluginOptionsUpdate(&$data) {
		if ($this->getOption('clean')=='1') {
			global $SQL_TYPE;
			if ( $SQL_TYPE==_SQLITE )
				sql_query('delete from '.sql_table('plug_referrer'));
			else
				sql_query('truncate table '.sql_table('plug_referrer'));
			$this->setOption('clean','0');
		}
	}

	function doSkinVar($skintype, $what='last', $amount=10, $showEngine=2, $headertype=0, $pre='', $post='') {
        global $member;
        global $manager;
        global $blog;
        global $CONF;
        $logtime    = time();
        $refer      = serverVar('HTTP_REFERER');
        $parsed     = parse_url($refer);
        $refParts   = explode("/", $refer);
        if ($_SERVER['QUERY_STRING']) {
            $pageRef    = serverVar('PHP_SELF')."_".serverVar('QUERY_STRING');
        } else {
            $pageRef    = serverVar('PHP_SELF');
        }
        if (! $blog ) {
            if (is_object($manager)) {
                $blog =& $manager->getBlog($CONF['DefaultBlog']);
            }
        }

        // see if we need to block this referrer
        if ($parsed[scheme] !=="http")    { $refer = ""; }
        // not local please ...
        if ($parsed[host] == serverVar('HTTP_HOST')        ||
            $parsed[host] == "www.".serverVar('HTTP_HOST') ||
            "www.".$parsed[host] == serverVar('HTTP_HOST')
            )
            { $refer = ""; }

        $filterip      = explode(",",$this->getOption('blockIp'));
        $filterlist    = explode(",",$this->getOption('blockDomain').",terrafirmascripts,thephpchef,phpwebsupport,vanimar,bestoftolkien,yuki-no-kisho,buy-drugs-online,mega-dating,pi-o.com,iamwin");
        $addbreaks     = $this->getOption('addBR');
        $maxlength     = $this->getOption('maxlength');
        $showtime      = $this->getOption('showDateTime');

        // ignore filtered domains
        foreach($filterip as $block) {
            if (strstr(serverVar('REMOTE_ADDR'),$block)) {
                $refer = "";
            }
        }
        foreach($filterlist as $block) {
            if (strstr($parsed[host],$block)) {
                $refer = "";
            }
        }

        // search engine ??
        $isEngine = 0;
        foreach($this->searchengines as $engine ) {
            if (strstr($refer,$engine)) {
                $extra = $parsed[query]; // searchwords used ....
                $isEngine = 1;
            }
        }

        // if we didn't block this, let's put it in the db ....
        // and if this is the first time we were called then ...
        if ($refer && !$this->count == 1) {
            if (! $extra) {
                // find the page title ...
                $fp = @fopen ($refer, "r");
                if ($fp){
                    $ref_str = fread($fp, 4096);
                    if (eregi("<title>(.*)</title>", $ref_str, $out)) {
                        $extra = htmlspecialchars ($out[1],ENT_QUOTES);
                    }
                }
                if (! $extra) {$extra = $parsed[host]." ".$parsed[path];}
            }

            // let's put it in the db now ...
            $query = "INSERT INTO ".sql_table('plug_referrer')." (ref_to, ref_from, ref_extra, ref_engine) VALUES ('".sql_escape($pageRef)."','".sql_escape($refer)."','".sql_escape($extra)."', ".$isEngine.")";
            sql_query($query);
        }
        $this->count = 1; // we've been here now.


		// show stats only to members
        if (!$member->isLoggedIn()) return;

        if ($headertype==1) echo $this->getOption('domaintext').$pre."\n";
        if ($headertype==2) echo $this->getOption('pagetext').$pre."\n";


        ////////////////
        //       Lastall
        ////////////////
        if ($what == "lastall") {
            $query = "SELECT ref_from            AS refFrom"
                   . ",      ref_extra           AS refShow"
                   . ",      ref_to              AS refTo"
                   . ", UNIX_TIMESTAMP(ref_when) AS refWhen"
                   . " FROM ".sql_table('plug_referrer');
            if ($showEngine < 2 ) {
                $query .= " WHERE ref_engine = ".$showEngine;
            }
            $query .= " ORDER BY ref_when DESC"
                   .  " LIMIT ".$amount;
            $refs = sql_query($query);
            if ($refs) {
                echo "<table>";
                while ($ref = sql_fetch_object($refs)) {
                    $ref->refTo = str_replace("_","?",$ref->refTo);
                    $ref->refShow = $this->searchString($ref->refFrom, $ref->refShow);
                    $temp = parse_url($ref->refFrom);
                    $host = $temp['host'];
                    $titletag = $host." : ".$ref->refShow;
                    $ref->refShow = explode("/",$ref->refShow);
                    $ref->refShow = implode(" ",$ref->refShow);
                    $ref->refShow = explode("3F",$ref->refShow);
                    $ref->refShow = implode(" ",$ref->refShow);
                    $ref->refShow = explode("3D",$ref->refShow);
                    $ref->refShow = implode(" ",$ref->refShow);
                    $ref->refShow = explode("&",$ref->refShow);
                    $ref->refShow = implode(" &",$ref->refShow);

                    echo "<tr><td>";
                    echo "<a title='".$this->convertstring($titletag)."' href='".htmlspecialchars($ref->refFrom)."'>".strftime("%e/%m/%g - %R",$ref->refWhen + (0 * 3600))." ".$this->convertstring(sql_unescape($ref->refShow))."</a>";
                    echo "</td><td>";
                    $linktxt  = substr($ref->refTo,strpos($ref->refTo,"?") + 1);
                    if( strpos($linktxt,"temid") > 0 ) {
                        $citemid = substr($linktxt,strpos($linktxt,"itemid=") + 7);
                        if ( strpos($citemid,"&") > 0) {
                            $citemid = substr($citemid,0, strpos($citemid,"&"));
                        }
                        $titleq = "SELECT ititle FROM ".sql_table('item')." WHERE inumber = ". $citemid;
                        $result = sql_query($titleq);
                        $row = sql_fetch_object($result);
                        if (! $row->ititle == "") {
                            $linktxt  = $row->ititle;
                        } else {
                            $linktxt = $citemid . "-" .$linktxt;
                        }
                    }

                    echo "<a href='".htmlspecialchars($ref->refTo)."'> -> ".$this->convertstring($linktxt)."</a>\n";
                    echo "</td></tr>";
                }
                echo "</table>";
            }
        }
        ////////////////
        // Stats
        ////////////////
        if ($what == "stats") {
            $query = "SELECT COUNT(*) as numRows FROM ".sql_table('plug_referrer')." WHERE ref_engine = 1";
            $res = sql_query($query);
        	$obj = sql_fetch_object($res);
            $searchers = $obj->numRows;
            $query = "SELECT COUNT(*) as numRows FROM ".sql_table('plug_referrer')." WHERE ref_engine = 0 AND ref_when > date_sub(now(), interval 30 day)";
            $res = sql_query($query);
        	$obj = sql_fetch_object($res);
            $hits = $obj->numRows;
            $total = $hits + $searchers;
            echo "<table><tr><td>Total referrers over the last 30 days: </td><td collspan='2'><strong>" .$total."</td></tr>";
            $perc = ($hits / $total) * 100;
            echo "<tr><td>Hits: </td><td><strong>" .$hits."</td><td> (".round($perc,2)." %)</strong></td></tr>";
            $perc = ($searchers / $total) * 100;
            echo "<tr><td>Dolers: </td><td><strong>".$searchers."</strong></td><td> (".round($perc,2)." %)</td></tr>";
            // last 24 hour ...
            $query = "SELECT COUNT(*) as numRows FROM ".sql_table('plug_referrer')." WHERE ref_when > date_sub(now(), interval 1 day)";
            $res = sql_query($query);
        	$obj = sql_fetch_object($res);
        	$today = $obj->numRows;
            $query = "SELECT COUNT(*) as numRows FROM ".sql_table('plug_referrer')." WHERE ref_when > date_sub(now(), interval 2 day) AND ref_when < date_sub(now(), interval 1 day)";
            $res = sql_query($query);
        	$obj = sql_fetch_object($res);
        	$yesterday = $obj->numRows;
        	$perc = (($yesterday - $today) / $yesterday) * -100;
            echo "<tr><td>Today: </td><td><strong>".$today."</strong></td><td> (".round($perc,2)." %)</td></tr>";
            echo "<tr><td>Yesterday: </td><td collspan='2'><strong>".$yesterday."</strong></td></tr>";
            echo "</table>";
        }
        ////////////////
        // Last or Item
        ////////////////
        if ($what == "last" || $what  ==  "item") {
            $query = "SELECT ref_from            AS refFrom"
                   . ",      ref_extra           AS refShow"
                   . ", UNIX_TIMESTAMP(ref_when) AS refWhen"
                   . " FROM ".sql_table('plug_referrer')." WHERE ";

            if ($showEngine < 2 ) {
                $query .= " ref_engine = ".$showEngine." AND ";
            }

            $query .=  " ref_to = '".sql_escape($pageRef)."' ORDER BY ref_when DESC LIMIT ".$amount;
            $refs = sql_query($query);
            if ($refs) {
                while ($ref = sql_fetch_object($refs)) {
                    $ref->refShow = $this->searchString($ref->refFrom, $ref->refShow);
                    $temp = parse_url($ref->refFrom);
                    $host = $temp['host'];
                    $titletag = $host." : ".$ref->refShow;
                    if ($what == "item" ){
                        echo "<a title='".$this->convertstring($titletag)."' href='".htmlspecialchars($ref->refFrom)."'>";
                        if ($showtime == yes) {
                            echo strftime("%e/%m/%g - %R",$ref->refWhen + ($blog->getTimeOffset() * 3600))." ";
                        }
                        echo $this->convertstring(sql_unescape($ref->refShow))."</a>";
                    } else {
                        echo "<a title='".$this->convertstring($titletag)."' href='".htmlspecialchars($ref->refFrom)."'>";
                        if ($showtime == yes) {
                            echo strftime("%R",$ref->refWhen + ($blog->getTimeOffset() * 3600))." ";
                        }
                        echo $this->convertstring(substr(sql_escape($ref->refShow),0,$maxlength))."</a>";
                    }
                    if ($addbreaks == yes) {echo "<br />\n";}
                }
            }
        }
        ////////////////
        //          Pop
        ////////////////
        if ($what == "pop") { // which pages get hits from outside?
            $query = "SELECT ref_to    AS refTo"
                   . ",      ref_extra AS refShow"
                   . ", COUNT(ref_to)  AS refCount"
                   . " FROM ".sql_table('plug_referrer');
            if ($showEngine < 2 ) {
                $query .= " WHERE ref_engine = ".$showEngine;
            }
            $query .= " GROUP BY ref_to "
                   . " ORDER BY refCount DESC"
                   . " LIMIT 1," .$amount; // skip the first that'll be the normal index ....
            $refs = sql_query($query);
            if ($refs) {
                while ($ref = sql_fetch_object($refs)) {
                    $ref->refTo = str_replace("_","?",$ref->refTo);
                    $titletag = $ref->refCount ." hits for: " .htmlspecialchars($ref->refTo);
                    $linktxt  = $ref->refCount." ".substr($ref->refTo,strpos($ref->refTo,"?") + 1);
                    if( strpos($linktxt,"itemid") > 0 ) {
                        $citemid = substr($linktxt,strpos($linktxt,"itemid=") + 7);
                        if ( strpos($citemid,"&") > 0) {
                            $citemid = substr($citemid,0, strpos($citemid,"&"));
                        }
                        $titleq = "SELECT ititle FROM ".sql_table('item')." WHERE inumber = ". $citemid;
                        $result = sql_query($titleq);
                        $row = sql_fetch_object($result);
                        if (! $row->ititle == "") {
                            $linktxt  = $ref->refCount." ".$row->ititle;
                        }
                    }
                    echo "<a title='".$this->convertstring($titletag)."' href='".htmlspecialchars($ref->refTo)."'>".$linktxt."</a>\n";
                }
            }
        }
        ////////////////
        // Top or Topall
        ////////////////
        if ($what == "top" || $what == "topall" ) { // get the top
            $query = "SELECT ref_from         AS refFrom"
                   . ",      ref_extra        AS refShow"
                   . ", UNIX_TIMESTAMP(ref_when) AS refWhen"
                   . ", COUNT(ref_from)       AS refCount"
                   . " FROM ".sql_table('plug_referrer');
            if ($showEngine < 2 ) {
                $query .= " WHERE ref_engine = ".$showEngine;
            }

            $query .= " GROUP BY ref_from "
                   . " ORDER BY refCount DESC"
                   . " LIMIT " .$amount;
            $refs = sql_query($query);
            if ($refs) {
                while ($ref = sql_fetch_object($refs)) {
                    $ref->refShow = $this->searchString($ref->refFrom, $ref->refShow);
                    $temp = parse_url($ref->refFrom);
                    $host = $temp['host'];
                    $titletag = $host." : ".$ref->refShow;
                    echo  "<a title='".$this->convertstring($titletag)."' href='".htmlspecialchars($ref->refFrom)."'>".$ref->refCount." ";
                    if ($what == "top") {
                        echo $this->convertstring(substr(sql_unescape($ref->refShow),0,$maxlength));
                    } else {
                        echo $this->convertstring(sql_unescape($ref->refShow));
                    }
                    echo "</a>";
                    if ($addbreaks == yes) {echo "<br />\n";}
                }
            }
        }
		
		if ($headertype==1 || $headertype==2) echo $post;
    }

  	function _makefancyTitle($title) {
  		$title = trim($title);
  		$title = strip_tags($title);
  		$title = iso2ascii($title);
  		preg_match_all('/[a-zA-Z0-9]+/', $title, $nt);
  		$urltitle = implode(' ', $nt[0]);
  		return $urltitle;
  	}

    function convertstring($text){
      return $this->_makefancyTitle($text);
    }

    function searchString($from, $query) {
        foreach ($this->searchengines as $engine ) {
            $q = '';
            if (strstr($from,$engine)) {
                parse_str($query,$res);
                // $res = explode('&',$query);
                $q = $res['q'];
                // not 'q' ?
                if ($q == "") {$q = $res['query'];}
                // not 'query'?
                if ($q == "") {$q = $res['p'];}
                if ($q == "") {$q = $res['search_for'];}
                if ($q == "") {$q = $res['MT'];}
                if ($q == "") {$q = $res['as_q'];}
                if ($q == "") {$q = $res['qr'];}
                if ($q == "") {$q = $res['vp'];}
                if ($q == "") {$q = $res['va'];}
                if ($q == "") {$q = $res['qkw'];}
                if ($q == "") {$q = $res['searchfor'];}

                if (strstr($from,"google")) {
                    $query = "[g] ";
                } else if (strstr($from,"ilse")) {
                    $query = "[i] ";
                } else if (strstr($from,"altavista")) {
                    $query = "[a] ";
                } else if (strstr($from,"search.msn")) {
                    $query = "[m] ";
                } else if (strstr($from,"zoek.vinden") || strstr($from,"zoeken.track") ) {
                    $query = "[z] ";
                } else if (strstr($from,"lycos")) {
                    $query = "[l] ";
                } else if (strstr($from,"yahoo")) {
                    $query = "[y] ";
                } else {
                    $query = "[o] ";
                }
                $query .= htmlspecialchars($q);
            }
            if ($q > '') { return $query; }
        }
        return $query;
    }

    // name of plugin
    function getName()   { return 'Referrer';   }
    // author of plugin
    function getAuthor() { return '-=Xiffy=- :: mod by Radek HULAN'; }
    function getURL()    { return 'http://xiffy.nl/weblog/'; }
    function getVersion(){ return '1.03'; }
    function getDescription() {
        return 'Keeps track of the referring pages. Call with Referrer(10,last) to show the last 10 referrers.  Referrer(10,top) to see the top referrer';
    }

  	function supportsFeature($feature) {
		switch($feature) {
			case 'SqlTablePrefix':
				return 1;
			default:
				return 0;
		}
	}

  function install(){
        $this->createOption('addBR','Add linebreaks <br /> to the links', 'yesno','yes');
        $this->createOption('showDateTime', 'Show when the referring occured', 'yesno', 'yes');
        $this->createOption('maxlength','How much character to show maximum', 'text', '30');
        $this->createOption('blockDomain','Comma seperated list from domains to ignore','textarea','spankit,bobbakazoo,search4pornography,arizonasba,chocoborancher,chaiti');
        $this->createOption('blockIp','Comma seperated list from domains to ignore','textarea','66.28.25.3,64.75.32.137,217.198.193.71,18.85.23.46');
        $this->createOption('searchengines','Comma seperated list of search engine names','textarea','google,search.yahoo,ilse,fasttrack,search.msn,zoek,altavista');
        $this->createOption('domaintext','Text to display for domain:','text','<h2>Domain referrers</h2>');
        $this->createOption('pagetext','Text to display for page:','text','<h2>Page referrers</h2>');
		$this->createOption('clean','Clean all referrers completely now?','select','0', 'no|0|yes|1');
    }
	
    function getTableList() {
        return array( /* sql_table('plug_referrer') - no need to backup this */ );
    }

}
?>