вторник, 31 марта 2015 г.

Адаптация счетчика посещений сайта VINAORA (joomla!) для любых сайтов.

     В настоящее время как-то больше принято пользоваться счетчиками посещаемости сайта от известных поисковых систем или хороших интернет-каталогов. Однако, иногда возникает необходимость использовать собственные счетчики. Чаще всего это - пожелание владельца сайта, связанное с дизайном сайта. Ну нравится вот такой счетчик людям - и тогда нужно писать свой или использовать один из многочисленных, представленных в Интернет. Но иногда попадаются нетривиальные задачи. Так случилось и в этот раз. Мне поставили задачу перенести сайт Студии иностранных языков YES Studio с очень устаревшей версии CMS joomla! 1.0 на 1С-Битрикс. Все бы хорошо, сайт я перенес с некоторой доработкой дизайна (например, добавил слайдер на CSS3) - но остался счетчик работы VINAORA , который очень нравился владельцу сайта. И в самом деле - в счетчике есть вывод посетителей за текущий и прошлый день, текущую и прошлую неделю, текущий и прошлый месяц и общее число посетителей за все время. Дизайн же можно менять в широких пределах, если хоть немного владеешь pHp. В принципе, можно было бы поискать и в сети счетчик для Битрикс с аналогичными данными, изменив его дизайн, или же использовать встроенный сбор статистики Битрикс, тоже доработав дизайн. Но - модуль веб-аналитики в Битрикс настолько скверный, что после его установки сайты замедляют работу в десятки раз (!), причем техподдержка Битрикс никак это не комментирует и не реагирует на претензии к модулю. А второе - на старой версии переносимого сайта накопилась хорошая база данных посещаемости за длительный срок, которую владелец сайта никак не хотел потерять. Так что проще было переписать счетчик так, чтобы он был пригоден для работы не только в joomla! , но и в любой CMS (или вообще без CMS). Проблема была только в том, чтобы заменить в коде счетчика вызовы специфичных функций из объектной модели joomla! на аналогичный по функционалу код pHp, не зависимый от CMS вообще.
     Итак, первое, что я сделал - просто перенес базу данных на новую версию сайта, чтобы сохранить всю статистику.
     Затем берем код счетчика для joomla!:

<?php
/**
* @version $Id: helper.php 2009-05-19 vinaora $
* @package VINAORA VISITORS COUNTER
* @copyright Copyright (C) 2007 - 2009 VINAORA.COM. All rights reserved.
* @license GNU/GPL
* @website http://vinaora.com
* @email admin@vinaora.com

* @warning DON'T EDIT OR DELETE LINK HTTP://VINAORA.COM ON THE FOOTER OF MODULE. CONTACT ME IF YOU WANT.
*
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
?>
<?php
require_once( dirname(__FILE__) . DS . "browsers.php" );

// Birth day of Joomla: 15 Sept 2005
define( 'BIRTH_DAY_JOOMLA' , 1126713600 );

class modVisitCounterHelper
{
function render(&$params)
{
global $mainframe;

/* ------------------------------------------------------------------------------------------------ */
// Read our Parameters
$today = @$params->get( 'today', 'Today' );
$yesterday = @$params->get( 'yesterday', 'Yesterday' );
$x_week = @$params->get( 'week', 'This week' );
$l_week = @$params->get( 'lweek', 'Last week' );
$x_month = @$params->get( 'month', 'This month' );
$l_month = @$params->get( 'lmonth', 'Last month' );
$all = @$params->get( 'all', 'All days' );

$beginday = @$params->get( 'beginday', '' );

$online = @$params->get( 'online', 'Online Now: ' );
$guestip = @$params->get( 'guestip', 'Your IP: ' );
$guestinfo = @$params->get( 'guestinfo', 'Your: ' );
$formattime = @$params->get( 'formattime', 'UTC: %Y-%m-%d %H:%M' );

$digit_type = @$params->get( 'digit_type', 'default' );
$stats_type = @$params->get( 'stats_type', 'default' );

$widthtable = (int) @$params->get( 'widthtable', 90 );

$sessiontime = (int) @$params->get( 'sessiontime', 10 );

$initialvalue = (int) @$params->get( 'initialvalue', 1 );

$issunday = @$params->get( 'issunday', 1 );

$deldays = (int) @$params->get( 'deldays', 0 );

$delday = (int) @$params->get( 'delday', 15 );

$pretext   = @$params->get( 'pretext', "" );
$posttext   = @$params->get( 'posttext', "" );

$iscache = @$params->get( 'iscache', 0 );
$checkdatabase = @$params->get( 'checkdatabase', 1 );

/* ------------------------------------------------------------------------------------------------ */



/* ------------------------------------------------------------------------------------------------ */
$s_today = modVisitCounterHelper::showParam( $today );
$s_yesterday = modVisitCounterHelper::showParam( $yesterday );
$s_week = modVisitCounterHelper::showParam( $x_week );
$s_lweek = modVisitCounterHelper::showParam( $l_week );
$s_month = modVisitCounterHelper::showParam( $x_month );
$s_lmonth = modVisitCounterHelper::showParam( $l_month );
$s_all = modVisitCounterHelper::showParam( $all );

$s_online = modVisitCounterHelper::showParam( $online );
$s_ip = modVisitCounterHelper::showParam( $guestip );
$s_guestinfo = modVisitCounterHelper::showParam( $guestinfo );
$s_timenow = modVisitCounterHelper::showParam( $formattime );

$s_digit = modVisitCounterHelper::showParam( $digit_type );
$s_delrecords = modVisitCounterHelper::showParam( $deldays );
/* ------------------------------------------------------------------------------------------------ */


// From minutes to seconds
$sessiontime = $sessiontime * 60;

// Get Time Offset from Global Configuration of Joomla!
$offset = $mainframe->getCfg( 'offset' );

// Get a reference to the global cache object.
$cache = & JFactory::getCache();

// Check if jos_vvisitcounter table exists. When not, create it
if ( $checkdatabase ){
if ( $iscache ){
$cache->call( array( 'modVisitCounterHelper', 'createTable' ) );
}
else{
modVisitCounterHelper::createTable();
}
}


/* ------------------------------------------------------------------------------------------------ */
// Detect Guest's IP Address and Insert new records
$ip = "0.0.0.0";
if(!empty($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];

$now = & JFactory::getDate(  );

// Now we are checking if the ip was logged in the database. 
// Depending of the value in minutes in the sessiontime variable.
// Check session time, insert new record if timeout
modVisitCounterHelper::insertVisitor( $sessiontime, $ip, $now->toUnix() );

// Update $now
$now = & JFactory::getDate(  );

/* ------------------------------------------------------------------------------------------------ */


/* ------------------------------------------------------------------------------------------------ */
// Determine TIME
// Determine this hour, this day, this month, this year
$minute = (int) $now->toFormat( "%M" );
$hour = (int) $now->toFormat( "%H" );
$day = (int) $now->toFormat( "%d" );
$month = (int) $now->toFormat( "%m" );
$year = (int) $now->toFormat( "%Y" );

// Determine Starting Time of Today
$daystart = mktime( 0,0,0,$month,$day,$year );
$local_daystart = modVisitCounterHelper::localTimeStart( $daystart, $offset, "day");

// Starting Time of Yesterday
$yesterdaystart = strtotime( "-1 day", $daystart ) ;
$local_yesterdaystart = strtotime( "-1 day", $local_daystart ) ;

// Starting Time of This Week
// If Sunday is starting day of week then Sunday = 0 ... Saturday = 6
// If Monday is starting day of week then Monday = 0 ... Sunday = 6
$weekday = (int) $now->toFormat( "%w" );
if ( !$issunday ) {
if ( $weekday ) $weekday--;
else $weekday = 7;
}
$weekstart = strtotime( "-$weekday days", $daystart );
$local_weekstart = modVisitCounterHelper::localTimeStart( $weekstart, $offset, "week");

// Starting Time of Last Week
$lweekstart = strtotime( "-1 week", $weekstart ) ;
$local_lweekstart = strtotime( "-1 week", $local_weekstart ) ;

// Determine Starting Time of This Month
$monthstart = mktime( 0,0,0,$month,1,$year );
$local_monthstart = modVisitCounterHelper::localTimeStart( $monthstart, $offset, "month");

// Determine Starting Time of Last Month
$lmonthstart = strtotime( "-1 month", $monthstart );
$local_lmonthstart = strtotime( "-1 month", $local_monthstart );

/* ------------------------------------------------------------------------------------------------ */


/* ------------------------------------------------------------------------------------------------ */
// BEGIN: Caculate number visitors of Today, Yesterday, This Week, Last Week, This Month, Last Month // Count All Visitors
$all_visitors = modVisitCounterHelper::getAllVisitors();
$all_visitors += $initialvalue;

// Count Today's Visitors
$today_visitors = modVisitCounterHelper::getVisitors( $local_daystart );

// Count Yesterday's Visitors
if( $s_yesterday ){
if ( $iscache ){
$yesterday_visitors = $cache->call( array( 'modVisitCounterHelper', 'getVisitors' ), $local_yesterdaystart, $local_daystart );
}
else {
$yesterday_visitors = modVisitCounterHelper::getVisitors( $local_yesterdaystart, $local_daystart );
}
}

// Count This Week's Visitors
if( $s_week ){
if ( $iscache ){
$week_visitors = $cache->call( array( 'modVisitCounterHelper', 'getVisitors' ), $local_weekstart, $local_daystart );
$week_visitors += $today_visitors;
}
else{
$week_visitors = modVisitCounterHelper::getVisitors( $local_weekstart, $local_daystart );
$week_visitors += $today_visitors;
}
}

// Count Last Week's Visitors
if( $s_lweek ){
if ( $iscache ){
$lweek_visitors = $cache->call( array( 'modVisitCounterHelper', 'getVisitors' ), $local_lweekstart, $local_weekstart );
}
else{
$lweek_visitors = modVisitCounterHelper::getVisitors( $local_lweekstart, $local_weekstart );
}
}

// Count This Month's Visitors
if( $s_month ){
if ( $iscache ){
$month_visitors = $cache->call( array( 'modVisitCounterHelper', 'getVisitors' ), $local_monthstart, $local_daystart );
$month_visitors +=  $today_visitors;
}
else{
$month_visitors = modVisitCounterHelper::getVisitors( $local_monthstart, $local_daystart );
$month_visitors +=  $today_visitors;
}
}

// Count Last Month's Visitors
if( $s_lmonth ){
if ( $iscache ){
$lmonth_visitors = $cache->call( array( 'modVisitCounterHelper', 'getVisitors' ), $local_lmonthstart, $local_monthstart );
}
else{
$lmonth_visitors = modVisitCounterHelper::getVisitors( $local_lmonthstart, $local_monthstart );
}
}

// Count Online in 20 minutes
$online_time = 20;
if( $s_online ){
$online_visitors = modVisitCounterHelper::getVisitors( $now->toUnix() - $online_time*60 );
}

// END: CACULATE VISITORS
/* ------------------------------------------------------------------------------------------------ */



/* ------------------------------------------------------------------------------------------------ */
// BEGIN: SHOW DIGIT COUNTER
$content = '<div>';
if ($pretext != "") $content .= '<div>'.$pretext.'</div>';

// Show digit counter
if($s_digit){

$content .= '<div style="text-align: center;">';

$n = $all_visitors;
$div = 100000;
while ($n > $div) {
$div *= 10;
}

while ($div >= 1) {
$digit = $n / $div % 10;
$content .= '<img src="'.JURI::base().'modules/mod_vvisit_counter/images/digit_counter/'.$digit_type.'/'.$digit.'.png"';
$content .= ' style="margin:0; border:0; "';
$content .= ' alt="mod_vvisit_counter"';
$content .= ' title="Vinaora Visitors Counter"';
$content .= ' />';
$n -= $digit * $div;
$div /= 10;
}
$content .= '</div>';
}
// END: SHOW DIGIT COUNTER
/* ------------------------------------------------------------------------------------------------ */



/* ------------------------------------------------------------------------------------------------ */
// BEGIN: TABLE STATISTICS
if ( modVisitCounterHelper::showParam( $stats_type ) ){

$content .= '<div><table cellpadding="0" cellspacing="0" ';
$content .= 'style="margin: 3px; text-align: center; align: center; ';
$content .= 'width: '.$widthtable.'%;" class="vinaora_counter">';
$content .= '<tbody align="center">';

// Show today, yestoday, this week, this month, and all visitors
if($s_today){
$timeline = modVisitCounterHelper::showTimeLine( $local_daystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vtoday.png", $timeline, $today, $today_visitors );
}
if($s_yesterday){
$timeline = modVisitCounterHelper::showTimeLine( $local_yesterdaystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vyesterday.png", $timeline, $yesterday, $yesterday_visitors );
}
if($s_week){
$timeline = modVisitCounterHelper::showTimeLine( $local_weekstart, $local_daystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vweek.png", $timeline, $x_week, $week_visitors );
}
if($s_lweek){
$timeline = modVisitCounterHelper::showTimeLine( $local_lweekstart, $local_weekstart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vlweek.png", $timeline, $l_week, $lweek_visitors );
}
if($s_month){
$timeline = modVisitCounterHelper::showTimeLine( $local_monthstart, $local_daystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vmonth.png", $timeline, $x_month, $month_visitors );
}
if($s_lmonth){
$timeline = modVisitCounterHelper::showTimeLine( $lmonthstart, $local_monthstart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vlmonth.png", $timeline, $l_month, $lmonth_visitors );
}
if($s_all){
if ( !$beginday ) $beginday = "Visitors Counter";
$content .= modVisitCounterHelper::spaceer( $stats_type, "vall.png", $beginday, $all, $all_visitors );
}

$content .= "</tbody></table></div>";
$content .= '<hr style="width: 90%" />';
}
// END: TABLE STATISTICS
/* ------------------------------------------------------------------------------------------------ */


/* ------------------------------------------------------------------------------------------------ */
// BEGIN: SHOW GUEST'S INFO
// Show Guest's Info
if ( $s_online || $s_ip || $s_guestinfo || $s_timenow ){

$content .= '<div style="text-align: center;">';

if($s_online){
$content .= $online . " " . $online_visitors . "<br />";
}

if($s_ip){
$content .= $guestip . " " . $ip . "<br />";
}

if($s_guestinfo){
//$content .= $guestinfo;
$browser = modVisitCounterBrowser::browser();
if (!empty( $browser )){
$content .= strtoupper($browser['name']);
$content .= " ";
$content .= $browser['version'];
$content .= ", ";
$content .= strtoupper($browser['platform']) ;
$content .= "<br /> ";
}
}

if ( $s_timenow ){
$now->setOffset( $offset );
$content .= $now->toFormat( $formattime );
}

$content .= '</div>';
//$content .= '<hr>';
}


if ($posttext != ""){
$content .= '<div>'.$posttext.'</div>';
}

$content .= '<div style="text-align: center;"><a href="http://gold';
$content .= 'promo.com.ua" target="_self" title="Счетчик посеще';
$content .= 'ний сайта">Счетчик посещений</a></div>';
$content .= '</div>';
// END: SHOW GUEST'S INFO
/* ------------------------------------------------------------------------------------------------ */

echo $content;

/* ------------------------------------------------------------------------------------------------ */
// BEGIN: Delete old records if today is the 7th, 14th, 21th or 28th of the month.
if ( $s_delrecords ){
if ( ($day % 7) == 0 ){
if ( ($minute % 20) == 0 ){
$temp = $daystart - $deldays*24*60*60;
modVisitCounterHelper::delVisitors( 0, $temp );
}
}
}
// END: Delete old records
/* ------------------------------------------------------------------------------------------------ */

}


/*
** Show Statistics Table 
*/
/* ------------------------------------------------------------------------------------------------ */
function spaceer( $stats_type="default", $image, $timeline = "", $time = "", $visitors = "")
{
$ret = '<tr align="left"><td>';
$ret .= '<img src="'.JURI::base().'modules/mod_vvisit_counter/images/stats/'.$stats_type.'/'.$image.'"';
$ret .= ' alt="mod_vvisit_counter"';
$ret .= ' title="'.$timeline.'" /></td>';
$ret .= '<td>'.$time.'</td>';
$ret .= '<td align="right">'.$visitors.'</td></tr>';
return $ret;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Create Table if Not Exist
*/
/* ------------------------------------------------------------------------------------------------ */
function createTable (){
// Check if table exists. When not, create it
$query = " CREATE TABLE IF NOT EXISTS #__vvisitcounter (
id int(11) unsigned NOT NULL auto_increment, 
tm int NOT NULL, 
ip varchar(16) NOT NULL DEFAULT '0.0.0.0', 
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; ";

$db =& JFactory::getDBO();
$db->setQuery($query);
$db->query();
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Insert New Visisitor
*/
/* ------------------------------------------------------------------------------------------------ */
function insertVisitor( $sessiontime, $ip, $time ){
// Check session time, insert new record if timeout
$db = & JFactory::getDBO();
$query = ' SELECT COUNT(*) FROM #__vvisitcounter ';
$query .= ' WHERE ip=' . $db->quote( $ip );
$query .= ' AND (tm + ' . $db->quote( $sessiontime ) . ') > ' . $db->quote( $time );
$db->setQuery($query);
$items = $db->loadResult();

if ( empty($items) )
{
$query = " INSERT INTO #__vvisitcounter (id, tm, ip) ";
$query .= " VALUES ('', " . $db->quote ( $time ) . ", " . $db->quote ( $ip ) . ")";
$db->setQuery($query);
$db->query();
$e = $db->getErrorMsg();
}
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Get Total of Visisitors Until $time
*/
/* ------------------------------------------------------------------------------------------------ */
function getAllVisitors( $time=0 ){

$visitors = 0;
$db = & JFactory::getDBO();

// Query total visitors
$query = ' SELECT MAX(id) FROM #__vvisitcounter ';
if ( $time > BIRTH_DAY_JOOMLA ){
$query .= ' WHERE tm < ' . $db->quote( $time );
}
$db->setQuery($query);

// Total visitors
$visitors = $db->loadResult();
return $visitors;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Get Number of Visisitors from $timestart to $timestop
*/
/* ------------------------------------------------------------------------------------------------ */
function getVisitors( $timestart = 0, $timestop = 0 ){

$visitors = 0;

if ( $timestart < BIRTH_DAY_JOOMLA ) $timestart = 0;
if ( $timestop < BIRTH_DAY_JOOMLA ) $timestop = 0;

$db = & JFactory::getDBO();
$query = ' SELECT COUNT(*) FROM #__vvisitcounter ';

if ( !$timestart ){
if ( !$timestop ) return 0;
$query .= ' WHERE tm < ' . $db->quote( $timestop );
}
else{
if ( !$timestop ){
$query .= ' WHERE tm >= ' . $db->quote( $timestart );
}
else{

if ( $timestop == $timestart ){
$query .= ' WHERE tm = ' . $db->quote( $timestart );
}

if ( $timestop > $timestart ){
$query .= ' WHERE tm >= ' . $db->quote( $timestart );
$query .= ' AND tm < ' . $db->quote( $timestop );
}

if ( $timestop < $timestart ){
$query .= ' WHERE tm >= ' . $db->quote( $timestop );
$query .= ' AND tm < ' . $db->quote( $timestart );
}
}
}

$db->setQuery($query);
$visitors = $db->loadResult();

return $visitors;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Remove Visisitors from $timestart to $timestop
*/
/* ------------------------------------------------------------------------------------------------ */
function delVisitors( $timestart = 0, $timestop = 0 ){

if ( $timestart < BIRTH_DAY_JOOMLA ) $timestart = 0;
if ( $timestop < BIRTH_DAY_JOOMLA ) $timestop = 0;

$db = & JFactory::getDBO();
$query = ' DELETE FROM #__vvisitcounter ';

if ( !$timestart ){
if ( !$timestop ) return 0;
$query .= ' WHERE tm < ' . $db->quote( $timestop );
}
else{
if ( !$timestop ){
$query .= ' WHERE tm >= ' . $db->quote( $timestart );
}
else{

if ( $timestop == $timestart ){
$query .= ' WHERE tm = ' . $db->quote( $timestart );
}

if ( $timestop > $timestart ){
$query .= ' WHERE tm >= ' . $db->quote( $timestart );
$query .= ' AND tm < ' . $db->quote( $timestop );
}

if ( $timestop < $timestart ){
$query .= ' WHERE tm >= ' . $db->quote( $timestop );
$query .= ' AND tm < ' . $db->quote( $timestart );
}
}
}

$db->setQuery($query);
$db->query();
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Check Parameter
** Return False if Parameter equal to "0" (zero) or "o" or "O" or empty
*/
/* ------------------------------------------------------------------------------------------------ */
function showParam( $param = "" ){

// $param is Undefined variable
if ( empty( $param ) ) return false;

// $param Defined variable
$param = strtolower( trim($param) );
if ( $param == "" ) return false;
if ( $param == "0" ) return false;
if ( $param == "o" ) return false;
return true;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Show Timeline.
** Format: %Y-%m-%d -> %Y-%m-%d
*/
/* ------------------------------------------------------------------------------------------------ */
function showTimeLine( $timeBegin = 0, $timeEnd = 0, $offset = "" ){
global $mainframe;
$str = "";
if ( empty( $offset ) ) $offset = $mainframe->getCfg( 'offset' );

if ( $timeBegin ){
$time = & JFactory::getDate( $timeBegin );
$time->setOffset( $offset );

$str1 = $time->toFormat( '%Y-%m-%d' ) ;
$str = $str1;
if ( $timeEnd ){
$time = & JFactory::getDate( $timeEnd );
$time->setOffset( $offset );

$str2 = $time->toFormat( '%Y-%m-%d' ) ;
$str .= " -> ";
$str .= $str2;
}
}
return $str;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Determine Local Starting Time.
** Return Unix Time
*/
/* ------------------------------------------------------------------------------------------------ */
function localTimeStart( $timestart, $offset=0, $type="day" ){
$now = & JFactory::getDate(  );
$type = strtolower( trim ($type) );
if ( $type != "day" && $type != "week" && $type != "month" ) $type = "day";

$nexttimestart = strtotime( "+1 " . $type, $timestart ) ;
$lasttimestart = strtotime( "-1 " . $type, $timestart ) ;

if ( $offset > 0 ) {
if ( ( $nexttimestart - $now->toUnix() ) <= $offset*60*60 ) {
$timestart = $nexttimestart - $offset*60*60;
}
else $timestart -=  $offset*60*60;
}
if ( $offset < 0 ) {
if ( ( $now->toUnix() - $timestart ) < -$offset*60*60 ) $timestart = $lasttimestart + -$offset*60*60;
else $timestart += -$offset*60*60;
}
return $timestart;
}
/* ------------------------------------------------------------------------------------------------ */

}
?>


И модифицируем его примерно вот таким образом (я удалил из него вывод некоторых данных, которые были не нужны на перенесенном сайте - ip пользователя, сведения о браузере и т.п. подробности, отключил очистку данных по истечении какого-то срока, поэтому мне не понадобилось подключение в коде дополнительного файла для аналалитики браузеров пользователей, ну и заменил выводы джумловских функций на обычный pHp):





<!--
* @version $Id: helper.php 2009-05-19 vinaora $
* @package VINAORA VISITORS COUNTER
* @copyright Copyright (C) 2007 - 2009 VINAORA.COM. All rights reserved.
* @license GNU/GPL
* @website http://vinaora.com
* @email admin@vinaora.com

* modified for 1C-Bitrix or any CMS different from joomla! by Andrey Yamangulov yamangulov@gmail.com
* модифицирован для 1С-Битрикс или произвольной CMS, отличной от joomla! : Андрей Ямангулов yamangulov@gmail.com
-->
  
<div> <?php

//connect to database
mysql_connect("localhost", "db_login", "db_password") or die("Connection error");
mysql_select_db("b_vvisitcounter");

class modVisitCounterHelper
{
function render(&$today, &$yesterday, &$x_week, &$l_week, &$x_month, &$l_month, &$all, &$beginday, &$online, &$guestip, &$guestinfo, &$formattime, &$digit_type, &$stats_type, &$widthtable, &$sessiontime, &$initialvalue, &$issunday, &$deldays, &$delday, &$pretext, &$posttext)
{
/* ------------------------------------------------------------------------------------------------ */
// Read our Parameters
$today = 'Today';
$yesterday = 'Yesterday';
$x_week = 'This week';
$l_week = 'Last week';
$x_month = 'This month';
$l_month = 'Last month';
$all = 'All days';
$beginday = '';
$online = 'Online Now; ';
$guestip = 'Your IP: ';
$guestinfo = 'Your: ';
$formattime = 'UTC: %Y-%m-%d %H:%M';
$digit_type = 'gold';
$stats_type = 'bronzes';
$widthtable = 90;
$sessiontime = 86400;
$initialvalue = 1;
$issunday = 0;
$deldays = 0;
$delday = 15;
$pretext   = "";
$posttext   = "Счетчик посещений";

/* ------------------------------------------------------------------------------------------------ */



/* ------------------------------------------------------------------------------------------------ */
$s_today = modVisitCounterHelper::showParam( $today );
$s_yesterday = modVisitCounterHelper::showParam( $yesterday );
$s_week = modVisitCounterHelper::showParam( $x_week );
$s_lweek = modVisitCounterHelper::showParam( $l_week );
$s_month = modVisitCounterHelper::showParam( $x_month );
$s_lmonth = modVisitCounterHelper::showParam( $l_month );
$s_all = modVisitCounterHelper::showParam( $all );

$s_online = modVisitCounterHelper::showParam( $online );
$s_ip = modVisitCounterHelper::showParam( $guestip );
$s_guestinfo = modVisitCounterHelper::showParam( $guestinfo );
$s_timenow = modVisitCounterHelper::showParam( $formattime );

$s_digit = modVisitCounterHelper::showParam( $digit_type );
$s_delrecords = modVisitCounterHelper::showParam( $deldays );
/* ------------------------------------------------------------------------------------------------ */

// Get Time Offset
$offset = date("Z", time());

/* ------------------------------------------------------------------------------------------------ */
// Detect Guest's IP Address and Insert new records
$ip = "0.0.0.0";
if(!empty($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];

$now = time();

// Now we are checking if the ip was logged in the database. 
// Depending of the value in seconds in the sessiontime variable.
// Check session time, insert new record if timeout
modVisitCounterHelper::insertVisitor( $sessiontime, $ip, $now );

// Update $now
$now = time();

/* ------------------------------------------------------------------------------------------------ */
// Determine TIME
// Determine this hour, this day, this month, this year
$minute = date("i");
$hour = date("H");
$day = date("d");
$month = date("m");
$year = date("Y");

// Determine Starting Time of Today
$daystart = mktime( 0,0,0,$month,$day,$year );
$local_daystart = modVisitCounterHelper::localTimeStart( $daystart, $offset, "day");

// Starting Time of Yesterday
$yesterdaystart = strtotime( "-1 day", $daystart ) ;
$local_yesterdaystart = strtotime( "-1 day", $local_daystart ) ;

// Starting Time of This Week
// If Sunday is starting day of week then Sunday = 0 ... Saturday = 6
// If Monday is starting day of week then Monday = 0 ... Sunday = 6
$weekday = date("w"); //(int) $now->toFormat( "%w" );
if ( !$issunday ) {
if ( $weekday ) $weekday--;
else $weekday = 7;
}
$weekstart = strtotime( "-$weekday days", $daystart );
$local_weekstart = modVisitCounterHelper::localTimeStart( $weekstart, $offset, "week");

// Starting Time of Last Week
$lweekstart = strtotime( "-1 week", $weekstart ) ;
$local_lweekstart = strtotime( "-1 week", $local_weekstart ) ;

// Determine Starting Time of This Month
$monthstart = mktime( 0,0,0,$month,1,$year );
$local_monthstart = modVisitCounterHelper::localTimeStart( $monthstart, $offset, "month");

// Determine Starting Time of Last Month
$lmonthstart = strtotime( "-1 month", $monthstart );
$local_lmonthstart = strtotime( "-1 month", $local_monthstart );

/* ------------------------------------------------------------------------------------------------ */
// BEGIN: Caculate number visitors of Today, Yesterday, This Week, Last Week, This Month, Last Month // Count All Visitors
$all_visitors = modVisitCounterHelper::getAllVisitors();
$all_visitors += $initialvalue;

// Count Today's Visitors
$today_visitors = modVisitCounterHelper::getVisitors( $local_daystart );

// Count Yesterday's Visitors
if( $s_yesterday ){
$yesterday_visitors = modVisitCounterHelper::getVisitors( $local_yesterdaystart, $local_daystart );
}

// Count This Week's Visitors
if( $s_week ){
$week_visitors = modVisitCounterHelper::getVisitors( $local_weekstart, $local_daystart );
$week_visitors += $today_visitors;
}

// Count Last Week's Visitors
if( $s_lweek ){
$lweek_visitors = modVisitCounterHelper::getVisitors( $local_lweekstart, $local_weekstart );
}

// Count This Month's Visitors
if( $s_month ){
$month_visitors = modVisitCounterHelper::getVisitors( $local_monthstart, $local_daystart );
$month_visitors +=  $today_visitors;
}

// Count Last Month's Visitors
if( $s_lmonth ){
$lmonth_visitors = modVisitCounterHelper::getVisitors( $local_lmonthstart, $local_monthstart );
}

// Count Online in 20 minutes
$online_time = 20;
if( $s_online ){
$online_visitors = modVisitCounterHelper::getVisitors( $now - $online_time*60 );
}

// END: CACULATE VISITORS

/* ------------------------------------------------------------------------------------------------ */
// BEGIN: SHOW DIGIT COUNTER
$content = '<div>';
if ($pretext != "") $content .= '<div>'.$pretext.'</div>';

// Show digit counter
if($s_digit){

$content .= '<div style="text-align: center;">';

$n = $all_visitors;
$div = 100000;
while ($n > $div) {
$div *= 10;
}

while ($div >= 1) {
$digit = $n / $div % 10;
$content .= '<img id="bxid_208413" src="'.'/modules/mod_vvisit_counter/images/digit_counter/'.$digit_type.'/'.$digit.'.png" style="margin:0; border:0; " alt="mod_vvisit_counter" title="Vinaora Visitors Counter"  />';
$n -= $digit * $div;
$div /= 10;
}
$content .= '</div>';
}
// END: SHOW DIGIT COUNTER
/* ------------------------------------------------------------------------------------------------ */



/* ------------------------------------------------------------------------------------------------ */
// BEGIN: TABLE STATISTICS
if ( modVisitCounterHelper::showParam( $stats_type ) ){

$content .= '<div><table cellpadding="0" cellspacing="0" ';
$content .= 'style="margin: 3px; text-align: center; align: center; ';
$content .= 'width: '.$widthtable.'%;" class="vinaora_counter">';
$content .= '<tbody align="center">';

// Show today, yestoday, this week, this month, and all visitors
if($s_today){
$timeline = modVisitCounterHelper::showTimeLine( $local_daystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vtoday.png", $timeline, $today, $today_visitors );
}
if($s_yesterday){
$timeline = modVisitCounterHelper::showTimeLine( $local_yesterdaystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vyesterday.png", $timeline, $yesterday, $yesterday_visitors );
}
if($s_week){
$timeline = modVisitCounterHelper::showTimeLine( $local_weekstart, $local_daystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vweek.png", $timeline, $x_week, $week_visitors );
}
if($s_lweek){
$timeline = modVisitCounterHelper::showTimeLine( $local_lweekstart, $local_weekstart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vlweek.png", $timeline, $l_week, $lweek_visitors );
}
if($s_month){
$timeline = modVisitCounterHelper::showTimeLine( $local_monthstart, $local_daystart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vmonth.png", $timeline, $x_month, $month_visitors );
}
if($s_lmonth){
$timeline = modVisitCounterHelper::showTimeLine( $lmonthstart, $local_monthstart );
$content .= modVisitCounterHelper::spaceer( $stats_type, "vlmonth.png", $timeline, $l_month, $lmonth_visitors );
}
if($s_all){
if ( !$beginday ) $beginday = "Visitors Counter";
$content .= modVisitCounterHelper::spaceer( $stats_type, "vall.png", $beginday, $all, $all_visitors );
}

$content .= "</tbody></table></div>";
//$content .= '<hr style="width: 90%" />';
}
// END: TABLE STATISTICS
/* ------------------------------------------------------------------------------------------------ */


/* ------------------------------------------------------------------------------------------------ */
// BEGIN: SHOW GUEST'S INFO
// Show Guest's Info
if ( $s_online || $s_ip || $s_guestinfo || $s_timenow ){

$content .= '<div style="text-align: center;">';
$content .= '</div>';
$content .= '<hr style="margin-right: 15px;">';
}


if ($posttext != ""){
$content .= '<div style="text-align: center; color: #d01415;">'.$posttext.'</div>';
}


$content .= '</div>';
// END: SHOW GUEST'S INFO
/* ------------------------------------------------------------------------------------------------ */

echo $content;





/* ------------------------------------------------------------------------------------------------ */
// BEGIN: Delete old records if today is the 7th, 14th, 21th or 28th of the month.
if ( $s_delrecords ){
if ( ($day % 7) == 0 ){
if ( ($minute % 20) == 0 ){
$temp = $daystart - $deldays*24*60*60;
modVisitCounterHelper::delVisitors( 0, $temp );
}
}
}
// END: Delete old records
/* ------------------------------------------------------------------------------------------------ */

}


/*
** Show Statistics Table 
*/
/* ------------------------------------------------------------------------------------------------ */
function spaceer( $stats_type="default", $image, $timeline = "", $time = "", $visitors = "")
{
$ret = '<tr align="left"><td>';
$ret .= '<img id="bxid_618746" src="'.'/modules/mod_vvisit_counter/images/stats/'.$stats_type.'/'.$image.'" alt="mod_vvisit_counter" title="'.$timeline.'"  /></td>';
$ret .= '<td>'.$time.'</td>';
$ret .= '<td align="right">'.$visitors.'</td></tr>';
return $ret;
}
/* ------------------------------------------------------------------------------------------------ */

/*
** Insert New Visisitor
*/
/* ------------------------------------------------------------------------------------------------ */
function insertVisitor( $sessiontime, $ip, $time ){
// Check session time, insert new record if timeout

$query = ' SELECT COUNT(*) FROM b_vvisitcounter ';
$query .= " WHERE ip='" . $ip . "'";
$query .= ' AND (tm + ' . $sessiontime . ') > ' . $time;
$items_id = mysql_query($query);
$items = mysql_result($items_id, 0);

if ( empty($items) )
{
$query = " INSERT INTO b_vvisitcounter (id, tm, ip) ";
$query .= " VALUES ('', " . $time . ", '" . $ip . "')";
mysql_query($query);

}
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Get Total of Visisitors Until $time
*/
/* ------------------------------------------------------------------------------------------------ */
function getAllVisitors( $time=0 ){

$visitors = 0;
$time = time();

// Query total visitors
$query = ' SELECT MAX(id) FROM b_vvisitcounter ';
$query .= ' WHERE tm < ' . $time;

// Total visitors
$visitors_id = mysql_query($query);
$visitors = mysql_result($visitors_id, 0);
return $visitors;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Get Number of Visisitors from $timestart to $timestop
*/
/* ------------------------------------------------------------------------------------------------ */
function getVisitors( $timestart = 0, $timestop = 0 ){

$visitors = 0;

$query = ' SELECT COUNT(*) FROM b_vvisitcounter ';

if ( !$timestart ){
if ( !$timestop ) return 0;
$query .= ' WHERE tm < ' . $timestop; //$db->quote( $timestop );
}
else{
if ( !$timestop ){
$query .= ' WHERE tm >= ' . $timestart; //$db->quote( $timestart );
}
else{

if ( $timestop == $timestart ){
$query .= ' WHERE tm = ' . $timestart; //$db->quote( $timestart );
}

if ( $timestop > $timestart ){
$query .= ' WHERE tm >= ' . $timestart; //$db->quote( $timestart );
$query .= ' AND tm < ' . $timestop; //$db->quote( $timestop );
}

if ( $timestop < $timestart ){
$query .= ' WHERE tm >= ' . $timestop; //$db->quote( $timestop );
$query .= ' AND tm < ' . $timestart; //$db->quote( $timestart );
}
}
}

$visitors_id = mysql_query($query);
$visitors = mysql_result($visitors_id, 0);
return $visitors;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Remove Visisitors from $timestart to $timestop
*/
/* ------------------------------------------------------------------------------------------------ */
function delVisitors( $timestart = 0, $timestop = 0 ){

$query = ' DELETE FROM b_vvisitcounter ';

if ( !$timestart ){
if ( !$timestop ) return 0;
$query .= ' WHERE tm < ' . $timestop; //$db->quote( $timestop );
}
else{
if ( !$timestop ){
$query .= ' WHERE tm >= ' . $timestart; //$db->quote( $timestart );
}
else{

if ( $timestop == $timestart ){
$query .= ' WHERE tm = ' . $timestart; //$db->quote( $timestart );
}

if ( $timestop > $timestart ){
$query .= ' WHERE tm >= ' . $timestart; //$db->quote( $timestart );
$query .= ' AND tm < ' . $timestop; //$db->quote( $timestop );
}

if ( $timestop < $timestart ){
$query .= ' WHERE tm >= ' . $timestop; //$db->quote( $timestop );
$query .= ' AND tm < ' . $timestart; //$db->quote( $timestart );
}
}
}

$del_visitors = mysql_query($query);
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Check Parameter
** Return False if Parameter equal to "0" (zero) or "o" or "O" or empty
*/
/* ------------------------------------------------------------------------------------------------ */
function showParam( $param = "" ){

// $param is Undefined variable
if ( empty( $param ) ) return false;

// $param Defined variable
$param = strtolower( trim($param) );
if ( $param == "" ) return false;
if ( $param == "0" ) return false;
if ( $param == "o" ) return false;
return true;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Show Timeline.
** Format: %Y-%m-%d -> %Y-%m-%d
*/
/* ------------------------------------------------------------------------------------------------ */
function showTimeLine( $timeBegin = 0, $timeEnd = 0, $offset = "" ){
//global $mainframe;
$str = "";
if ( empty( $offset ) ) $offset = date("Z", time()); //$mainframe->getCfg( 'offset' );

if ( $timeBegin ){
$time_b = date( $timeBegin ); //& JFactory::getDate( $timeBegin );
//$time->setOffset( $offset );

//$str1 = $time->toFormat( '%Y-%m-%d' ) ;
//$str = $str1;
$str = $time_b;
if ( $timeEnd ){
$time_e = date( $timeEnd ); //& JFactory::getDate( $timeEnd );
//$time->setOffset( $offset );

//$str2 = $time->toFormat( '%Y-%m-%d' ) ;
//$str .= " -> ";
//$str .= $str2;
$str = $time_e;
}
}
return $str;
}
/* ------------------------------------------------------------------------------------------------ */



/*
** Determine Local Starting Time.
** Return Unix Time
*/
/* ------------------------------------------------------------------------------------------------ */
function localTimeStart( $timestart, $offset=0, $type="day" ){
$now = time(); //date("Y-m-d H:i"); //& JFactory::getDate(  );
$offset = date("Z", time());
$type = strtolower( trim ($type) );
if ( $type != "day" && $type != "week" && $type != "month" ) $type = "day";

$nexttimestart = strtotime( "+1 " . $type, $timestart ) ;
$lasttimestart = strtotime( "-1 " . $type, $timestart ) ;

if ( $offset > 0 ) {
if ( ( $nexttimestart - $now ) <= $offset ) {
$timestart = $nexttimestart - $offset;
}
else $timestart -=  $offset;
}
if ( $offset < 0 ) {
if ( ( $now - $timestart ) < -$offset ) $timestart = $lasttimestart + -$offset;
else $timestart += -$offset;
}
return $timestart;
}
/* ------------------------------------------------------------------------------------------------ */

}
?></div>

<div> 
  <br />
 </div>

<div> <?php
$hlp = new modVisitCounterHelper;
$hlp->render();
?> </div>


Понятно, что данные для входа в базу данных и имя базы данных вы меняете на свои. Кроме того, внизу я добавил создание экземпляра класса и вызов нужной функции из него, чтобы счетчик отобразился на нужной странице.
Далее в 1С-Битрикс весь код я добавил один раз в шаблон сайта. Однако, если вы будете делать не так, и если хотите, чтобы счетчик отображался только на избранных страницах, то вам нужно весь код с начала до вызова экземпляра класса вынести в отдельный файл, подключаемый в шаблоне сайта, а уже сам вызов экземпляра класса поставить только на избранных страницах.
В моем варианте я изменил код так, чтобы с одного адреса посетитель подсчитывается только раз в сутки ($sessiontime=86400 - секунд в сутках), но вы можете сделать на свое усмотрение, как и изменить дизайн вывода счетчика.
Ссылки на изображения в дизайне в тексте кода взяты из моего сайта, у вас они могут быть совсем другие, кроме того, на сайте VINAORA данный счетчик пока еще есть, но ссылки на скачивание уже недоступны. я полагаю, уже очень давно. Так что это вам придется сделать самостоятельно. Для работы счетчика достаточно приведенного мной кода плюс ваш дизайн.