<?php if (!defined('PmWiki')) exit();
# vim: set ts=4 sw=4 et:
##
##        File: whoswhere.php
##     Version: 2009-03-08
##      SVN ID: $Id: whoswhere.php 308 2009-03-07 23:45:19Z pbowers $
##      Status: alpha
##      Author: Peter Bowers
## Create Date: March 7, 2009
##   Copyright: 2009, Peter Bowers
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License, Version 2, as
## published by the Free Software Foundation.
## http://www.gnu.org/copyleft/gpl.html
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##

$RecipeInfo['WhosWhere']['Version'] = '2009-03-08';

# Whenever this script is included it automatically updates according to the
# current session_id, $action, etc.
if (session_id()) {
    global $wwExpire;
	$db = wwWhosWhereInit();
	SDV($wwExpire, 60*60*24); // expire data older than 24 hours
	$sqldel = "DELETE FROM whoswhere WHERE sessionid='".session_id()."' OR date<$Now-$wwExpire";
    if ($db->exec($sqldel) === false) {
        echo "<pre>DATABASE ERROR(del): ".print_r($db->errorInfo(),true)."</pre><br>\n";
        die();
    }
	if (!$Author) {
		if (@$_COOKIE['author']) $Author = $_COOKIE['author'];
		elseif (@$_SERVER['REMOTE_USER']) $Author = $_SERVER['REMOTE_USER'];
        else $Author = $_SERVER['REMOTE_ADDR']; 
	}
	$sqlins = "INSERT INTO whoswhere (sessionid, authid, author, ip, action, pn, date) VALUES ('".session_id()."', '$AuthId', '$Author', '$_SERVER[REMOTE_ADDR]', '$action', '$pagename', $Now)";
	if ($db->exec($sqlins) === false) {
        echo "<pre>DATABASE ERROR(ins): ".print_r($db->errorInfo(),true)."</pre><br>\n";
        die();
    }
}

# $wwHeaderFmt and $wwDetailFmt can be overridden
# $wwNoAuthHeaderFmt and $wwNoAuthDetailFmt use $wwHeaderFmt and 
#    $wwDetailFmt if they are blank (default)
# arguments to (:whoswhere ARGS:) can override all of the above:
#    headerfmt=
#    detailfmt=
#    noauthheaderfmt=
#    noauthdetailfmt=
# $wwAuthFields lists allowed fields for authorized users to see
# $wwNoAuthFields lists allowed fields for NONauthorized users to see, but it
#    uses the value from $wwAuthFields if $wwNoAuthFields is blank (default)
Markup('whoswhere', '>{$var}', '/\(:whoswhere([^:]*):\)/ie', 'wwDisplay(\$pagename, "$1")');
function wwDisplay($pagename, $args)
{
    global $Now, $AuthId, $wwSeconds, $wwHeaderFmt, $wwDetailFmt, 
        $wwNoAuthHeaderFmt, $wwNoAuthDetailFmt, $wwAuthFields, $wwNoAuthFields;

    # Handle all the defaults & overrides to get $DetailFmt, $HeaderFmt, $Fields
    $opt = ParseArgs($args);
	SDV($wwSeconds, 60*20); // report activity within the last 20 minutes
    if (@$opt['headerfmt']) 
        $wwHeaderFmt = str_replace('\n', "\n", $opt['headerfmt']);
    else 
        SDV($wwHeaderFmt, "|| border=1\n||! Who? ||! Where? ||! Doing What? ||! When?||");
    if (@$opt['detailfmt']) 
        $wwDetailFmt = $opt['detailfmt'];
    else 
        SDV($wwDetailFmt, '|| {anyid} || {pn} || {action} || {date} ago||');
    if (@$opt['noauthdetailfmt']) 
        $wwNoAuthDetailFmt = $opt['noauthdetailfmt'];
    else 
        SDV($wwNoAuthDetailFmt, '');
    if (@$opt['noauthheaderfmt']) 
        $wwNoAuthHeaderFmt = str_replace('\n', "\n", $opt['noauthheaderfmt']);
    else 
        SDV($wwNoAuthHeaderFmt, '');
    $DetailFmt = $wwDetailFmt;
    $HeaderFmt = $wwHeaderFmt;
    if (!$AuthId && $wwNoAuthDetailFmt) $DetailFmt = $wwNoAuthDetailFmt;
    else $DetailFmt = $wwDetailFmt;
    if (!$AuthId && $wwNoAuthHeaderFmt) $HeaderFmt = $wwNoAuthHeaderFmt;
    else $HeaderFmt = $wwHeaderFmt;
    SDV($wwAuthFields, 'anyid|ip|authid|author|pn|action|date');
    SDV($wwNoAuthFields, '');
    $Fields = ((!$AuthId && $wwNoAuthFields) ? $wwNoAuthFields : $wwAuthFields);

	$db = wwWhosWhereInit();
	$sql = "SELECT * FROM whoswhere WHERE date>$Now-$wwSeconds";
	$rtn = '';
	foreach ($db->query($sql) as $row) {
		$secs = $Now - $row['date'];
		$mins = floor($secs/60);
		$secs = $secs - ($mins*60);
        $row['date'] = sprintf("%d:%02d", $mins, $secs);
        $row['anyid'] = ($row['authid']?$row['authid']:"(not logged in)") . 
            ($row['author']?' ('.$row['author'].')':'');
        $rtn .= "\n" . preg_replace("/\\{($Fields)\\}/e", '$row["$1"]', $DetailFmt);
	}
	if ($rtn) 
		$rtn = $HeaderFmt . $rtn;
	else
		$rtn = '(Nobody is Anywhere)';
	return($rtn);
}

# Return the $db resource (create if necessary)
function wwWhosWhereInit()
{
    global $WorkDir, $wwDatabase;
    SDV($wwDatabase, "sqlite:$WorkDir/whoswhere.sqlite.db");
    try {
        $db = new PDO($wwDatabase);
    } catch (PDOException $e) {
        echo "Error!: " . $e->getMessage() . " (database=$wwDatabase)<br/>";
        die(); // possibly no sqlite support?
    }

    # Now check if the whoswhere table exists and create if necessary.
    $statement = $db->query('SELECT name FROM sqlite_master WHERE type = \'table\' AND name = \'whoswhere\'');
    $result = $statement->fetchAll();

    if( sizeof($result) == 0 ){
        $sqlcreate = 'CREATE TABLE whoswhere (sessionid CHAR(40) PRIMARY KEY, authid CHAR(30), author CHAR(50), ip CHAR(20), action CHAR(15), pn CHAR(50), date INT)';
        if ($db->exec($sqlcreate) === false) {
            echo "<pre>DATABASE ERROR(create): ".print_r($db->errorInfo(),true)."</pre><br>\n";
            die();
        }
    }

	return($db);
}