<?php
define('INCLUDE_STEPS', 'service');
require_once dirname(__FILE__) . '/common/common.php';
require_once 'classes/class.PluginInterface.php';

$manuallyExecuted = 0;
if(isset($_GET['service']) && $GLOBALS['gSettingsArray']['Allow run services from URL']){
	$runService = $_GET['service'];
	$manuallyExecuted = 2;
} elseif (!$runService = @$argv[1]) {
    die("Error: No service defined\n");
}

if(!isset($_GET['service'])){
	$GLOBALS['logger']->log(2, "** CRON REQUEST **: services.php called for service '$runService'");
} else {
	$GLOBALS['logger']->log(2, "** OUTSIDE SERVICE REQUEST **: services.php called for service '$runService'");	
}

// when called from the PHP binary, I need to provide the full path...
$plugins = new PluginInterface(dirname(__FILE__).'/plugins/services',array('execute'));
$pluginNames = $plugins->getFoundPluginNames();
foreach ($pluginNames as $plugin) {
    if ($plugin == $runService && $GLOBALS['gSettingsArray']["plugin_{$plugin}_Enabled"] == 1) {
        $messages = $plugins->callFunction($plugin, 'execute');
        $errors = '';
        $results = '';
        if (is_array($messages)) {
            foreach ($messages as $message) {
                if (is_error($message)) {
                    $errors .= $message->getMessage()."\n";
                } else {
                    $results .= "$message\n";
                }
            }
        }

        $query = "INSERT INTO services_log (plugin, time, manually_executed, results, errors) VALUES(?, ?, ?, ?, ?)";
        $GLOBALS['db']->query($query, $plugin, date('Y-m-d H:i:s'), $manuallyExecuted, $results, $errors);

        if ($errors) {
            echo "Errors calling plugin $plugin:\n$errors\n";
            if ($recipient = $GLOBALS['gSettingsArray']['Application Error Notification']) {
                $body = "ClientExec automated error notification\n\nThe service plugin ".$gSettingsArray["plugin_{$plugin}_Plugin Name"]
                       ." generated the following error(s):\n$errors\n";
                // bypass mail queue, because it could be it the one failing, creating thus an infinite loop
                MailMessageEmail($body,
                                 $gSettingsArray['Support E-mail'],
                                 $gSettingsArray['Support E-mail'],
                                 $recipient, '', 'ClientExec Service Plugin Error Notification', 1, 0);
            }
        }
        if(isset($_GET['service']) && !$errors){
        	echo strtoupper('Service '. $runService .' executed succesfully');
        }
    }
}

?>