<?php
/*
 * MODx Revolution
 *
 * Copyright 2006-2010 by the MODx Team.
 * All rights reserved.
 *
 * 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 program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

/**
 * Error handler for request/response processing.
 *
 * @package modx
 * @subpackage error
 */

/**
 * Abstract class for error handling and validation for requests.
 *
 * @abstract Implement a derivative of this class for error handling and
 * validation of any kind of MODx request.
 * @package modx
 * @subpackage error
 */
class modError {
    /**
    * @var array The array of errors
    */
    public $errors;
    /**
    * @var string The error message to output.
    */
    public  $message;
    /**
    * @var modX A reference to the $modx object.
    */
    public  $modx;
    /**
    * @var integer The total number of errors.
    */
    public  $total = 0;
    /**
     * @var boolean Indicates failure or success.
     */
    public  $status = false;
    protected $_objects = array();

    function __construct(modX &$modx, $message = '') {
        $this->modx =& $modx;
        $this->message = $message;
        $this->errors = array ();
    }

    /**
     * Adds an object to the validation queue.
     *
     * @access public
     * @param xPDOObject $obj An xPDOObject to validate.
     */
    public function addObjectToValidate(xPDOObject &$obj) {
        if (is_object($obj) && $obj instanceof xPDOObject) {
            $this->_objects[]= $obj;
        }
    }

    /**
     * Checks validation, and if any errors are found, returns them. Error
     * handlers that derive from this can determine their own behaviour should
     * errors be found.
     * @access public
     * @param xPDOObject/array $objs An xPDOObject or array of xPDOObjects to
     * add to the validation queue.
     * @return string The validation message returned.
     */
    public function checkValidation(array $objs= array()) {
        if (is_object($objs)) {
            $this->addObjectToValidate($objs);
        }
        else if (is_array($objs) && !empty($objs)) {
            foreach ($objs as $obj) {
                $this->addObjectToValidate($obj);
            }
        }
        return $this->_validate();
    }

    /**
     * Grabs formatted validation messages for all objects in the validation
     * queue.
     * @access protected
     * @return string The compiled validation message returned.
     */
    protected function _validate() {
        $s = '';
        foreach ($this->_objects as $obj) {
            if ($validator= $obj->getValidator()) {
                $messages= $validator->getMessages();
                if (!empty($messages)) {
                    $fields = array();
                    foreach ($messages as $message) {
                        $s .= $message['message'].'<br />'."\n";
                        if (!isset($fields[$message['field']])) $fields[$message['field']] = array();
                        $fields[$message['field']][$message['name']] = $message['message'];
                    }
                    foreach ($fields as $fieldKey => $field) {
                        foreach ($field as $fieldMsgName => $fieldMsg) {
                            $this->addField($fieldKey, $fieldMsg);
                        }
                    }
                }
            }
        }
        return $s;
    }

    /**
     * Process errors and return a proper output value.
     *
     * @param string $message The error message to output.
     * @param boolean $status Whether or not the action is a success or failure.
     * @param object|array $object The object to send back to output.
     * @return string|object|array The transformed object data array.
     */
    public function process($message = '', $status = false, $object = null) {
        if (isset($this->modx->registry) && $this->modx->registry->isLogging()) {
            $this->modx->registry->resetLogging();
        }
        if ($status === true) {
            $s = $this->_validate();
            if ($s !== '') {
                $status = false;
                $message = $s;
            }
        }
        $this->status = (boolean) $status;

        if ($message != '') {
            $this->message = $message;
        }
        $objarray = array ();
        if (is_array($object)) {
            $obj = reset($object);
            if (is_object($obj) && $obj instanceof xPDOObject) {
                $this->total = count($object);
            }
            unset ($obj);
        }
        $objarray = $this->toArray($object);
        return array (
            'success' => $status,
            'message' => $this->message,
            'total' => isset ($this->total) && $this->total != 0 ? $this->total : count($this->errors),
            'errors' => $this->errors,
            'object' => $objarray,
        );
    }

    /**
     * Add a specific field error to the error queue.
     *
     * @param string $name The id of the field.
     * @param string $error The error message.
     */
    public function addField($name, $error) {
        $this->errors[] = array (
            'id' => $name,
            'msg' => $error
        );
    }

    /**
     * Return the fields added as errors.
     *
     * @return array An array of errors for specific fields.
     */
    public function getFields() {
        $f = array ();
        $errors = array_values(array_filter($this->errors, array($this, 'isFieldError')));
        foreach ($errors as $fi) {
            $f[] = $fi['msg'];
        }
        return $f;
    }

    /**
     * Add an error to the error queue.
     *
     * @param string|array $msg An error message string or custom error array.
     */
    public function addError($msg) {
        $this->errors[] = $msg;
    }

    /**
     * Return all of the errors in the error queue.
     */
    public function getErrors($includeFields = false) {
        $errors = $this->errors;
        if (!$includeFields) {
            $errors = array_values(array_filter($this->errors, array($this, 'isNotFieldError')));
        }
        return $errors;
    }

    /**
     * Returns true if the error passed to it represents a field error.
     *
     * @param mixed $error An element of modError::errors.
     * @return boolean True if the error is a field error.
     */
    public function isFieldError($error) {
        return (is_array($error) && isset($error['msg']) && isset($error['id']) && count($error) == 2);
    }

    /**
     * Returns true if the error passed to it does not represent a field error.
     *
     * @param mixed $error An element of modError::errors.
     * @return boolean True if the error is not a field error.
     */
    public function isNotFieldError($error) {
        return (!is_array($error) || !(isset($error['msg']) && isset($error['id']) && count($error) == 2));
    }

    /**
     * Check to see if there is any errors on the queue.
     *
     * @return boolean True if there are errors or a message has been specified.
     */
    public function hasError() {
        return count($this->errors) > 0 || $this->message != '';
    }

    /**
     * Send a failure error message.
     *
     * @param string $message The error message to send.
     * @param object|array|string $object An object to send back to the output.
     */
    public function failure($message = '', $object = null) {
        return $this->process($message, false, $object);
    }

    /**
     * Send a success error message.
     *
     * @param string $message The error message to send.
     * @param object|array|string $object An object to send back to the output.
     */
    public function success($message = '', $object = null) {
        return $this->process($message, true, $object);
    }

    /**
     * Converts an object or objects embedded in an array, to arrays.
     *
     * This function also makes sure that any members of the array are not PHP
     * resource types (e.g. database connections, file handles, etc.).
     *
     * @param array|object $object An array or object to process.
     * @return array Returns an array representation of the object(s).
     */
    public function toArray($object) {
        $array = array ();
        if (is_array($object)) {
            while (list ($key, $value) = each($object)) {
                if (!is_resource($value)) {
                    if (is_object($value) || is_array($value)) {
                        $array[$key] = $this->toArray($value);
                    } else {
                        $array[$key] = $value;
                    }
                }
            }
        }
        elseif (is_object($object)) {
            if ($object instanceof xPDOObject) {
                $array = $this->toArray($object->toArray());
            } else {
                $array = $this->toArray(get_object_vars($object));
            }
        }
        if ($this->modx->getDebug() === true)
            $this->modx->log(xPDO::LOG_LEVEL_DEBUG, "modError::toArray() -- " . print_r($array, true));
        return $array;
    }

    /**
     * Resets the error messages.
     */
    public function reset() {
        $this->errors = array();
        $this->message = '';
    }
}

/**
 * Response class for Processor executions
 */
class modProcessorResponse {
    /**
     * When there is only a general error
     */
    const ERROR_GENERAL = 'error_general';
    /**
     * When there are only field-specific errors
     */
    const ERROR_FIELD = 'error_field';
    /**
     * When there is both field-specific and general errors
     */
    const ERROR_BOTH = 'error_both';
    /**
     * The field for the error type
     */
    const ERROR_TYPE = 'error_type';

    /**
     * @var modX A reference to the modX object
     */
    public $modx = null;
    /**
     * @var array A reference to the full response
     */
    public $response = null;
    /**
     * @var array A collection of modProcessorResponseError objects for each field-specific error
     */
    public $errors = array();
    /**
     * @var string The error type for this response
     */
    public $error_type = '';

    /**
     * The constructor for modProcessorResponse
     * 
     * @param modX $modx A reference to the modX object.
     * @param array $response The array response from the modX.runProcessor method
     */
    function __construct(modX &$modx,$response = array()) {
        $this->modx =& $modx;
        $this->response = $response;
        if ($this->isError()) {
            if (!empty($response['errors']) && is_array($response['errors'])) {
                foreach ($response['errors'] as $error) {
                    $this->errors[] = new modProcessorResponseError($error);
                }
                if (!empty($response['message'])) {
                    $this->error_type = modProcessorResponse::ERROR_BOTH;
                } else {
                    $this->error_type = modProcessorResponse::ERROR_FIELD;
                }
            } else {
                $this->error_type = modProcessorResponse::ERROR_GENERAL;
            }
        }
    }

    /**
     * Returns the type of error for this response
     * @return string The type of error returned
     */
    public function getErrorType() {
        return $this->error_type;
    }

    /**
     * Checks to see if the response is an error
     * @return Returns true if the response was a success, otherwise false
     */
    public function isError() {
        return empty($this->response) || empty($this->response['success']);
    }

    /**
     * Returns true if there is a general status message for the response.
     * @return boolean True if there is a general message
     */
    public function hasMessage() {
        return !empty($this->response['message']) ? true : false;
    }

    /**
     * Gets the general status message for the response.
     * @return string The status message
     */
    public function getMessage() {
        return !empty($this->response['message']) ? $this->response['message'] : '';
    }

    /**
     * Returns the entire response object in array form
     * @return array The array response
     */
    public function getResponse() {
        return $this->response;
    }

    /**
     * Returns true if an object was sent with this response.
     * @return boolean True if an object was sent.
     */
    public function hasObject() {
        return !empty($this->response['object']) ? true : false;
    }

    /**
     * Returns the array object, if is sent in the response
     * @return array The object in the response, usually the object being performed on.
     */
    public function getObject() {
        return !empty($this->response['object']) ? $this->response['object'] : array();
    }

    /**
     * An array of modProcessorResponseError objects for each field-specific error
     * @return array
     */
    public function getFieldErrors() {
        return $this->errors;
    }

    /**
     * Checks to see if there are any field-specific errors in this response
     * @return boolean True if there were field-specific errors
     */
    public function hasFieldErrors() {
        return !empty($this->errors) ? true : false;
    }

    /**
     * Gets all errors and adds them all into an array.
     *
     * @param string $fieldErrorSeparator The separator to use between fieldkey and message for field-specific errors.
     * @return array An array of all errors.
     */
    public function getAllErrors($fieldErrorSeparator = ': ') {
        $errormsgs = array();
        if ($response->hasMessage()) {
            $errormsgs[] = $response->getMessage();
        }
        if ($response->hasFieldErrors()) {
            $errors = $response->getFieldErrors();
            if (!empty($errors)) {
                foreach ($errors as $error) {
                    $errormsgs[] = $error->field.$fieldErrorSeparator.$error->message;
                }
            }
        }
        return $errormsgs;
    }
}
/**
 * An abstraction class of field-specific errors for a processor response
 */
class modProcessorResponseError {
    /**
     * @var array The error data itself
     */
    public $error = null;
    /**
     * @var string The field key that the error occurred on
     */
    public $field = null;
    /**
     * @var string The message that was sent for the field error
     */
    public $message = '';

    /**
     * The constructor for the modProcessorResponseError class
     *
     * @param array $error An array error response
     */
    function __construct($error = array()) {
        $this->error = $error;
        if (!empty($error['id'])) { $this->field = $error['id']; }
        if (!empty($error['msg'])) { $this->message = $error['msg']; }
    }

    /**
     * Returns the message for the field-specific error
     * @return string
     */
    public function getMessage() {
        return $this->message;
    }

    /**
     * Returns the field key for the field-specific error
     */
    public function getField() {
        return $this->field;
    }
    
    /**
     * Returns the array data for the field-specific error
     * @return array
     */
    public function getError() {
        return $this->error;
    }
}