b2evolution PHP Cross Reference Blogging Systems

Source: /inc/sessions/model/_hitlog.funcs.php - 929 lines - 26622 bytes - Summary - Text - Print

Description: This file implements functions for logging of hits and extracting stats. NOTE: the refererList() and stats_* functions are not fully functional ATM. I'll transform them into the Hitlog object during the next days. blueyed.

   1  <?php
   2  /**
   3   * This file implements functions for logging of hits and extracting stats.
   4   *
   5   * NOTE: the refererList() and stats_* functions are not fully functional ATM. I'll transform them into the Hitlog object during the next days. blueyed.
   6   *
   7   * This file is part of the evoCore framework - {@link http://evocore.net/}
   8   * See also {@link http://sourceforge.net/projects/evocms/}.
   9   *
  10   * @copyright (c)2003-2014 by Francois Planque - {@link http://fplanque.com/}
  11   * Parts of this file are copyright (c)2004-2006 by Daniel HAHLER - {@link http://thequod.de/contact}.
  12   *
  13   * {@internal License choice
  14   * - If you have received this file as part of a package, please find the license.txt file in
  15   *   the same folder or the closest folder above for complete license terms.
  16   * - If you have received this file individually (e-g: from http://evocms.cvs.sourceforge.net/)
  17   *   then you must choose one of the following licenses before using the file:
  18   *   - GNU General Public License 2 (GPL) - http://www.opensource.org/licenses/gpl-license.php
  19   *   - Mozilla Public License 1.1 (MPL) - http://www.opensource.org/licenses/mozilla1.1.php
  20   * }}
  21   *
  22   * {@internal Open Source relicensing agreement:
  23   * Daniel HAHLER grants Francois PLANQUE the right to license
  24   * Daniel HAHLER's contributions to this file and the b2evolution project
  25   * under any OSI approved OSS license (http://www.opensource.org/licenses/).
  26   * }}
  27   *
  28   * {@internal Origin:
  29   * This file was inspired by N C Young's Referer Script released in
  30   * the public domain on 07/19/2002. {@link http://ncyoung.com/entry/57}.
  31   * See also {@link http://ncyoung.com/demo/referer/}.
  32   * }}
  33   *
  34   * @package evocore
  35   *
  36   * {@internal Below is a list of authors who have contributed to design/coding of this file: }}
  37   * @author N C Young (nathan@ncyoung.com).
  38   * @author blueyed: Daniel HAHLER.
  39   * @author fplanque: Francois PLANQUE.
  40   * @author vegarg: Vegar BERG GULDAL.
  41   *
  42   * @version $Id: _hitlog.funcs.php 6136 2014-03-08 07:59:48Z manuel $
  43   */
  44  if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
  45  
  46  
  47  /**
  48   * Display hits results table
  49   */
  50  function hits_results_block( $params = array() )
  51  {
  52      if( !is_logged_in() )
  53      {    // Only logged in users can access to this function
  54          return;
  55      }
  56  
  57      global $current_User;
  58      if( !$current_User->check_perm( 'stats', 'view' ) )
  59      {    // Current user has no permission to view all stats (aggregated stats)
  60          return;
  61      }
  62  
  63      /**
  64       * View funcs
  65       */
  66      load_funcs('sessions/views/_stats_view.funcs.php');
  67  
  68      global $blog, $admin_url, $rsc_url;
  69      global $Session, $UserSettings, $DB;
  70  
  71      global $datestartinput, $datestart, $datestopinput, $datestop;
  72      global $preset_referer_type, $preset_agent_type;
  73  
  74      $tab = param( 'tab', 'string', 'summary', true );
  75      $tab3 = param( 'tab3', 'string', '', true );
  76  
  77      switch( $tab )
  78      {
  79          case 'other':
  80              $preset_results_title = T_('Direct browser hits');
  81              $preset_referer_type = 'direct';
  82              $preset_agent_type = 'browser';
  83              $preset_filter_all_url = '?ctrl=stats&amp;tab=referers&amp;blog='.$blog;
  84              $hide_columns = 'referer';
  85              break;
  86  
  87          case 'referers':
  88              $preset_results_title = T_('Refered browser hits');
  89              $preset_referer_type = 'referer';
  90              $preset_agent_type = 'browser';
  91              $preset_filter_all_url = '?ctrl=stats&amp;tab=referers&amp;blog='.$blog;
  92              break;
  93  
  94          case 'refsearches':
  95              if( $tab3 == 'hits' )
  96              {
  97                  $preset_results_title = T_('Search hits');
  98                  $preset_referer_type = 'search';
  99                  $preset_agent_type = 'browser';
 100                  $preset_filter_all_url = '?ctrl=stats&amp;tab=refsearches&amp;tab3=hits&amp;blog='.$blog;
 101              }
 102              break;
 103      }
 104  
 105      if( param_date( 'datestartinput', T_('Invalid date'), false,  NULL ) !== NULL )
 106      {    // We have a user provided localized date:
 107          memorize_param( 'datestart', 'string', NULL, trim(form_date($datestartinput)) );
 108      }
 109      else
 110      {    // We may have an automated param transmission date:
 111          param( 'datestart', 'string', '', true );
 112      }
 113      if( param_date( 'datestopinput', T_('Invalid date'), false, NULL ) !== NULL )
 114      {    // We have a user provided localized date:
 115          memorize_param( 'datestop', 'string', NULL, trim(form_date($datestopinput)) );
 116      }
 117      else
 118      {    // We may have an automated param transmission date:
 119          param( 'datestop', 'string', '', true );
 120      }
 121  
 122      $exclude = param( 'exclude', 'integer', 0, true );
 123      $sess_ID = param( 'sess_ID', 'integer', NULL, true );
 124      $remote_IP = param( 'remote_IP', 'string', NULL, true );
 125      $referer_type = isset( $preset_referer_type ) ? $preset_referer_type : param( 'referer_type', 'string', NULL, true );
 126      $agent_type = isset( $preset_agent_type ) ? $preset_agent_type : param( 'agent_type', 'string', NULL, true );
 127      $device = param( 'device', 'string', NULL, true );
 128      $hit_type = param( 'hit_type', 'string', NULL, true );
 129      $reqURI = param( 'reqURI', 'string', NULL, true );
 130  
 131      // Create result set:
 132  
 133      $SQL = new SQL();
 134      $SQL->SELECT( 'SQL_NO_CACHE hit_ID, sess_ID, sess_device, hit_datetime, hit_type, hit_referer_type, hit_uri, hit_disp, hit_ctrl, hit_action, hit_blog_ID, hit_referer, hit_remote_addr,'
 135          . 'user_login, hit_agent_type, blog_shortname, dom_name, goal_name, hit_keyphrase, hit_serprank, hit_response_code' );
 136      $SQL->FROM( 'T_hitlog LEFT JOIN T_basedomains ON dom_ID = hit_referer_dom_ID'
 137          . ' LEFT JOIN T_sessions ON hit_sess_ID = sess_ID'
 138          . ' LEFT JOIN T_blogs ON hit_blog_ID = blog_ID'
 139          . ' LEFT JOIN T_users ON sess_user_ID = user_ID'
 140          . ' LEFT JOIN T_track__goalhit ON hit_ID = ghit_hit_ID'
 141          . ' LEFT JOIN T_track__goal ON ghit_goal_ID = goal_ID' );
 142  
 143      $CountSQL = new SQL();
 144      $CountSQL->SELECT( 'SQL_NO_CACHE COUNT(hit_ID)' );
 145      $CountSQL->FROM( 'T_hitlog' );
 146  
 147      $operator = ($exclude ? ' <> ' : ' = ' );
 148  
 149      if( ! empty( $sess_ID ) )
 150      { // We want to filter on the session ID:
 151          $filter = 'hit_sess_ID' . $operator . $sess_ID;
 152          $SQL->WHERE( $filter );
 153          $CountSQL->WHERE( $filter );
 154      }
 155      elseif( !empty($remote_IP) ) // TODO: allow combine
 156      { // We want to filter on the goal name:
 157          $filter = 'hit_remote_addr' . $operator . $DB->quote( $remote_IP );
 158          $SQL->WHERE( $filter );
 159          $CountSQL->WHERE( $filter );
 160      }
 161  
 162      if( !empty($referer_type) )
 163      {
 164          $filter = 'hit_referer_type = ' .$DB->quote($referer_type);
 165          $SQL->WHERE_and( $filter );
 166          $CountSQL->WHERE_and( $filter );
 167      }
 168  
 169      if( !empty($agent_type) )
 170      {
 171          $filter = 'hit_agent_type = '. $DB->quote($agent_type);
 172          $SQL->WHERE_and( $filter );
 173          $CountSQL->WHERE_and( $filter );
 174      }
 175  
 176      if( !empty($device) )
 177      {
 178          if( $device == 'other' )
 179          { // Unknown device
 180              $device = '';
 181          }
 182          $filter = 'sess_device = '. $DB->quote($device);
 183          $SQL->WHERE_and( $filter );
 184          $CountSQL->WHERE_and( $filter );
 185          $CountSQL->FROM_add( 'LEFT JOIN T_sessions ON hit_sess_ID = sess_ID' );
 186      }
 187  
 188      if( !empty($hit_type) )
 189      {
 190          $filter = 'hit_type = '. $DB->quote($hit_type);
 191          $SQL->WHERE_and( $filter );
 192          $CountSQL->WHERE_and( $filter );
 193      }
 194  
 195      if( !empty($reqURI) )
 196      {
 197          $filter = 'hit_uri LIKE ' .$DB->quote( $reqURI );
 198          $SQL->WHERE_and( $filter );
 199          $CountSQL->WHERE_and( $filter );
 200      }
 201  
 202      if( !empty($datestart) )
 203      {
 204          $SQL->WHERE_and( 'hit_datetime >= '.$DB->quote($datestart.' 00:00:00') );
 205          $CountSQL->WHERE_and( 'hit_datetime >= '.$DB->quote($datestart.' 00:00:00') );
 206      }
 207      if( !empty($datestop) )
 208      {
 209          $SQL->WHERE_and( 'hit_datetime <= '.$DB->quote($datestop.' 23:59:59') );
 210          $CountSQL->WHERE_and( 'hit_datetime <= '.$DB->quote($datestop.' 23:59:59') );
 211      }
 212  
 213  
 214      if( !empty( $blog ) )
 215      {
 216          $filter = 'hit_blog_ID = ' .$DB->escape($blog);
 217          $SQL->WHERE_and( $filter );
 218          $CountSQL->WHERE_and( $filter );
 219      }
 220  
 221      $resuts_param_prefix = 'hits_';
 222      if( !empty( $preset_referer_type ) )
 223      {
 224          $resuts_param_prefix = substr( $preset_referer_type, 0, 8 ).'_'.$resuts_param_prefix;
 225      }
 226  
 227      $default_order = '--D';
 228  
 229      $Results = new Results( $SQL->get(), $resuts_param_prefix, $default_order, $UserSettings->get( 'results_per_page' ), $CountSQL->get() );
 230  
 231      // Initialize Results object
 232      hits_results( $Results, array( 'default_order' => $default_order ) );
 233  
 234      if( is_ajax_content() )
 235      { // init results param by template name
 236          if( !isset( $params[ 'skin_type' ] ) || ! isset( $params[ 'skin_name' ] ) )
 237          {
 238              debug_die( 'Invalid ajax results request!' );
 239          }
 240          $Results->init_params_by_skin( $params[ 'skin_type' ], $params[ 'skin_name' ] );
 241      }
 242  
 243      // Display results:
 244      $Results->display();
 245  
 246      if( !is_ajax_content() )
 247      { // Create this hidden div to get a function name for AJAX request
 248          echo '<div id="'.$resuts_param_prefix.'ajax_callback" style="display:none">'.__FUNCTION__.'</div>';
 249      }
 250  }
 251  
 252  
 253  /**
 254   * @todo Transform to make this a stub for {@link $Hitlist}
 255   *
 256   * Extract stats
 257   */
 258  function refererList(
 259      $howMany = 5,
 260      $visitURL = '',
 261      $disp_blog = 0,
 262      $disp_uri = 0,
 263      $type = "'referer'",        // was: 'referer' normal refer, 'invalid', 'badchar', 'blacklist', 'rss', 'robot', 'search'
 264                                                      // new: 'search', 'blacklist', 'referer', 'direct', ('spam' but spam is not logged)
 265      $groupby = '',     // dom_name
 266      $blog_ID = '',
 267      $get_total_hits = false, // Get total number of hits (needed for percentages)
 268      $get_user_agent = false ) // Get the user agent
 269  {
 270      global $DB, $res_stats, $stats_total_hits, $ReqURI;
 271  
 272      if( strpos( $type, "'" ) !== 0 )
 273      { // no quote at position 0
 274          $type = "'".$type."'";
 275      }
 276  
 277      //if no visitURL, will show links to current page.
 278      //if url given, will show links to that page.
 279      //if url="global" will show links to all pages
 280      if (!$visitURL)
 281      {
 282          $visitURL = $ReqURI;
 283      }
 284  
 285      if( $groupby == '' )
 286      { // No grouping:
 287          $sql = 'SELECT hit_ID, UNIX_TIMESTAMP(hit_datetime) AS hit_datetime, hit_referer, dom_name';
 288      }
 289      else
 290      { // group by
 291          if( $groupby == 'baseDomain' )
 292          { // compatibility HACK!
 293              $groupby = 'dom_name';
 294          }
 295          $sql = 'SELECT COUNT(*) AS totalHits, hit_referer, dom_name';
 296      }
 297      if( $disp_blog )
 298      {
 299          $sql .= ', hit_blog_ID';
 300      }
 301      if( $disp_uri )
 302      {
 303          $sql .= ', hit_uri';
 304      }
 305      if( $get_user_agent )
 306      {
 307          $sql .= ', agnt_signature';
 308      }
 309  
 310      $sql_from_where = "
 311                FROM T_hitlog LEFT JOIN T_basedomains ON dom_ID = hit_referer_dom_ID
 312               WHERE hit_referer_type IN (".$type.")
 313                 AND hit_agent_type = 'browser'";
 314      if( !empty($blog_ID) )
 315      {
 316          $sql_from_where .= " AND hit_blog_ID = '".$blog_ID."'";
 317      }
 318      if ( $visitURL != 'global' )
 319      {
 320          $sql_from_where .= " AND hit_uri = '".$DB->escape($visitURL, 0, 250)."'";
 321      }
 322  
 323      $sql .= $sql_from_where;
 324  
 325      if( $groupby == '' )
 326      { // No grouping:
 327          $sql .= ' ORDER BY hit_ID DESC';
 328      }
 329      else
 330      { // group by
 331          $sql .= " GROUP BY ".$groupby." ORDER BY totalHits DESC";
 332      }
 333      $sql .= ' LIMIT '.$howMany;
 334  
 335      $res_stats = $DB->get_results( $sql, ARRAY_A );
 336  
 337      if( $get_total_hits )
 338      { // we need to get total hits
 339          $sql = 'SELECT COUNT(*) '.$sql_from_where;
 340          $stats_total_hits = $DB->get_var( $sql );
 341      }
 342      else
 343      { // we're not getting total hits
 344          $stats_total_hits = 1;        // just in case some tries a percentage anyway (avoid div by 0)
 345      }
 346  
 347  }
 348  
 349  
 350  /*
 351   * stats_hit_ID(-)
 352   */
 353  function stats_hit_ID()
 354  {
 355      global $row_stats;
 356      echo $row_stats['visitID'];
 357  }
 358  
 359  /*
 360   * stats_hit_remote_addr(-)
 361   */
 362  function stats_hit_remote_addr()
 363  {
 364      global $row_stats;
 365      echo $row_stats['hit_remote_addr'];
 366  }
 367  
 368  /*
 369   * stats_time(-)
 370   */
 371  function stats_time( $format = '' )
 372  {
 373      global $row_stats;
 374      if( $format == '' )
 375          $format = locale_datefmt().' '.locale_timefmt();
 376      echo date_i18n( $format, $row_stats['hit_datetime'] );
 377  }
 378  
 379  
 380  /*
 381   * stats_total_hit_count(-)
 382   */
 383  function stats_total_hit_count()
 384  {
 385      global $stats_total_hits;
 386      echo $stats_total_hits;
 387  }
 388  
 389  
 390  /*
 391   * stats_hit_count(-)
 392   */
 393  function stats_hit_count( $disp = true )
 394  {
 395      global $row_stats;
 396      if( $disp )
 397          echo $row_stats['totalHits'];
 398      else
 399          return $row_stats['totalHits'];
 400  }
 401  
 402  
 403  /*
 404   * stats_hit_percent(-)
 405   */
 406  function stats_hit_percent(
 407      $decimals = 1,
 408      $dec_point = '.' )
 409  {
 410      global $row_stats, $stats_total_hits;
 411      $percent = $row_stats['totalHits'] * 100 / $stats_total_hits;
 412      echo number_format( $percent, $decimals, $dec_point, '' ).'&nbsp;%';
 413  }
 414  
 415  
 416  /*
 417   * stats_blog_ID(-)
 418   */
 419  function stats_blog_ID()
 420  {
 421      global $row_stats;
 422      echo $row_stats['hit_blog_ID'];
 423  }
 424  
 425  
 426  /*
 427   * stats_blog_name(-)
 428   */
 429  function stats_blog_name()
 430  {
 431      global $row_stats;
 432  
 433      $BlogCache = & get_BlogCache();
 434      $Blog = & $BlogCache->get_by_ID($row_stats['hit_blog_ID']);
 435  
 436      $Blog->disp('name');
 437  }
 438  
 439  
 440  /*
 441   * stats_referer(-)
 442   */
 443  function stats_referer( $before='', $after='', $disp_ref = true )
 444  {
 445      global $row_stats;
 446      $ref = trim($row_stats['hit_referer']);
 447      if( strlen($ref) > 0 )
 448      {
 449          echo $before;
 450          if( $disp_ref ) echo htmlentities( $ref );
 451          echo $after;
 452      }
 453  }
 454  
 455  
 456  /*
 457   * stats_basedomain(-)
 458   */
 459  function stats_basedomain( $disp = true )
 460  {
 461      global $row_stats;
 462      if( $disp )
 463          echo htmlentities( $row_stats['dom_name'] );
 464      else
 465          return $row_stats['dom_name'];
 466  }
 467  
 468  
 469  /**
 470   * Displays keywords used for search leading to this page
 471   */
 472  function stats_search_keywords( $keyphrase, $length = 45 )
 473  {
 474      global $evo_charset;
 475  
 476      if( empty( $keyphrase ) )
 477      {
 478          return '<span class="note">['.T_('n.a.').']</span>';
 479      }
 480  
 481      // Save original string
 482      $keyphrase_orig = $keyphrase;
 483  
 484      $keyphrase = strmaxlen($keyphrase, $length, '...', 'raw');
 485  
 486      // Convert keyword encoding, some charsets are supported only in PHP 4.3.2 and later.
 487      // This fixes encoding problem for Cyrillic keywords
 488      // See http://forums.b2evolution.net/viewtopic.php?t=17431
 489      $keyphrase = htmlentities( $keyphrase, ENT_COMPAT, $evo_charset );
 490  
 491      return '<span title="'.format_to_output( $keyphrase_orig, 'htmlattr' ).'">'.$keyphrase.'</span>';
 492  }
 493  
 494  
 495  /**
 496   * Generate a random ip
 497   *
 498   * @return string ip
 499   */
 500  function generate_random_ip()
 501  {
 502      return mt_rand(0, 255).'.'.mt_rand(0, 255).'.'.mt_rand(0, 255).'.'.mt_rand(0, 255);
 503  }
 504  
 505  
 506  /**
 507   * Generate fake hit statistics
 508   *
 509   * @param integer the number of days to generate statistics
 510   * @param integer min interval between hits in seconds
 511   * @param integer max interval between hits in seconds
 512   * @param boolean TRUE to display the process dots during generating of the hits
 513   * @return integer count of inserted hits
 514   */
 515  function generate_hit_stat( $days, $min_interval, $max_interval, $display_process = false )
 516  {
 517      global $baseurlroot, $admin_url, $user_agents, $DB, $htsrv_url;
 518  
 519      load_class('items/model/_itemlistlight.class.php', 'ItemListLight');
 520      load_class('sessions/model/_hit.class.php', 'Hit');
 521  
 522      $links = array();
 523  
 524      $BlogCache = & get_BlogCache();
 525  
 526      $blogs_id = $BlogCache->load_public();
 527  
 528      foreach ($blogs_id as $blog_id)
 529      { // handle all public blogs
 530              $listBlog = & $BlogCache->get_by_ID($blog_id);
 531          if (empty($listBlog))
 532          {
 533              continue;
 534          }
 535  
 536          $ItemList = new ItemListLight($listBlog);
 537          $filters = array();
 538  
 539          # This is the list of categories to restrict the linkblog to (cats will be displayed recursively)
 540          # Example: $linkblog_cat = '4,6,7';
 541          $linkblog_cat = '';
 542  
 543          # This is the array if categories to restrict the linkblog to (non recursive)
 544          # Example: $linkblog_catsel = array( 4, 6, 7 );
 545          $linkblog_catsel = array(); // $cat_array;
 546          // Compile cat array stuff:
 547          $linkblog_cat_array = array();
 548          $linkblog_cat_modifier = '';
 549  
 550          compile_cat_array($linkblog_cat, $linkblog_catsel, /* by ref */ $linkblog_cat_array, /* by ref */ $linkblog_cat_modifier, $listBlog->ID);
 551  
 552          $filters['cat_array'] = $linkblog_cat_array;
 553          $filters['cat_modifier'] = $linkblog_cat_modifier;
 554  
 555  
 556          $ItemList->set_default_filters($filters);
 557  
 558          // Get the items list of current blog
 559          $ItemList->query();
 560  
 561          if (!$ItemList->result_num_rows)
 562          { // Nothing to display:
 563              continue;
 564          }
 565  
 566          while ($Item = & $ItemList->get_category_group())
 567          {
 568              // Open new cat:
 569              $Chapter = & $Item->get_main_Chapter();
 570              while ($Item = & $ItemList->get_item())
 571              {
 572                  $links[] = array('link' => '/' . $listBlog->siteurl . '/' . $Chapter->get_url_path() . $Item->urltitle, // trim($Chapter->get_permanent_url(NULL ,' ')).
 573                      'blog_id' => $blog_id);
 574              }
 575          }
 576  
 577          // add search links for all blogs
 578          $links[] = array('link' => url_add_param( '/' . $listBlog->siteurl, 's=$keywords$&disp=search&submit=Search', '&' ),
 579              'blog_id' => $blog_id);
 580  
 581          $links[] = array('link' => url_add_param( '/' . $listBlog->siteurl, 'disp=users', '&' ),
 582              'blog_id' => $blog_id,
 583              'disp' => 'users');
 584  
 585          $links[] = array('link' => url_add_param( '/'.$listBlog->siteurl, 'disp=user&user_ID=1', '&' ),
 586              'blog_id' => $blog_id,
 587              'disp' => 'users');
 588  
 589          $links[] = array('link' => url_add_param( '/' . $listBlog->siteurl, 'disp=threads', '&' ),
 590              'blog_id' => $blog_id,
 591              'disp' => 'threads');
 592  
 593          $links[] = array('link' => url_add_param( '/' . $listBlog->siteurl, 'disp=profile', '&' ),
 594              'blog_id' => $blog_id,
 595              'disp' => 'profile');
 596  
 597          $links[] = array(
 598                  'link' => $htsrv_url.'anon_async.php',
 599                  'blog_id' => $blog_id
 600              );
 601      }
 602  
 603      $referes = array('http://www.fake-referer1.com',
 604          'http://www.fake-referer2.com',
 605          'http://www.fake-referer3.com',
 606          'http://www.fake-referer4.com',
 607          'http://www.fake-referer5.com',
 608          'http://www.fake-referer6.com',
 609          'http://www.fake-referer7.com',
 610          'http://www.fake-referer8.com',
 611          'http://www.fake-referer9.com',
 612          'http://www.mail.google.com/fake/referer',
 613          'http://www.webmail.aol.com/fake/referer',
 614          'http://www.mail.yahoo.com/fake/referer',
 615          'http://bloglines.com/fake/referer',
 616          'http://www.fake-refer-online-casino1.com',
 617          'http://www.fake-refer-online-casino2.com',
 618          'http://www.fake-refer-online-casino3.com',
 619          'http://www.google.com/url?sa=t&rct=j&q=$keywords$&source=web&cd=4',
 620          'http://www.bing.com/search?q=$keywords$&src=IE-SearchBox&FORM=IE8SRC'
 621      );
 622  
 623      $devices = array(
 624              'iphone',
 625              'ipad',
 626              'andrtab',
 627              'android',
 628              'berrytab',
 629              'blkberry',
 630              'winphone',
 631              'wince',
 632              'palm',
 633              'gendvice'
 634          );
 635  
 636      $robots = array();
 637      foreach ($user_agents as $lUserAgent)
 638      {
 639          if ($lUserAgent[0] == 'robot')
 640          {
 641              $robots[] = $lUserAgent[1];
 642          }
 643      }
 644  
 645      $robots_count = count($robots) - 1;
 646  
 647      $ref_count = count($referes) - 1;
 648  
 649      $admin_link = array('link' => $admin_url,
 650          'blog_id' => NULL);
 651  
 652      $links_count = count($links);
 653  
 654      if( empty( $links_count ) )
 655      {
 656          $Messages->add('Do not have blog links to generate statistics');
 657          break;
 658      }
 659  
 660      // generate users id array
 661  
 662      $users_array = $DB->get_results('
 663                      SELECT user_ID
 664                        FROM T_users
 665                        WHERE user_status = "activated" OR user_status= "autoactivated"
 666                        LIMIT 10'
 667                      , 'ARRAY_A');
 668  
 669      $users_count = count( $users_array );
 670      $devices_count = count( $devices );
 671  
 672      if( empty( $users_count ) )
 673      {
 674          $Messages->add('Do not have valid users to generate statistics');
 675          break;
 676      }
 677  
 678      // Calculate the period of testing
 679      $cur_time = time();
 680      $past_time = mktime(date("H"), date("i"), date("s"), date("m"), date("d") - $days, date("Y"));
 681  
 682      $insert_data = '';
 683      $insert_data_count = 0;
 684  
 685      // create session array for testing
 686      $sessions = array();
 687      mt_srand(crc32(microtime()));
 688      for ($i = 0; $i <= $users_count - 1; $i++)
 689      {
 690          $sessions[] = array(
 691                  'sess_ID'          => -1,
 692                  'sess_key'         => generate_random_key(32),
 693                  'sess_start_ts'    => 0,
 694                  'sess_lastseen_ts' => 0,
 695                  'sess_ipaddress'   => generate_random_ip(),
 696                  'sess_user_ID'     => $users_array[$i]['user_ID'],
 697                  'sess_device'      => $devices[ mt_rand( 0, $devices_count - 1 ) ],
 698                  'pervios_link'     => '',
 699                  'robot'            => ''
 700              );
 701      }
 702  
 703      // main cycle of generation
 704      //mt_srand(crc32(microtime()));
 705      for ($time_shift = $past_time; $cur_time > $time_shift; $time_shift += mt_rand($min_interval, $max_interval))
 706      {
 707          //mt_srand(crc32(microtime()));
 708          $insert_data_count = $insert_data_count + 1;
 709  
 710          $rand_i = mt_rand(0, $users_count - 1);
 711          $rand_link = mt_rand(0, $links_count - 1);
 712          $cur_seesion = $sessions[$rand_i];
 713  
 714  
 715          if (strstr($links[$rand_link]['link'], '$keywords$'))
 716          { // check if the current search link is selected randomly.
 717              // If yes, generate search link and add it to DB
 718              //mt_srand(crc32(microtime()+ $time_shift));
 719              $keywords = 'fake search ' . mt_rand(0, 9);
 720              $links[$rand_link]['link'] = str_replace('$keywords$', urlencode($keywords), $links[$rand_link]['link']);
 721              if (strstr($links[$rand_link]['link'], 's='))
 722              {
 723                  $links[$rand_link]['s'] = $keywords;
 724              }
 725          }
 726  
 727  
 728          if ($cur_seesion['sess_ID'] == -1)
 729          { // This session needs initialization:
 730              $cur_seesion['sess_start_ts'] = $time_shift - 1;
 731              $cur_seesion['sess_lastseen_ts'] = $time_shift;
 732  
 733              $DB->query("
 734                      INSERT INTO T_sessions ( sess_key, sess_start_ts, sess_lastseen_ts, sess_ipaddress, sess_user_ID, sess_device )
 735                      VALUES (
 736                          '" . $cur_seesion['sess_key'] . "',
 737                          '" . date('Y-m-d H:i:s', $cur_seesion['sess_start_ts']) . "',
 738                          '" . date('Y-m-d H:i:s', $cur_seesion['sess_lastseen_ts']) . "',
 739                          " . $DB->quote( $cur_seesion['sess_ipaddress'] ) . ",
 740                          " . $cur_seesion['sess_user_ID'] . ",
 741                          " . $DB->quote( $cur_seesion['sess_device'] ) . "
 742                      )");
 743  
 744              $cur_seesion['sess_ID'] = $DB->insert_id;
 745              $sessions[$rand_i] = $cur_seesion;
 746  
 747              $Test_hit = new Hit('', $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $links[$rand_link]);
 748              $Test_hit->log();
 749          }
 750          else
 751          {
 752              if (($time_shift - $cur_seesion['sess_lastseen_ts']) > 3000 || !empty($cur_seesion['robot']))
 753              { // This session last updated more than 3000 sec ago. Instead of this session create a new session.
 754                  $cur_seesion = array(
 755                      'sess_ID'          => -1,
 756                      'sess_key'         => generate_random_key(32),
 757                      'sess_start_ts'    => 0,
 758                      'sess_lastseen_ts' => 0,
 759                      'sess_ipaddress'   => generate_random_ip(),
 760                      'sess_user_ID'     => $users_array[mt_rand(0, $users_count - 1)]['user_ID'],
 761                      'sess_device'      => $devices[ mt_rand( 0, $devices_count - 1 ) ],
 762                      'pervios_link'     => '',
 763                      'robot'            => ''
 764                  );
 765  
 766                  $cur_seesion['sess_start_ts'] = $time_shift - 1;
 767                  $cur_seesion['sess_lastseen_ts'] = $time_shift;
 768                  $r_num = mt_rand(0, 100);
 769                  if ($r_num > 40)
 770                  { // Create anonymous user and make double insert into hits.
 771                      $cur_seesion['sess_user_ID'] = -1;
 772                      $DB->query("
 773                              INSERT INTO T_sessions ( sess_key, sess_start_ts, sess_lastseen_ts, sess_ipaddress, sess_device )
 774                              VALUES (
 775                                  '" . $cur_seesion['sess_key'] . "',
 776                                  '" . date('Y-m-d H:i:s', $cur_seesion['sess_start_ts']) . "',
 777                                  '" . date('Y-m-d H:i:s', $cur_seesion['sess_lastseen_ts']) . "',
 778                                  " . $DB->quote( $cur_seesion['sess_ipaddress'] ) . ",
 779                                  " . $DB->quote( $cur_seesion['sess_device'] ) . "
 780                              )");
 781  
 782                      if ($r_num >= 80)
 783                      { // Create robot hit
 784                          $cur_seesion['robot'] = $robots[mt_rand(0, $robots_count)];
 785                      }
 786                  }
 787                  else
 788                  {
 789                      $DB->query("
 790                              INSERT INTO T_sessions( sess_key, sess_start_ts, sess_lastseen_ts, sess_ipaddress, sess_user_ID, sess_device )
 791                              VALUES (
 792                                  '" . $cur_seesion['sess_key'] . "',
 793                                  '" . date('Y-m-d H:i:s', $cur_seesion['sess_start_ts']) . "',
 794                                  '" . date('Y-m-d H:i:s', $cur_seesion['sess_lastseen_ts']) . "',
 795                                  " . $DB->quote($cur_seesion['sess_ipaddress']) . ",
 796                                  " . $cur_seesion['sess_user_ID'] . ",
 797                                  " . $DB->quote( $cur_seesion['sess_device'] ) . "
 798                              )");
 799                  }
 800  
 801                  $cur_seesion['sess_ID'] = $DB->insert_id;
 802  
 803                  if (mt_rand(0, 100) > 20)
 804                  {
 805                      //$ref_count
 806                      $ref_link = $referes[mt_rand(0, $ref_count)];
 807                      if (strstr($ref_link, '$keywords$'))
 808                      { // check if the current search link is selected randomly.
 809                          $keywords = 'fake search ' . mt_rand(0, 9);
 810                          $ref_link = str_replace('$keywords$', urlencode($keywords), $ref_link);
 811                      }
 812                  }
 813                  else
 814                  {
 815                      $ref_link = '';
 816                  }
 817  
 818                  if ($cur_seesion['sess_user_ID'] == -1)
 819                  {
 820                      if (empty($cur_seesion['robot']))
 821                      {
 822                          $link = array('link' => '/htsrv/login.php',
 823                              'blog_id' => 1);
 824  
 825                          $Test_hit = new Hit($ref_link, $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $link);
 826  
 827                          $Test_hit->log();
 828  
 829                          $link = array('link' => '/htsrv/login.php?redirect_to=fake_stat',
 830                              'blog_id' => 1);
 831  
 832                          $Test_hit = new Hit($baseurlroot, $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'] + 3, 1, $link);
 833  
 834                          $Test_hit->log();
 835  
 836                          $cur_seesion['pervios_link'] = $baseurlroot . $link['link'];
 837                      }
 838                      else
 839                      {
 840                          if (mt_rand(0, 100) < 50)
 841                          { // robot hit
 842                              $Test_hit = new Hit('', $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $links[$rand_link], $cur_seesion['robot']);
 843                          }
 844                          else
 845                          { // rss/atom hit
 846                              $Test_hit = new Hit('', $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $links[$rand_link], NULL, NULL, 1);
 847                          }
 848                          $Test_hit->log();
 849                      }
 850                  }
 851                  else
 852                  {
 853                      if (mt_rand(0, 100) < 10)
 854                      { // Test hit to admin page
 855                          $Test_hit = new Hit('', $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $admin_link, NULL, 1);
 856                          $Test_hit->log();
 857                          $cur_seesion['pervios_link'] = $admin_url;
 858                      }
 859                      else
 860                      {
 861                          $Test_hit = new Hit($ref_link, $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $links[$rand_link]);
 862                          $Test_hit->log();
 863                          $cur_seesion['pervios_link'] = $baseurlroot . $links[$rand_link]['link'];
 864                      }
 865                  }
 866              }
 867              else
 868              {
 869                  // Update session
 870                  $cur_seesion['sess_lastseen_ts'] = $time_shift;
 871  
 872                  $Test_hit = new Hit($cur_seesion['pervios_link'], $cur_seesion['sess_ipaddress'], $cur_seesion['sess_ID'], $cur_seesion['sess_lastseen_ts'], 1, $links[$rand_link]);
 873                  $Test_hit->log();
 874  
 875  
 876  
 877                  $sql = "UPDATE T_sessions SET
 878                                  sess_lastseen_ts = '" . date('Y-m-d H:i:s', $cur_seesion['sess_lastseen_ts']) . "'
 879                                  WHERE sess_ID = {$cur_seesion['sess_ID']}";
 880  
 881                  $DB->query($sql, 'Update session');
 882  
 883                  $cur_seesion['pervios_link'] = $baseurlroot . $links[$rand_link]['link'];
 884  
 885                  $sessions[$rand_i] = $cur_seesion;
 886              }
 887          }
 888  
 889          $sessions[$rand_i] = $cur_seesion;
 890  
 891          if( $display_process )
 892          {
 893              if( $insert_data_count % 100 == 0 )
 894              { // Display a process of creating by one dot for 100 hits
 895                  echo ' .';
 896                  flush();
 897              }
 898          }
 899      }
 900  
 901      return $insert_data_count;
 902  }
 903  
 904  
 905  /**
 906   * Get domain type title by value
 907   *
 908   * @param string Domain type value
 909   * @return string Domain title
 910   */
 911  function stats_dom_type_title( $dom_type, $escape_quotes = false )
 912  {
 913      $dom_type_titles = array(
 914              'unknown'    => $escape_quotes ? TS_('Unknown') : T_('Unknown'),
 915              'normal'     => $escape_quotes ? TS_('Referer') : T_('Referer'),
 916              'searcheng'  => $escape_quotes ? TS_('Search referer') : T_('Search referer'),
 917              'aggregator' => $escape_quotes ? TS_('Aggregator referer') : T_('Aggregator referer'),
 918              'email'      => $escape_quotes ? TS_('Email provider') : T_('Email provider'),
 919          );
 920  
 921      if( isset( $dom_type_titles[ $dom_type ] ) )
 922      {
 923          return $dom_type_titles[ $dom_type ];
 924      }
 925  
 926      return $dom_type;
 927  }
 928  
 929  ?>

title

Description

title

Description

title

Description

title

title

Body