#!/usr/bin/php
<?php

$CAMPSITE_DIR = dirname(dirname(__FILE__));
$GLOBALS['g_campsiteDir'] = $CAMPSITE_DIR;
$ETC_DIR = $CAMPSITE_DIR . '/conf';

require_once("$CAMPSITE_DIR/bin/cli_script_lib.php");

if (!camp_is_readable("$ETC_DIR/install_conf.php")) {
	exit;
}

// includes installation configuration file
require_once("$ETC_DIR/install_conf.php");

if (!is_file("$ETC_DIR/database_conf.php")) {
	echo "\n";
	echo "Database configuration file is missed!\n";
	echo "\n";
	exit;
}

// includes campsite initialisation
require_once("$CAMPSITE_DIR/include/campsite_init.php");

// defines the notifier template file name
define('NOTIFIER_TEMPLATE', '_events_notifier.tpl');

// connects to database server
if (db_server_connect() == false) {
    msg_error('Connecting to DB server');
    exit;
}

// sets the array which holds message data
$message = array();

// reads reply address
$message['reply'] = get_reply_address();

// reads events
$tstamp = get_event_timestamp();

$sql_query = "SELECT u.Name AS UserRealName, u.EMail AS UserEMail, "
    . "u.UName AS UserName, e.Name AS EventName, l.text AS LogText, "
    . "l.time_created AS LogTimeCreated, NOW() AS RightNow "
    . "FROM Log AS l, liveuser_users AS u, Events AS e "
    . "WHERE l.fk_event_id = e.Id AND e.Notify = 'Y' AND l.fk_user_id = u.Id "
    . "AND l.time_created > '" . $tstamp . "' "
    . "ORDER BY l.time_created ASC";
if (!$result = mysql_query($sql_query)) {
    msg_error('Reading log timestamp');
    exit;
}

$i = 0;
$num_rows = mysql_num_rows($result);

// if events log exists, inits smarty template system
if ($num_rows > 0) {
    $tpl = init_smarty();
}

$last_tstamp = 0;
while ($i < $num_rows && $row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $last_tstamp = $row['LogTimeCreated'];

    // assigns values to smarty template variables
    $tpl->assign('user_real_name', $row['UserRealName']);
    $tpl->assign('user_name', $row['UserName']);
    $tpl->assign('user_email', $row['UserEMail']);
    $tpl->assign('event_text', $row['LogText']);
    $tpl->assign('event_timestamp', $row['LogTimeCreated']);

    // sets the message body text
    $message['text'] = '';
    $message['text'] = $tpl->fetch(NOTIFIER_TEMPLATE);

    // reads users emails to notify to
    $recipients = get_users_to_notify();
    if (sizeof($recipients) <= 0) {
        continue;
    }

    // sets message recipients and subject
    $message['recipients'] = $recipients;
    $message['subject'] = $row['EventName'];

    // sends email message
    send_email($message);
    $i++;
}

if ($last_tstamp != 0) {
    $sql_query = "UPDATE AutoId SET LogTStamp = '" . $last_tstamp . "'";
    mysql_query($sql_query);
}


/**
 * Reads reply address
 *
 * @return string
 */
function get_reply_address()
{
    $sql_query = "SELECT EMail FROM liveuser_users WHERE UName = 'admin'";
    if (!$result = mysql_query($sql_query)) {
        msg_error('Getting reply address');
        exit;
    }

    if (mysql_num_rows($result) <= 0) {
        msg_error('There is no reply address');
        exit;
    }

    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    mysql_free_result($result);

    return $row['EMail'];
} // fn get_reply_address


/**
 * @return string
 */
function get_event_timestamp()
{
    $sql_query = 'SELECT LogTStamp FROM AutoId';
    if (!$result = mysql_query($sql_query)) {
        msg_error('Getting logtstamp');
        exit;
    }

    if (mysql_num_rows($result) <= 0) {
        msg_error('There is no logtstamp');
        exit;
    }

    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    mysql_free_result($result);

    return $row['LogTStamp'];
} // fn get_event


/**
 * @return array $users
 *      An array with users emails to notify to
 */
function get_users_to_notify()
{
    $sql_query = "SELECT g.group_id "
        . "FROM liveuser_groups AS g, liveuser_rights AS r, liveuser_grouprights AS l "
        . "WHERE g.group_id = l.group_id AND r.right_id = l.right_id AND r.right_define_name = 'MailNotify'";
    if (!$result = mysql_query($sql_query)) {
        msg_error('Getting groups');
        exit;
    }

    $groups = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $groups[] = $row['group_id'];
    }

    mysql_free_result($result);
    if (sizeof($groups) <= 0) {
        return null;
    }

    $groups_str = implode(',', $groups);
    $sql_query = 'SELECT u.EMail '
        . 'FROM liveuser_users AS u, liveuser_groupusers AS g, liveuser_perm_users AS p '
        . 'WHERE g.perm_user_id = p.perm_user_id '
        . 'AND u.Id = p.auth_user_id AND g.group_id IN (' . $groups_str . ')';
    if (!$result = mysql_query($sql_query)) {
        msg_error('Getting recipients');
        exit;
    }

    $users = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $users[] = $row['EMail'];
    }
    mysql_free_result($result);

    $sql_query = 'SELECT u.EMail '
        . 'FROM liveuser_users AS u, liveuser_rights AS r, '
        . 'liveuser_userrights AS l, liveuser_perm_users AS p '
        . 'WHERE u.Id = p.auth_user_id AND l.right_id = r.right_id '
        . 'AND l.perm_user_id = p.perm_user_id AND r.right_id = l.right_id '
        . "AND r.right_define_name = 'MailNotify'";
    if (!$result = mysql_query($sql_query)) {
        msg_error('Getting recipients');
        exit;
    }

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $users[] = $row['EMail'];
    }
    mysql_free_result($result);

    return $users;
} // fn get_users_to_notify


/**
 * @return boolean
 *      true on success, false on failure
 */
function send_email($p_message)
{
    if (!is_array($p_message) || empty($p_message)) {
        return false;
    }

    $to = implode(', ', $p_message['recipients']);
    $subject = $p_message['subject'];
    $message = $p_message['text'];
    $headers = "From: ".$p_message['reply']."\n" .
        'X-Mailer: PHP/' . phpversion() . "\n" .
        "MIME-Version: 1.0\n" .
        "Content-Type: text/plain; charset=utf-8\n" .
        "Content-Transfer-Encoding: 8bit\n\n";

    // sends the email message
    return mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers);
} // fn send_email


/**
 * @return object $tpl
 *      Smarty object
 */
function init_smarty()
{
    global $CAMPSITE_DIR;

    // includes smarty main class
    require_once("$CAMPSITE_DIR/include/smarty/Smarty.class.php");

    // instantiates smarty template system
    $tpl = new Smarty();

    // inits smarty configuration settings
    $tpl->left_delimiter = '{{';
    $tpl->right_delimiter = '}}';
    $tpl->force_compile = true;
    $tpl->config_dir = $CAMPSITE_DIR.'/include/smarty/configs';
    $tpl->template_dir = $CAMPSITE_DIR.'/templates/system_templates';
    $tpl->compile_dir = $CAMPSITE_DIR.'/templates_cache';

    return $tpl;
} // fn init_smarty


/**
 * @return boolean
 */
function db_server_connect()
{
    global $Campsite;

    $db_host = $Campsite['DATABASE_SERVER_ADDRESS']
        .':'.$Campsite['DATABASE_SERVER_PORT'];
    $db_user = $Campsite['DATABASE_USER'];
    $db_pass = $Campsite['DATABASE_PASSWORD'];
    $db_name = $Campsite['DATABASE_NAME'];
    $link = mysql_connect($db_host, $db_user, $db_pass);
    if (!$link) {
        return false;
    }

    mysql_select_db($db_name, $link);
    return mysql_query("SET NAMES 'utf8'");
} // fn db_server_connect


/**
 * @param string $p_msg
 */
function msg_error($p_msg)
{
    print('ERROR: ' . $p_msg);
} // fn msg_error

?>
