<?php
// no direct access
defined('_JEXEC') or die('Restricted access');

/* * ***********************************************************************
 * Users App for Watchful
 * Copyright (c) 2006-2013 Anything Digital & Inetis
 * ************************************************************************
 * Watchful.li is a web site monitoring and security service.
 * 
 * Although Watchful.li is a paid service, 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.
 *
 * This header must not be removed. Additional contributions/changes
 * may be added to this header as long as no information is deleted.
 * ************************************************************************
 * Get the latest version of this program at: https://watchful.li
 * *********************************************************************** */

//Require the watchfulliApps class in class.apps.php
require_once(JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_watchfulli' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'apps.php');
// We extend a base class to pass additional parameters in the language strings
// It will probably be included in the client but we also put it here so the app will work
// even for older version of the Watchful client.
class UsersAppAlert extends AppAlert
{
    public $parameter1;
    public $parameter2;
    public $parameter3;

    public function UsersAppAlert($level, $message, $parameter1 = null, $parameter2 = null, $parameter3 = null)
    {
        if ($level != null && $message != null)
        {
            $this->level = $level;
            $this->message = $message;
            $this->parameter1 = $parameter1;
            $this->parameter2 = $parameter2;
            $this->parameter3 = $parameter3;
        }
    }

}
class plgWatchfulliAppsUsersApp extends watchfulliApps
{

    public function createAppAlert($level, $message, $parameter1 = null, $parameter2 = null, $parameter3 = null)
    {
        $alert = new UsersAppAlert($level, $message, $parameter1, $parameter2, $parameter3);
        $this->addAlert($alert);
    }

    public function appMainProgram($oldValuesSerialized = null)
    {
        $this->setName("usersApp");
        $this->setDescription("Users app to check if a new user is registered");
        $debug = $this->params->get('debug', 0);

        if (version_compare(JVERSION, '1.6.0', 'ge'))
        {
            $query = $this->buildQuery();
        }
        else
        {
            $query = $this->buildQueryJ15();
        }

        $db = & JFactory::getDBO();
        $db->setQuery($query);
        if (version_compare(JVERSION, '1.6.0', 'ge'))
        {
            $usersIds = $db->loadColumn();
        }
        else
        {
            $usersIds = $db->loadResultArray();
        }

        if ($usersIds)
        {
            $newValue = json_encode($usersIds);
        }
        else
        {
            $newValue = "[]";
        }
        if ($debug)
            $this->createAppAlert(1, "[DEBUG][USERSAPP] New value: $newValue");

        //Looking for an old value
        $oldValue = $this->readExAppValue($oldValuesSerialized);
        if ($debug)
            $this->createAppAlert(1, "[DEBUG][USERSAPP] Old value: $oldValue");
        if ($oldValue == null) //First Time the app is triggered
        {
            $this->createAppValue('usersApp', $newValue);
        }
        elseif ($oldValue != $newValue)
        {
            $this->createAppAlert(1, "USERSAPP_LIST_CHANGED");
            $this->updateAppValue('usersApp', $newValue);
            $oldUsersIds = json_decode($oldValue);
            if (is_array($oldUsersIds))
            {
                // check if there are new users
                if (count(array_diff($usersIds, $oldUsersIds)))
                {
                    if ($this->params->get('show_usernames', 0) == 1)
                    {
                        // Show individual usernames
                        $addedUsersIds = array_diff($usersIds, $oldUsersIds);
                        foreach ($addedUsersIds as $userId)
                        {
                            $username = & JFactory::getUser($userId)->name;
                            $this->createAppAlert(1, "USERSAPP_USER_ADDED", $username);
                        }
                    }
                    else
                    {
                        // Just tell that there are new users
                        $this->createAppAlert(1, "USERSAPP_USERS_ADDED");
                    }
                }
                // check if there are deleted users
                if (count(array_diff($oldUsersIds, $usersIds)))
                {
                    $this->createAppAlert(1, "USERSAPP_USERS_DELETED");
                }
            }
        }
        else
        {
            if ($debug)
                $this->createAppAlert(1, "[DEBUG][USERSAPP] No changes");
        }

        return $this;
    }

    private function buildQueryJ15()
    {
        $query = "SELECT id from #__users";
        $usersgroups = $this->params->get('usersgroups', array());
        if (!is_array($usersgroups))
            $usersgroups = array($usersgroups);
        if (!empty($usersgroups))
        {
            $query .= " WHERE gid IN (" . implode(',', $usersgroups) . ")";
        }
        $query .= " ORDER BY id ASC";
        return $query;
    }

    private function buildQuery()
    {
        $usersgroups = $this->params->get('usersgroups', array());
        if (!is_array($usersgroups))
            $usergroups = array($usersgroups);
        $query = "SELECT DISTINCT id FROM #__users";
        if (!empty($usersgroups))
        {
            $query .= " LEFT JOIN #__user_usergroup_map ug ON #__users.id = ug.user_id
                WHERE ug.group_id IN (" . implode(',', $usersgroups) . ")";
        }
        $query .= " ORDER BY id ASC";
        return $query;
    }

}
