b2evolution

Multilingual multiuser multiblog engine

b2evolution Technical Documentation (0.9.x) [ class tree: evocore ] [ index: evocore ] [ all elements ]

Source for file _functions_hitlogs.php

Documentation is available at _functions_hitlogs.php

  1. <?php
  2. /**
  3.  * Logging of hits, extraction of stats
  4.  *
  5.  * b2evolution - {@link http://b2evolution.net/}
  6.  * Released under GNU GPL License - {@link http://b2evolution.net/about/license.html}
  7.  * @copyright (c)2003-2005 by Francois PLANQUE - {@link http://fplanque.net/}
  8.  *
  9.  * @package evocore
  10.  * @author This file built upon code by N C Young (nathan@ncyoung.com) (http://ncyoung.com/entry/57)
  11.  */
  12. if!defined('DB_USER') ) die'Please, do not access this page directly.' );
  13.  
  14. //get most linked to pages on site
  15. //select count(visitURL) as count, visitURL from b2hitlog group by visitURL order by count desc
  16.  
  17. /*if ($refererList)
  18. {
  19.     print "referers:<br />";
  20.     $ar = refererList($refererList,"global");
  21.     print join("<br />",$ar);
  22. }
  23.  
  24. if ($topRefererList)
  25. {
  26.     print join("<br />",topRefererList($topRefererList,"global"));
  27. }
  28. */
  29.  
  30.  
  31. /**
  32.  * Log a hit on a blog page / rss feed
  33.  *
  34.  */
  35. function log_hit()
  36. {
  37.     global $DB$localtimenow$blog$tablehitlog$blackList$search_engines$user_agents;
  38.     global $doubleCheckReferers$comments_allowed_uri_scheme$HTTP_REFERER$page$ReqURI$ReqPath;
  39.     global $stats_autoprune;
  40.     
  41.     # TODO: check for already logged?
  42.  
  43.     $fullCurrentURL $_SERVER['SERVER_NAME']$ReqURI;
  44.     // debug_log( 'Hit Log: '. "full current url: ".$fullCurrentURL);
  45.  
  46.     $ref $HTTP_REFERER;
  47.     // debug_log( 'Hit Log: '. "referer: ".$ref);
  48.  
  49.     $RemoteAddr $_SERVER['REMOTE_ADDR'];
  50.     // debug_log( 'Hit Log: '. "Remote Addr: ".$RemoteAddr);
  51.     //$RemoteHost = $_SERVER['REMOTE_HOST'];
  52.     //debug_log( 'Hit Log: '. "Remote Host: ".$RemoteHost);
  53.  
  54.     $UserAgent = isset($_SERVER['HTTP_USER_AGENT']$_SERVER['HTTP_USER_AGENT''';
  55.     // debug_log( 'Hit Log: '. "User Agent: ".$UserAgent);
  56.     if ($UserAgent != strip_tags($UserAgent))
  57.     //then they have tried something funny,
  58.         //putting HTML or PHP into the HTTP_REFERER
  59.         debug_log'Hit Log: '.T_("bad char in User Agent"));
  60.         $UserAgent '';
  61.     }
  62.  
  63.     // debug_log( 'Hit Log: '."Languages: ".$_SERVER['HTTP_ACCEPT_LANGUAGE']);
  64.  
  65.     
  66.     $ignore 'no';  // So far so good
  67.     
  68.     if$ref != strip_tags($ref) )
  69.     //then they have tried something funny,
  70.         //putting HTML or PHP into the HTTP_REFERER
  71.         //$ignore = 'badchar';
  72.         debug_log'Hit Log: bad char in referer');
  73.         return;        // Hazardous
  74.     }
  75.     elseif$error validate_url$ref$comments_allowed_uri_scheme ) )
  76.     {    //if they are trying to inject javascript or a blocked (spam) URL
  77.         debug_log'Hit Log: '$error);
  78.         return;        // Hazardous
  79.     }
  80.     
  81.     // SEARCH BLACKLIST    
  82.     foreach$blackList as $site )
  83.     {
  84.         ifstrpos$ref$site !== false )
  85.         {
  86.             // $ignore = 'blacklist';
  87.             debug_log'Hit Log: 'T_('referer ignored')' ('T_('BlackList')')');
  88.             return;
  89.         }
  90.     }
  91.             
  92.     ifstristr($ReqPath'rss')
  93.             || stristr($ReqPath'rdf')
  94.             || stristr($ReqPath'atom')  )
  95.     {
  96.         $ignore 'rss';
  97.         // don't mess up the XML!! debug_log( 'Hit Log: referer ignored (RSS));
  98.     }
  99.     else
  100.     {    // Lookup robots
  101.         foreach ($user_agents as $user_agent)
  102.         {
  103.             if( ($user_agent[0== 'robot'&& (strstr($UserAgent$user_agent[1])) )
  104.             {
  105.                 $ignore "robot";
  106.                 debug_log'Hit Log: 'T_('referer ignored')' ('T_('robot')')');
  107.                 break;
  108.             }
  109.         }
  110.     }
  111.     
  112.     if$ignore == 'no' )
  113.     {
  114.         ifstrlen($ref13 )
  115.         {    // minimum http://az.fr/ , this will be considered direct access (although it could be https:)
  116.             $ignore 'invalid';
  117.             debug_log'Hit Log: 'T_('referer ignored')' ('T_('invalid')')' );
  118.         }
  119.     }
  120.  
  121.     if$ignore == 'no' )
  122.     {    // identify search engines
  123.         foreach($search_engines as $engine)
  124.         {
  125.             // debug_log( 'Hit Log: '."engine: ".$engine);
  126.             if(stristr($ref$engine))
  127.             {
  128.                 $ignore 'search';
  129.                 debug_log'Hit Log: 'T_('referer ignored')" ("T_('search engine')")");
  130.                 break;
  131.             }
  132.         }
  133.     }    
  134.  
  135.     if$doubleCheckReferers )
  136.     {
  137.         debug_log'Hit Log: 'T_('loading referering page') );
  138.  
  139.         // this is so that the page up until the call to
  140.         // logReferer will get shown before it tries to check
  141.         // back against the refering URL.
  142.         flush();
  143.  
  144.         $goodReferer 0;
  145.         if strlen($ref)
  146.         {
  147.             $fp @fopen ($ref'r');
  148.             if ($fp)
  149.             {
  150.                 //timeout after 5 seconds
  151.                 socket_set_timeout($fp5);
  152.                 while (!feof ($fp))
  153.                 {
  154.                     $page .= trim(fgets($fp));
  155.                 }
  156.                 if (strstr($page,$fullCurrentURL))
  157.                 {
  158.                     debug_log'Hit Log: 'T_('found current url in page') );
  159.                     $goodReferer 1;
  160.                 }
  161.             }
  162.         else {
  163.             // Direct accesses are always good hits
  164.             $goodReferer 1;
  165.         }
  166.  
  167.         if(!$goodReferer)
  168.         {    // This was probably spam!
  169.             debug_log'Hit Log: 'sprintf('did not find %s in %s'$fullCurrentURL$page ) );
  170.             $ref="";
  171.             return;
  172.         }
  173.  
  174.     }
  175.  
  176.     $baseDomain preg_replace("/https?:\/\//i"""$ref);
  177.     $baseDomain preg_replace("/^www\./i"""$baseDomain);
  178.     $baseDomain preg_replace("/\/.*/i"""$baseDomain);
  179.  
  180.     $sql "INSERT INTO $tablehitlog( visitTime, visitURL, hit_ignore, referingURL, baseDomain, 
  181.                                                                         hit_blog_ID, hit_remote_addr, hit_user_agent ) 
  182.                     VALUES( FROM_UNIXTIME(".$localtimenow."), '".$DB->escape($ReqURI)."', '$ignore',
  183.                                     '".$DB->escape($ref)."', '".$DB->escape($baseDomain)."', $blog
  184.                                     '".$DB->escape($RemoteAddr)."', '".$DB->escape($UserAgent)."')";
  185.     $DB->query$sql );
  186.  
  187.     /*
  188.      * Auto pruning of old stats
  189.      */
  190.     ifisset($stats_autoprune&& ($stats_autoprune 0) )
  191.     {    // Autopruning is requested
  192.         $sql "DELETE FROM T_hitlog
  193.                          WHERE visitTime < '".date'Y-m-d'$localtimenow ($stats_autoprune 86400) )."'";
  194.                                                                                                                         // 1 day = 86400 seconds
  195.         $rows_affected $DB->query$sql );
  196.         debug_log'Hit Log: autopruned '.$rows_affected.' rows.' );
  197.     }
  198.  
  199. }
  200.  
  201.  
  202. /**
  203.  * Delete a hit
  204.  *
  205.  * {@internal hit_delete(-) }}
  206.  *
  207.  * @param int ID to delete
  208.  */
  209. function hit_delete$hit_ID )
  210. {
  211.     global $DB$tablehitlog;
  212.  
  213.     $sql ="DELETE FROM $tablehitlog WHERE visitID = $hit_ID";
  214.     $DB->query$sql );
  215.  
  216. }
  217.  
  218.  
  219. /**
  220.  * Delete all hits from a certain date
  221.  *
  222.  * {@internal hit_prune(-) }}
  223.  *
  224.  * @param int unix timestamp to delete hits for
  225.  */
  226. function hit_prune$date )
  227. {
  228.     global $DB$tablehitlog;
  229.  
  230.     $iso_date date ('Y-m-d'$date);
  231.     $sql ="DELETE FROM $tablehitlog WHERE DATE_FORMAT(visitTime,'%Y-%m-%d') = '$iso_date'";
  232.     $DB->query$sql );
  233.  
  234. }
  235.  
  236.  
  237. /**
  238.  * Change type for a hit
  239.  *
  240.  * {@internal hit_change_type(-) }}
  241.  *
  242.  * @param int ID to change
  243.  * @param string new type, must be valid ENUM for hit_ignore field
  244.  */
  245. function hit_change_type$hit_ID$type )
  246. {
  247.     global $DB$tablehitlog;
  248.  
  249.     $sql ="UPDATE $tablehitlog ".
  250.                 "SET hit_ignore = '$type', ".
  251.                 "    visitTime = visitTime ".    // prevent mySQL from updating timestamp
  252.                 "WHERE visitID = $hit_ID";
  253.     $DB->query$sql );
  254. }
  255.  
  256.  
  257. /**
  258.  *
  259.  * {@internal refererList(-) }}
  260.  *
  261.  * Extract stats
  262.  */
  263. function refererList(
  264.     $howMany 5,
  265.     $visitURL '',
  266.     $disp_blog 0,
  267.     $disp_uri 0,
  268.     $type "'no'",        // 'no' normal refer, 'invalid', 'badchar', 'blacklist', 'rss', 'robot', 'search'
  269.     $groupby '',     // baseDomain
  270.     $blog_ID '',
  271.     $get_total_hits false// Get total number of hits (needed for percentages)
  272.     $get_user_agent false // Get the user agent
  273. {
  274.     global     $DB$tablehitlog$res_stats$stats_total_hits$ReqURI;
  275.  
  276.     autoquote$type );        // In case quotes are missing
  277.  
  278.     $ret array();
  279.  
  280.     //if no visitURL, will show links to current page.
  281.     //if url given, will show links to that page.
  282.     //if url="global" will show links to all pages
  283.     if (!$visitURL)
  284.     {
  285.         $visitURL $ReqURI;
  286.     }
  287.  
  288.     if$groupby == '' )
  289.     {    // No grouping:
  290.         $sql "SELECT visitID, UNIX_TIMESTAMP(visitTime) AS visitTime, referingURL, baseDomain";
  291.     }
  292.     else
  293.     {    // group by
  294.         $sql "SELECT COUNT(*) AS totalHits, referingURL, baseDomain";
  295.     }
  296.     if$disp_blog )
  297.     {
  298.         $sql .= ", hit_blog_ID";
  299.     }
  300.     if$disp_uri )
  301.     {
  302.         $sql .= ", visitURL";
  303.     }
  304.     if$get_user_agent )
  305.     {
  306.         $sql .= ", hit_user_agent";
  307.     }
  308.     
  309.     $sql_from_where " FROM $tablehitlog WHERE hit_ignore IN ($type)";
  310.     if!empty($blog_ID) )
  311.     {
  312.         $sql_from_where .= " AND hit_blog_ID = '$blog_ID'";
  313.     }
  314.     if ($visitURL != "global")
  315.     {
  316.         $sql_from_where .= " AND visitURL = '$visitURL'";
  317.     }
  318.  
  319.     $sql .= $sql_from_where;
  320.  
  321.     if$groupby == '' )
  322.     {    // No grouping:
  323.         $sql .= " ORDER BY visitID DESC";
  324.     }
  325.     else
  326.     {    // group by
  327.         $sql .= "    GROUP BY $groupby ORDER BY totalHits DESC";
  328.     }
  329.     $sql .= " LIMIT $howMany";
  330.  
  331.     $res_stats $DB->get_results$sqlARRAY_A );
  332.  
  333.     if$get_total_hits )
  334.     {    // we need to get total hits
  335.         $sql "SELECT COUNT(*) ".$sql_from_where;
  336.         $stats_total_hits $DB->get_var$sql );
  337.     }
  338.     else
  339.     {    // we're not getting total hits
  340.         $stats_total_hits 1;        // just in case some tries a percentage anyway (avoid div by 0)
  341.     }
  342.  
  343. }
  344.  
  345.  
  346. /*
  347.  * stats_hit_ID(-)
  348.  */
  349. function stats_hit_ID()
  350. {
  351.     global $row_stats;
  352.     echo $row_stats['visitID'];
  353. }
  354.  
  355. /*
  356.  * stats_hit_remote_addr(-)
  357.  */
  358. {
  359.     global $row_stats;
  360.     echo $row_stats['hit_remote_addr'];
  361. }
  362.  
  363. /*
  364.  * stats_time(-)
  365.  */
  366. function stats_time$format '' )
  367. {
  368.     global $row_stats;
  369.     if$format == '' 
  370.         $format locale_datefmt().' '.locale_timefmt();
  371.     echo date_i18n$format$row_stats['visitTime');
  372. }
  373.  
  374.  
  375. /*
  376.  * stats_total_hit_count(-)
  377.  */
  378. {
  379.     global $stats_total_hits;
  380.     echo $stats_total_hits;
  381. }
  382.  
  383.  
  384. /*
  385.  * stats_hit_count(-)
  386.  */
  387. function stats_hit_count()
  388. {
  389.     global $row_stats;
  390.     echo $row_stats['totalHits'];
  391. }
  392.  
  393.  
  394. /*
  395.  * stats_hit_percent(-)
  396.  */
  397. function stats_hit_percent
  398.     $decimals 1
  399.     $dec_point '.' )
  400. {
  401.     global $row_stats$stats_total_hits;
  402.     $percent $row_stats['totalHits'100 $stats_total_hits;
  403.     echo number_format$percent$decimals$dec_point'' ).'&nbsp;%';
  404. }
  405.  
  406.  
  407. /*
  408.  * stats_blog_ID(-)
  409.  */
  410. function stats_blog_ID()
  411. {
  412.     global $row_stats;
  413.     echo $row_stats['hit_blog_ID'];
  414. }
  415.  
  416.  
  417. /*
  418.  * stats_blog_name(-)
  419.  */
  420. function stats_blog_name()
  421. {
  422.     global $row_stats;
  423.     $stats_blogparams get_blogparams_by_ID$row_stats['hit_blog_ID');
  424.     echo format_to_output$stats_blogparams->blog_name'htmlbody' );
  425. }
  426.  
  427.  
  428. /*
  429.  * stats_referer(-)
  430.  */
  431. function stats_referer$before=''$after=''$disp_ref true )
  432. {
  433.     global $row_stats;
  434.     $ref trim($row_stats['referingURL']);
  435.     ifstrlen($ref)
  436.     {
  437.         echo $before;
  438.         if$disp_ref echo htmlentities$ref );
  439.         echo $after;
  440.     }
  441. }
  442.  
  443.  
  444. /*
  445.  * stats_basedomain(-)
  446.  */
  447. function stats_basedomain$disp true )
  448. {
  449.     global $row_stats;
  450.     if$disp )
  451.         echo htmlentities$row_stats['baseDomain');
  452.     else
  453.         return $row_stats['baseDomain'];
  454. }
  455.  
  456.  
  457. /**
  458.  * stats_search_keywords(-)
  459.  *
  460.  * Displays keywords used for search leading to this page
  461.  */
  462. {
  463.     global $row_stats;
  464.     $kwout '';
  465.     $ref $row_stats['referingURL'];
  466.     if( ($pos_question strpos$ref'?' )) == false )
  467.     {
  468.         echo '['T_('not a query - no params!')']';
  469.         return;
  470.     }
  471.     $ref_params explode'&'substr$ref$pos_question+) );
  472.     foreach$ref_params as $ref_param )
  473.     {
  474.         $param_parts explode'='$ref_param );
  475.         if$param_parts[0== 'q' or $param_parts[0== 'query' or $param_parts[0== 'p' or $param_parts[0== 'kw' or $param_parts[0== 'qs' )
  476.         // found "q" query parameter
  477.             $q urldecode($param_parts[1]);
  478.             ifstrpos$q'Ã' !== false )
  479.             {    // Probability that the string is UTF-8 encoded is very high, that'll do for now...
  480.                 //echo "[UTF-8 decoding]";
  481.                 $q utf8_decode$q );
  482.             }
  483.             $qwords explode' '$q );
  484.             foreach$qwords as $qw )
  485.             {    
  486.                 ifstrlen$qw 30 $qw substr$qw030 )."...";    // word too long, crop it
  487.                 $kwout .= $qw.' ';
  488.             }
  489.             echo htmlentities($kwout);
  490.             return;
  491.         }
  492.     }
  493.     echo '['T_('no query string found')']';
  494. }
  495.  
  496.  
  497. /*
  498.  * stats_req_URI(-)
  499.  */
  500. function stats_req_URI()
  501. {
  502.     global $row_stats;
  503.     echo htmlentities($row_stats['visitURL']);
  504. }
  505.  
  506.  
  507. /**
  508.  * stats_user_agent(-)
  509.  *
  510.  * @param boolean 
  511.  */
  512. function stats_user_agent$translate false )
  513. {
  514.     global $row_stats$user_agents;
  515.     $UserAgent $row_stats'hit_user_agent' ];
  516.     if$translate )
  517.     {
  518.         foreach ($user_agents as $curr_user_agent)
  519.         {
  520.             if (stristr($UserAgent$curr_user_agent[1]))
  521.             {
  522.                 $UserAgent $curr_user_agent[2];
  523.                 break;
  524.             }
  525.         }
  526.     }
  527.     echo htmlentities$UserAgent );
  528. }
  529.  
  530.  
  531. /**
  532.  * Display "Statistics" title if these have been requested
  533.  *
  534.  * @deprecated Stats should not be made public (SPAM!!!)
  535.  * @param string Prefix to be displayed if something is going to be displayed
  536.  * @param mixed Output format, see {@link format_to_output()} or false to
  537.  *                                 return value instead of displaying it
  538.  */
  539. function stats_title$prefix ' '$display 'htmlbody' )
  540. {
  541.     if$display)
  542.         return '';
  543. }
  544.  
  545.  
  546.  
  547. /* select count(*) as nb, hit_ignore
  548. from b2hitlog
  549. group by hit_ignore
  550. order by nb desc 
  551.  
  552.  
  553. update b2hitlog
  554. set hit_ignore ='robot' 
  555. where `hit_ignore` LIKE 'invalid' AND `hit_user_agent` LIKE 'FAST-WebCrawler/%'  
  556.  
  557.  
  558.  
  559. */
  560. ?>

Documentation generated on Tue, 20 May 2008 01:54:56 +0200 by phpDocumentor 1.4.2