<?php

require_once 'newedge/classes/NE_PluginCollection.php';

/**
* @package Admin
*/
class ExecuteService extends NE_Action
{
    var $permission     = '';

    // user authentication and permission validation done inside dispatch()

    function dispatch()
    {
        if (defined('RUNNING_SERVICE_SCRIPT')) {
            // *************************
            // Running from outside CE
            // *************************
            if (isset($_GET['service']) && $this->settings->get('Allow run services from URL')) {
                $runService = $_GET['service'];
                $manuallyExecuted = 2;
	            $this->logger->log(2, "** OUTSIDE SERVICE REQUEST **: services.php called for service '$runService'");	
            } elseif ($runService = @$_SERVER['argv'][1]) {
	            $this->logger->log(2, "** CRON REQUEST **: services.php called for service '$runService'");
                $manuallyExecuted = 0;
            } else {
                die('Service not defined or services not set up to run from the URL.');
            }

            if ($this->settings->get("plugin_{$runService}_Enabled") != 1) {
                die("Service $runService is not Enabled.");
            }
        } else {
            // ************************
            // Running from inside CE
            // ************************
            if (!isset($_SESSION['userId'])) {
                NE_Lib::redirectPage('index.php?fuse=admin&amp;view=Login');
            }
            if (!$this->user->hasPermission('admin_manage_plugins')) {
                trigger_error("You don't have enough permissions to trigger this action", E_USER_ERROR);
                exit;
            }

            if (!isset($_GET['service'])) {
                die('Service not defined.');
            }
            $manuallyExecuted = 1;
            $runService = $_GET['service'];
        }

        $plugins = new NE_PluginCollection("services", $this->user);

        // service execution can take a while
        @set_time_limit(0);

        while ($plugin = $plugins->getNext()) {
            if ($plugin->getInternalName() == $runService) {
                $messages = $plugin->execute();
                $errors = '';
                $results = '';
                if (is_array($messages)) {
                    foreach ($messages as $message) {
                        if (is_a($message, 'NE_Error')) {
                            $errors .= $message->getMessage()."\n";
                        } else {
                            $results .= "$message\n";
                        }
                    }
                }

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

                if (defined('RUNNING_SERVICE_SCRIPT') && $errors) {
                    echo "Errors calling plugin ".$plugin->getInternalName().":\n$errors\n";
                    if ($recipients = $this->settings->get('Application Error Notification')) {
                        require_once 'newedge/classes/NE_MailGateway.php';
                        $mailGateway = new NE_MailGateway();
                        $body = "ClientExec automated error notification\n\nThe service plugin ".$this->settings->get("plugin_".$plugin->getInternalName()."_Plugin Name")
                               ." generated the following error(s):\n$errors\n";

                        $recipients = explode("\r\n", $recipients);
                        foreach ($recipients as $recipient) {
                            // bypass mail queue, because it could be it the one failing, creating thus an infinite loop
                            $mailSend = $mailGateway->mailMessageEmail(  array('HTML' => null, 'plainText' => $body),
                                                                         $this->settings->get('Support E-mail'),
                                                                         $this->settings->get('Support E-mail'),
                                                                         $recipient,
                                                                         '',
                                                                         'ClientExec Service Plugin Error Notification',
                                                                         1);
                            if (is_a($mailSend, 'NE_Error')) {
                                echo $mailSend->getMessage();
                            }
                        }
                    }
                }

                if (!defined('RUNNING_SERVICE_SCRIPT') && $errors) {
                    NE_Lib::addMessage(nl2br($errors));
                    NE_Lib::addMessage(nl2br($results));
                }

                if (!defined('RUNNING_SERVICE_SCRIPT') && !$errors) {
                    NE_Lib::addMessage($this->lang('Service executed successfully'));
                    NE_Lib::addMessage(nl2br($results));
                }
                break;
            }
        }

        if (!defined('RUNNING_SERVICE_SCRIPT')) {
            NE_Lib::redirectPage("index.php?settingID=".$_REQUEST['service']."&amp;fuse=admin&amp;view=Services");
        }
    }
}

?>
