#!/usr/local/bin/php
<?php
/**
 * This script counts the number of active authenticated user sessions.
 *
 * Command line options:
 *   '-l'   List the username of active authenticated users
 *   '-ll'  List the username and login time of active authenticated users
 *
 * Copyright 2007-2013 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL-2). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl.
 *
 * @author   Michael Slusarz <slusarz@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl LGPL-2
 * @package  Horde
 */

$baseFile = __DIR__ . '/../lib/Application.php';
if (file_exists($baseFile)) {
    require_once $baseFile;
} else {
    require_once 'PEAR/Config.php';
    require_once PEAR_Config::singleton()
        ->get('horde_dir', null, 'pear.horde.org') . '/lib/Application.php';
}
Horde_Registry::appInit('horde', array(
    'authentication' => 'none',
    'cli' => true
));
$sessionHandler = $GLOBALS['injector']->createInstance('Horde_SessionHandler');
try {
    $sessions = $sessionHandler->getSessionsInfo();
} catch (Horde_SessionHandler_Exception $e) {
    $cli->fatal('Session counting is not supported with the current session handler.');
}

if (($argc < 2) || (($argv[1] != '-l') && ($argv[1] != '-ll'))) {
    $cli->writeln(count($sessions));
} else {
    foreach ($sessions as $data) {
        if ($argv[1] == '-ll') {
            $cli->writeln($data['userid'] . ' [' . date('r', $data['timestamp']) . ']');
        } else {
            $cli->writeln($data['userid']);
        }
    }
    $cli->writeln($cli->green('Total Sessions: ' . count($sessions)));
}
