<?php if (!defined('PmWiki')) exit();

/*  Copyright 2005 Christophe David (www.christophedavid.org)
    This file is CurrentVisitors.php; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This script makes it easy to show how may visitors have been browsing
    your site (or a given group or a given page) during the n last seconds.

    To use this script, simply copy it into the cookbook/ directory
    and add the following line to config.php or a per-page/per-group
    customization file.

        include_once('cookbook/CurrentVisitors.php');
*/

################################################################################

SDV($MaximumNumberOfSecondsToConsiderAVisitorAsCurrent, 1800);
SDV($CurrentVisitorsDirectory, "$WorkDir/CurrentVisitors");

################################################################################
################################################################################
################################################################################

define(CURRENT_VISITORS, '1.11');

$NumberOfCurrentVisitors = 0;

if ($action == 'browse')
   {
   if (   (is_dir($CurrentVisitorsDirectory) == true)
       || (mkdirp($CurrentVisitorsDirectory) == true)
      )
      {
      # create a 0 byte file or update the timestamp of an existing one
      $FileName = $CurrentVisitorsDirectory . '/' . preg_replace('/[^0-9]/', '_', $_SERVER['REMOTE_ADDR']);
      touch($FileName);

      # cleanup too old files and count how many remain
      if (($DirectoryHandle = opendir($CurrentVisitorsDirectory)) == true)
         {
         $TimeNow = time();
         while (($file = readdir($DirectoryHandle)) == true)
            {
            if (is_dir($file) == false)
               {
               $FileFullPath = $CurrentVisitorsDirectory . '/' . $file;
               $FileStat     = stat($FileFullPath);
               $FileAge      = $TimeNow - $FileStat[9];
               if ($FileAge > $MaximumNumberOfSecondsToConsiderAVisitorAsCurrent)
                  {
                  unlink($FileFullPath);
                  }
               else
                  {
                  $NumberOfCurrentVisitors++;
                  }
               }
            }
         closedir($DirectoryHandle);
         }
      }
   }

Markup('CurrentVisitors', 'fulltext', "/\(:CurrentVisitors:\)/", $NumberOfCurrentVisitors);

################################################################################
?>