<?php
/*************************
  Coppermine Photo Gallery
  ************************
  Copyright (c) 2003-2005 Coppermine Dev Team
  v1.1 originally written by Gregory DEMAR

  This program is free software; 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.
  ********************************************
  Coppermine version: 1.4.3
  $Source$
  $Revision: 1.1 $
  $Author: Nibbler $
  $Date: 2006-01-17 $
**********************************************/

// Add plugin_install action
$thisplugin->add_action('plugin_install','online_install');

// Add page_start action
$thisplugin->add_action('page_start','online_page_start');

// Add plugin_uninstall action
$thisplugin->add_action('plugin_uninstall','online_uninstall');

// Add plugin_cleanup action
$thisplugin->add_action('plugin_cleanup','online_cleanup');

// Add search display action
$thisplugin->add_filter('plugin_block','online_mainpage');

// Add a configure action
$thisplugin->add_action('plugin_configure','online_configure');


function online_configure()
{
echo <<< EOT
    <form action="{$_SERVER['REQUEST_URI']}" method="post">
        <p>
            How long do you want to keep users listed as online for before they are assumed to have gone ?
        </p>
        <div style="margin:25;">
        <table border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td><input type="text" name="duration" value="10" /></td>
                <td>Minutes</td>
            </tr>
        </table>
        </div>
        <span>
           <input type="submit" name="submit" value="Submit" /> &nbsp;&nbsp;&nbsp;
            <input type="button" name="cancel" onClick="window.location='pluginmgr.php';" value="Cancel" />
        </span>
    </form>
EOT;
}

function online_page_start()
{
        global $raw_ip, $CONFIG;

        $CONFIG['TABLE_ONLINE'] = $CONFIG['TABLE_PREFIX']."mod_online";

        $user_id = USER_ID;
        $user_name = USER_NAME;

        if (defined('LOGIN_PHP')){
                cpg_db_query("DELETE FROM {$CONFIG['TABLE_ONLINE']} WHERE user_id = 0 AND user_ip = '$raw_ip'");
                return;
        }

        if (defined('LOGOUT_PHP')){
                cpg_db_query("DELETE FROM {$CONFIG['TABLE_ONLINE']} WHERE user_id = $user_id");
                return;
        }

        cpg_db_query("DELETE FROM {$CONFIG['TABLE_ONLINE']} WHERE last_action < NOW() - INTERVAL {$CONFIG['mod_updates_duration']} MINUTE");



        if ($user_id) {
                cpg_db_query("REPLACE INTO {$CONFIG['TABLE_ONLINE']} (user_id, user_name, user_ip, last_action) VALUES ('$user_id', '$user_name', '$raw_ip', NOW())");

        } else{
                $testarray = explode('.',$raw_ip);
                $teststr = $testarray[0] . '.' . $testarray[1];
                $sel = cpg_db_query("SELECT user_ip FROM {$CONFIG['TABLE_ONLINE']} WHERE user_ip LIKE '$teststr%'");
                $res = mysql_fetch_row($sel);
                $result = $res[0];

                if (mysql_num_rows($sel)){
                        cpg_db_query("UPDATE {$CONFIG['TABLE_ONLINE']} SET last_action = NOW() WHERE user_ip = '$result' LIMIT 1");
                } else {
                        cpg_db_query("INSERT INTO {$CONFIG['TABLE_ONLINE']} (user_id, user_name, user_ip, last_action) VALUES ('$user_id', '$user_name', '$raw_ip', NOW())");
                }
        }
}

function online_mainpage()
{
        global $CONFIG, $cpg_udb, $comment_date_fmt, $matches ;

        if($matches[1] != 'onlinestats') {
          return $matches;
        }
        if (defined('UDB_INTEGRATION')){
                $CONFIG['TABLE_USERS'] = $cpg_udb->usertable;
                $user_id = $cpg_udb->field['user_id'];
                $user_name = $cpg_udb->field['username'];
        } else {
                $user_id = 'user_id';
                $user_name = 'user_name';
        }

        $result = cpg_db_query("SELECT COUNT(*) FROM {$CONFIG['TABLE_USERS']}");
        $num_users = mysql_fetch_array($result);
        $num_users = $num_users[0];

        $result = cpg_db_query("SELECT COUNT(*) FROM {$CONFIG['TABLE_ONLINE']}");
        $num_online = mysql_fetch_array($result);
        $num_online = $num_online[0];

        $result = cpg_db_query("SELECT COUNT(*) FROM {$CONFIG['TABLE_ONLINE']} WHERE user_id <> 0");
        $num_reg_online = mysql_fetch_array($result);
        $num_reg_online = $num_reg_online[0];
        $result = cpg_db_query("SELECT $user_id, $user_name FROM {$CONFIG['TABLE_USERS']} ORDER BY $user_id DESC LIMIT 1");
        $row = mysql_fetch_row($result);
        $newest_user_name = $row[1];
        $newest_user_id = $row[0];

        $result = cpg_db_query("SELECT user_id, user_name FROM {$CONFIG['TABLE_ONLINE']} WHERE user_id <> 0");

        $logged_in_array = array();

        while ($row = mysql_fetch_assoc($result)) {
                $logged_in_array[] = "<a href=\"profile.php?uid={$row['user_id']}\">{$row['user_name']}</a>";
        }

        $logged_in_names = implode(', ', array_unique($logged_in_array));

        $num_guests = $num_online - $num_reg_online;

        // most users online - TND
        if ($num_online > $CONFIG['record_online_users'])
        {
                $time = time() + ($CONFIG['time_offset'] - date("O") / 100) * 3600;

                $CONFIG['record_online_date'] = localised_date(-1, $comment_date_fmt);
                $CONFIG['record_online_users'] = $num_online;

                $result = cpg_db_query("UPDATE {$CONFIG['TABLE_CONFIG']} SET value = '$num_online' WHERE name = 'record_online_users'");
                $result = cpg_db_query("UPDATE {$CONFIG['TABLE_CONFIG']} SET value = '$time' WHERE name = 'record_online_date'");
        }

        starttable("100%", "Who is Online");

        echo '<tr><td class="tableb">';
        echo ($num_users == 1) ? "We have 1 registered user<br>" : "We have {$num_users} registered users<br>";
        echo "The newest registered user is <a href=\"profile.php?uid={$newest_user_id}\">{$newest_user_name}</a><br>";
        echo ($num_online == 1) ? "In total there is 1 user online" : "In total there are {$num_online} users online";
        echo " :: {$num_reg_online} Registered, and ";
        echo ($num_guests == 1) ? "1 Guest<br>" : "{$num_guests} Guests<br>";
        echo 'Most users ever online: ' . $CONFIG['record_online_users'] . " on " . localised_date($CONFIG['record_online_date'], $comment_date_fmt ) . "<br>";
        echo "Registered Users: {$logged_in_names}</td></tr>";

        endtable();
}

// Install
function online_install()
{
        global $CONFIG, $thisplugin;

        if (isset($_POST['duration'])) {
                 require 'include/sql_parse.php';

                // create table
                $db_schema = $thisplugin->fullpath . '/schema.sql';
                $sql_query = fread(fopen($db_schema, 'r'), filesize($db_schema));
                $sql_query = preg_replace('/CPG_/', $CONFIG['TABLE_PREFIX'], $sql_query);

                $sql_query = remove_remarks($sql_query);
                $sql_query = split_sql_file($sql_query, ';');
                $sql_query[] = "INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (name, value) VALUES ('mod_updates_duration', '{$_POST['duration']}')";

                foreach($sql_query as $q) cpg_db_query($q);

           return true;
    } else {
        return 1;
    }
}

// Unnstall (drop?)
function online_uninstall()
{
        global $CONFIG;

        if (!isset($_POST['drop'])) return 1;

        if ($_POST['drop']) {
                cpg_db_query("DROP TABLE IF EXISTS {$CONFIG['TABLE_ONLINE']}");
                cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'mod_updates_duration'");
           }

        return true;
}

// Ask if we want to drop the table
function online_cleanup($action) {
    if ($action===1) {
        echo <<< EOT
    <form action="{$_SERVER['REQUEST_URI']}" method="post">
        <p>
            Remove the table that was used to store online data ?
        </p>
        <div style="margin:25;">
        <table border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td><input type="radio" name="drop" value="1" /></td>
                <td>Yes</td>
            </tr>
            <tr>
                <td><input type="radio" name="drop" checked="checked" value="0" /></td>
                <td>No</td>
            </tr>
        </table>
        </div>
        <span>
           <input type="submit" name="submit" value="Submit" /> &nbsp;&nbsp;&nbsp;
            <input type="button" name="cancel" onClick="window.location='pluginmgr.php';" value="Cancel" />
        </span>
    </form>
EOT;
    }
}
?>