ahwelp hace 7 años
commit
c51e6abc63
Se han modificado 4 ficheros con 1057 adiciones y 0 borrados
  1. 12 0
      composer.json
  2. 108 0
      src/RequestResponse/Flash.php
  3. 808 0
      src/RequestResponse/Request.php
  4. 129 0
      src/RequestResponse/Response.php

+ 12 - 0
composer.json

@@ -0,0 +1,12 @@
+{
+    "name": "ahwelp/request-response",
+    "description": "Requests and responses",
+    "type": "library",
+    "authors": [
+        {
+            "name": "ahwelp",
+            "email": "ahwelp@universo.univates.br"
+        }
+    ],
+    "require": {}
+}

+ 108 - 0
src/RequestResponse/Flash.php

@@ -0,0 +1,108 @@
+<?php
+namespace RequestResponse;
+
+class Flash{
+
+    private static $_instance;
+
+    // Message types and shortcuts
+    const INFO    = 'i';
+    const SUCCESS = 's';
+    const WARNING = 'w';
+    const ERROR   = 'e';
+
+    const SESSION_NAME   = 'flashes';
+
+    const defaultType = self::INFO;
+
+    protected $msgTypes = [
+        self::ERROR   => 'error',
+        self::WARNING => 'warning',
+        self::SUCCESS => 'success',
+        self::INFO    => 'info',
+    ];
+
+    public $old_messages = Array();
+
+    public $new_messages = Array();
+
+    //SINGLETON==============================================
+
+    private function __construct(){
+        if(session_id() == '' || !isset($_SESSION)) {
+            session_start();
+        }
+        $this->old_messages = $_SESSION['flashes'];
+        unset( $_SESSION[self::SESSION_NAME] );
+    }
+
+    private static function newObj(){
+        if (!isset( self::$_response )) {
+            self::$_response = new Flash();
+        }
+        return self::$_response;
+    }
+
+    public function getInstance(){
+        if (!isset(self::$_response)) {
+            return self::newObj();
+        }
+        return self::$_response;
+    }
+    //=======================================================
+
+    public function load_to_session(){
+        $_SESSION[self::SESSION_NAME] = $this->new_messages;
+    }
+
+    public static function add_message($type = self::defaultType, $message){
+        $instance = self::getInstance();
+        $instance->new_messages[$type] = $message;
+        $instance->load_to_session();
+    }
+
+    public static function add_info($message){
+        $instance = self::getInstance();
+        $instance->new_messages[self::INFO] = $message;
+        $instance->load_to_session();
+    }
+
+    public static function add_error($message){
+        $instance = self::getInstance();
+        $instance->new_messages[self::ERROR] = $message;
+        $instance->load_to_session();
+    }
+
+    public static function get_errors(){
+        if(!self::has_errors()){
+            return Array();
+        }
+        return self::getInstance()->old_messages[self::ERROR];
+    }
+
+    public static function get_infos(){
+        if(!self::has_info()){
+            return Array();
+        }
+        return self::getInstance()->old_messages[self::INFO];
+    }
+
+    public static function has_errors(){
+        $instance = self::getInstance();
+        if( array_key_exists(self::ERROR, $instance->old_messages ) ){
+            return true;
+        }else{
+            return false;
+        }
+    }
+
+    public static function has_info(){
+        $instance = self::getInstance();
+        if( array_key_exists(self::INFO, $instance->old_messages ) ){
+            return true;
+        }else{
+            return false;
+        }
+    }
+
+}

+ 808 - 0
src/RequestResponse/Request.php

@@ -0,0 +1,808 @@
+<?php
+namespace RequestResponse;
+
+use RequestResponse\Response as Response;
+
+class Request{
+
+    function required_param($parname, $type) {
+        if (func_num_args() != 2 or empty($parname) or empty($type)) {
+            throw new \Exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
+        }
+        // POST has precedence.
+        if (isset($_POST[$parname])) {
+            $param = $_POST[$parname];
+        } else if (isset($_GET[$parname])) {
+            $param = $_GET[$parname];
+        } else {
+            throw new \Exception('');
+        }
+
+        if (is_array($param)) {
+            return required_param_array($parname, $type);
+        }
+
+        return self::clean_param($param, $type);
+    }
+
+    function required_param_array($parname, $type) {
+        if (func_num_args() != 2 or empty($parname) or empty($type)) {
+            throw new \Exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
+        }
+        // POST has precedence.
+        if (isset($_POST[$parname])) {
+            $param = $_POST[$parname];
+        } else if (isset($_GET[$parname])) {
+            $param = $_GET[$parname];
+        } else {
+            throw new \Exception('');
+        }
+        if (!is_array($param)) {
+            throw new \Exception('');
+        }
+
+        $result = array();
+        foreach ($param as $key => $value) {
+            if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
+                continue;
+            }
+            $result[$key] = clean_param($value, $type);
+        }
+        return $result;
+    }
+
+
+    public static function optional_param($parname, $default = '', $type){
+        if (func_num_args() != 3 or empty($parname) or empty($type)) {
+            throw new \Exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
+        }
+
+        if (isset($_POST[$parname])) {
+            $param = $_POST[$parname];
+        } else if (isset($_GET[$parname])) {
+            $param = $_GET[$parname];
+        } else {
+            return $default;
+        }
+
+        if (is_array($param)) {
+            return optional_param_array($parname, $default, $type);
+        }
+
+        return self::clean_param($param, $type);
+    }
+
+    public static function optional_param_array($parname, $default = Array(), $type) {
+        if (func_num_args() != 3 or empty($parname) or empty($type)) {
+            throw new \Exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
+        }
+
+        // POST has precedence.
+        if (isset($_POST[$parname])) {
+            $param = $_POST[$parname];
+        } else if (isset($_GET[$parname])) {
+            $param = $_GET[$parname];
+        } else {
+            return $default;
+        }
+        if (!is_array($param)) {
+            return $default;
+        }
+
+        $result = array();
+        foreach ($param as $key => $value) {
+            if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
+                continue;
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * Used by {@link optional_param()} and {@link required_param()} to
+     * clean the variables and/or cast to specific types, based on
+     * an options field.
+     * <code>
+     * $course->format = clean_param($course->format, PARAM_ALPHA);
+     * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
+     * </code>
+     *
+     * @param mixed $param the variable we are cleaning
+     * @param string $type expected format of param after cleaning.
+     * @return mixed
+     * @throws coding_exception
+     */
+    public static function clean_param($param, $type) {
+        global $CFG;
+
+        if (is_array($param)) {
+            throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
+        } else if (is_object($param)) {
+            if (method_exists($param, '__toString')) {
+                $param = $param->__toString();
+            } else {
+                throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
+            }
+        }
+
+        switch ($type) {
+            case PARAM_RAW:
+                // No cleaning at all.
+                $param = fix_utf8($param);
+                return $param;
+
+            case PARAM_RAW_TRIMMED:
+                // No cleaning, but strip leading and trailing whitespace.
+                $param = fix_utf8($param);
+                return trim($param);
+
+            case PARAM_INT:
+                // Convert to integer.
+                return (int)$param;
+
+            case PARAM_FLOAT:
+                // Convert to float.
+                return (float)$param;
+
+            case PARAM_ALPHA:
+                // Remove everything not `a-z`.
+                return preg_replace('/[^a-zA-Z]/i', '', $param);
+
+            case PARAM_ALPHAEXT:
+                // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
+                return preg_replace('/[^a-zA-Z_-]/i', '', $param);
+
+            case PARAM_ALPHANUM:
+                // Remove everything not `a-zA-Z0-9`.
+                return preg_replace('/[^A-Za-z0-9]/i', '', $param);
+
+            case PARAM_ALPHANUMEXT:
+                // Remove everything not `a-zA-Z0-9_-`.
+                return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
+
+            case PARAM_SEQUENCE:
+                // Remove everything not `0-9,`.
+                return preg_replace('/[^0-9,]/i', '', $param);
+
+            case PARAM_BOOL:
+                // Convert to 1 or 0.
+                $tempstr = strtolower($param);
+                if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
+                    $param = 1;
+                } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
+                    $param = 0;
+                } else {
+                    $param = empty($param) ? 0 : 1;
+                }
+                return $param;
+
+            case PARAM_NOTAGS:
+                // Strip all tags.
+                $param = fix_utf8($param);
+                return strip_tags($param);
+
+            case PARAM_TEXT:
+                // Leave only tags needed for multilang.
+                $param = fix_utf8($param);
+                // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
+                // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
+                do {
+                    if (strpos($param, '</lang>') !== false) {
+                        // Old and future mutilang syntax.
+                        $param = strip_tags($param, '<lang>');
+                        if (!preg_match_all('/<.*>/suU', $param, $matches)) {
+                            break;
+                        }
+                        $open = false;
+                        foreach ($matches[0] as $match) {
+                            if ($match === '</lang>') {
+                                if ($open) {
+                                    $open = false;
+                                    continue;
+                                } else {
+                                    break 2;
+                                }
+                            }
+                            if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
+                                break 2;
+                            } else {
+                                $open = true;
+                            }
+                        }
+                        if ($open) {
+                            break;
+                        }
+                        return $param;
+
+                    } else if (strpos($param, '</span>') !== false) {
+                        // Current problematic multilang syntax.
+                        $param = strip_tags($param, '<span>');
+                        if (!preg_match_all('/<.*>/suU', $param, $matches)) {
+                            break;
+                        }
+                        $open = false;
+                        foreach ($matches[0] as $match) {
+                            if ($match === '</span>') {
+                                if ($open) {
+                                    $open = false;
+                                    continue;
+                                } else {
+                                    break 2;
+                                }
+                            }
+                            if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
+                                break 2;
+                            } else {
+                                $open = true;
+                            }
+                        }
+                        if ($open) {
+                            break;
+                        }
+                        return $param;
+                    }
+                } while (false);
+                // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
+                return strip_tags($param);
+
+            case PARAM_COMPONENT:
+                // We do not want any guessing here, either the name is correct or not
+                // please note only normalised component names are accepted.
+                if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
+                    return '';
+                }
+                if (strpos($param, '__') !== false) {
+                    return '';
+                }
+                if (strpos($param, 'mod_') === 0) {
+                    // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
+                    if (substr_count($param, '_') != 1) {
+                        return '';
+                    }
+                }
+                return $param;
+
+
+            case PARAM_SAFEDIR:
+                // Remove everything not a-zA-Z0-9_- .
+                return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
+
+            case PARAM_SAFEPATH:
+                // Remove everything not a-zA-Z0-9/_- .
+                return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
+
+            case PARAM_FILE:
+                // Strip all suspicious characters from filename.
+                $param = fix_utf8($param);
+                $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
+                if ($param === '.' || $param === '..') {
+                    $param = '';
+                }
+                return $param;
+
+            case PARAM_PATH:
+                // Strip all suspicious characters from file path.
+                $param = fix_utf8($param);
+                $param = str_replace('\\', '/', $param);
+
+                // Explode the path and clean each element using the PARAM_FILE rules.
+                $breadcrumb = explode('/', $param);
+                foreach ($breadcrumb as $key => $crumb) {
+                    if ($crumb === '.' && $key === 0) {
+                        // Special condition to allow for relative current path such as ./currentdirfile.txt.
+                    } else {
+                        $crumb = clean_param($crumb, PARAM_FILE);
+                    }
+                    $breadcrumb[$key] = $crumb;
+                }
+                $param = implode('/', $breadcrumb);
+
+                // Remove multiple current path (./././) and multiple slashes (///).
+                $param = preg_replace('~//+~', '/', $param);
+                $param = preg_replace('~/(\./)+~', '/', $param);
+                return $param;
+
+            case PARAM_HOST:
+                // Allow FQDN or IPv4 dotted quad.
+                $param = preg_replace('/[^\.\d\w-]/', '', $param );
+                // Match ipv4 dotted quad.
+                if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
+                    // Confirm values are ok.
+                    if ( $match[0] > 255
+                        || $match[1] > 255
+                        || $match[3] > 255
+                        || $match[4] > 255 ) {
+                        // Hmmm, what kind of dotted quad is this?
+                        $param = '';
+                    }
+                } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
+                    && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
+                    && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
+                ) {
+                    // All is ok - $param is respected.
+                } else {
+                    // All is not ok...
+                    $param='';
+                }
+                return $param;
+
+            case PARAM_URL:          // Allow safe ftp, http, mailto urls.
+                $param = fix_utf8($param);
+                if (!empty($param) && self::validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
+                    // All is ok, param is respected.
+                } else {
+                    // Not really ok.
+                    $param ='';
+                }
+                return $param;
+
+
+            case PARAM_PEM:
+                $param = trim($param);
+                // PEM formatted strings may contain letters/numbers and the symbols:
+                //   forward slash: /
+                //   plus sign:     +
+                //   equal sign:    =
+                //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
+                if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
+                    list($wholething, $body) = $matches;
+                    unset($wholething, $matches);
+                    $b64 = clean_param($body, PARAM_BASE64);
+                    if (!empty($b64)) {
+                        return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
+                    } else {
+                        return '';
+                    }
+                }
+                return '';
+
+            case PARAM_BASE64:
+                if (!empty($param)) {
+                    // PEM formatted strings may contain letters/numbers and the symbols
+                    //   forward slash: /
+                    //   plus sign:     +
+                    //   equal sign:    =.
+                    if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
+                        return '';
+                    }
+                    $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
+                    // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
+                    // than (or equal to) 64 characters long.
+                    for ($i=0, $j=count($lines); $i < $j; $i++) {
+                        if ($i + 1 == $j) {
+                            if (64 < strlen($lines[$i])) {
+                                return '';
+                            }
+                            continue;
+                        }
+
+                        if (64 != strlen($lines[$i])) {
+                            return '';
+                        }
+                    }
+                    return implode("\n", $lines);
+                } else {
+                    return '';
+                }
+
+            case PARAM_TAGLIST:
+                $param = fix_utf8($param);
+                $tags = explode(',', $param);
+                $result = array();
+                foreach ($tags as $tag) {
+                    $res = clean_param($tag, PARAM_TAG);
+                    if ($res !== '') {
+                        $result[] = $res;
+                    }
+                }
+                if ($result) {
+                    return implode(',', $result);
+                } else {
+                    return '';
+                }
+
+
+
+
+
+
+
+
+
+            case PARAM_USERNAME:
+                $param = fix_utf8($param);
+                $param = trim($param);
+                // Convert uppercase to lowercase MDL-16919.
+                $param = core_text::strtolower($param);
+                if (empty($CFG->extendedusernamechars)) {
+                    $param = str_replace(" " , "", $param);
+                    // Regular expression, eliminate all chars EXCEPT:
+                    // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
+                    $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
+                }
+                return $param;
+
+            case PARAM_EMAIL:
+                $param = fix_utf8($param);
+                if (validate_email($param)) {
+                    return $param;
+                } else {
+                    return '';
+                }
+
+            case PARAM_STRINGID:
+                if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
+                    return $param;
+                } else {
+                    return '';
+                }
+
+            case PARAM_TIMEZONE:
+                // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
+                $param = fix_utf8($param);
+                $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
+                if (preg_match($timezonepattern, $param)) {
+                    return $param;
+                } else {
+                    return '';
+                }
+
+            default:
+                // Doh! throw error, switched parameters in optional_param or another serious problem.
+                print_error("unknownparamtype", '', '', $type);
+        }
+    }
+
+    function fix_utf8($value) {
+        if (is_null($value) or $value === '') {
+            return $value;
+
+        } else if (is_string($value)) {
+            if ((string)(int)$value === $value) {
+                // Shortcut.
+                return $value;
+            }
+            // No null bytes expected in our data, so let's remove it.
+            $value = str_replace("\0", '', $value);
+
+            // Note: this duplicates min_fix_utf8() intentionally.
+            static $buggyiconv = null;
+            if ($buggyiconv === null) {
+                $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
+            }
+
+            if ($buggyiconv) {
+                if (function_exists('mb_convert_encoding')) {
+                    $subst = mb_substitute_character();
+                    mb_substitute_character('');
+                    $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
+                    mb_substitute_character($subst);
+
+                } else {
+                    // Warn admins on admin/index.php page.
+                    $result = $value;
+                }
+
+            } else {
+                $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
+            }
+
+            return $result;
+
+        } else if (is_array($value)) {
+            foreach ($value as $k => $v) {
+                $value[$k] = fix_utf8($v);
+            }
+            return $value;
+
+        } else if (is_object($value)) {
+            // Do not modify original.
+            $value = clone($value);
+            foreach ($value as $k => $v) {
+                $value->$k = fix_utf8($v);
+            }
+            return $value;
+
+        } else {
+            // This is some other type, no utf-8 here.
+            return $value;
+        }
+    }
+
+    /**
+     * Validations
+     * @param $urladdr
+     * @param string $options
+     * @return bool
+     */
+
+    function validateUrlSyntax( $urladdr, $options="" ){
+
+        // Force Options parameter to be lower case
+        // DISABLED PERMAMENTLY - OK to remove from code
+        //    $options = strtolower($options);
+
+        // Check Options Parameter
+        if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
+        {
+            trigger_error("Options attribute malformed", E_USER_ERROR);
+        }
+
+        // Set Options Array, set defaults if options are not specified
+        // Scheme
+        if (strpos( $options, 's') === false) $aOptions['s'] = '?';
+        else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
+        // http://
+        if (strpos( $options, 'H') === false) $aOptions['H'] = '?';
+        else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
+        // https:// (SSL)
+        if (strpos( $options, 'S') === false) $aOptions['S'] = '?';
+        else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
+        // mailto: (email)
+        if (strpos( $options, 'E') === false) $aOptions['E'] = '-';
+        else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
+        // ftp://
+        if (strpos( $options, 'F') === false) $aOptions['F'] = '-';
+        else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
+        // User section
+        if (strpos( $options, 'u') === false) $aOptions['u'] = '?';
+        else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
+        // Password in user section
+        if (strpos( $options, 'P') === false) $aOptions['P'] = '?';
+        else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
+        // Address Section
+        if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
+        else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
+        // IP Address in address section
+        if (strpos( $options, 'I') === false) $aOptions['I'] = '?';
+        else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
+        // Port number
+        if (strpos( $options, 'p') === false) $aOptions['p'] = '?';
+        else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
+        // File Path
+        if (strpos( $options, 'f') === false) $aOptions['f'] = '?';
+        else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
+        // Query Section
+        if (strpos( $options, 'q') === false) $aOptions['q'] = '?';
+        else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
+        // Fragment (Anchor)
+        if (strpos( $options, 'r') === false) $aOptions['r'] = '?';
+        else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
+
+
+        // Loop through options array, to search for and replace "-" to "{0}" and "+" to ""
+        foreach($aOptions as $key => $value)
+        {
+            if ($value == '-')
+            {
+                $aOptions[$key] = '{0}';
+            }
+            if ($value == '+')
+            {
+                $aOptions[$key] = '';
+            }
+        }
+
+        // DEBUGGING - Unescape following line to display to screen current option values
+        // echo '<pre>'; print_r($aOptions); echo '</pre>';
+
+
+        // Preset Allowed Characters
+        $alphanum    = '[a-zA-Z0-9]';  // Alpha Numeric
+        $unreserved  = '[a-zA-Z0-9_.!~*' . '\'' . '()-]';
+        $escaped     = '(%[0-9a-fA-F]{2})'; // Escape sequence - In Hex - %6d would be a 'm'
+        $reserved    = '[;/?:@&=+$,]'; // Special characters in the URI
+
+        // Beginning Regular Expression
+        // Scheme - Allows for 'http://', 'https://', 'mailto:', or 'ftp://'
+        $scheme            = '(';
+        if     ($aOptions['H'] === '') { $scheme .= 'http://'; }
+        elseif ($aOptions['S'] === '') { $scheme .= 'https://'; }
+        elseif ($aOptions['E'] === '') { $scheme .= 'mailto:'; }
+        elseif ($aOptions['F'] === '') { $scheme .= 'ftp://'; }
+        else
+        {
+            if ($aOptions['H'] === '?') { $scheme .= '|(http://)'; }
+            if ($aOptions['S'] === '?') { $scheme .= '|(https://)'; }
+            if ($aOptions['E'] === '?') { $scheme .= '|(mailto:)'; }
+            if ($aOptions['F'] === '?') { $scheme .= '|(ftp://)'; }
+            $scheme = str_replace('(|', '(', $scheme); // fix first pipe
+        }
+        $scheme            .= ')' . $aOptions['s'];
+        // End setting scheme
+
+        // User Info - Allows for 'username@' or 'username:password@'. Note: contrary to rfc, I removed ':' from username section, allowing it only in password.
+        //   /---------------- Username -----------------------\  /-------------------------------- Password ------------------------------\
+        $userinfo          = '((' . $unreserved . '|' . $escaped . '|[;&=+$,]' . ')+(:(' . $unreserved . '|' . $escaped . '|[;:&=+$,]' . ')+)' . $aOptions['P'] . '@)' . $aOptions['u'];
+
+        // IP ADDRESS - Allows 0.0.0.0 to 255.255.255.255
+        $ipaddress         = '((((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9]))\.){3}((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9])))';
+
+        // Tertiary Domain(s) - Optional - Multi - Although some sites may use other characters, the RFC says tertiary domains have the same naming restrictions as second level domains
+        $domain_tertiary   = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)*';
+
+        /* MDL-9295 - take out domain_secondary here and below, so that URLs like http://localhost/ and lan addresses like http://host/ are accepted.
+                               // Second Level Domain - Required - First and last characters must be Alpha-numeric. Hyphens are allowed inside.
+            $domain_secondary  = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)';
+        */
+
+// we want more relaxed URLs in Moodle: MDL-11462
+        // Top Level Domain - First character must be Alpha. Last character must be AlphaNumeric. Hyphens are allowed inside.
+        $domain_toplevel   = '([a-zA-Z](([a-zA-Z0-9-]*)[a-zA-Z0-9])?)';
+        /*                       // Top Level Domain - Required - Domain List Current As Of December 2004. Use above escaped line to be forgiving of possible future TLD's
+            $domain_toplevel   = '(aero|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|post|pro|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ax|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)';
+        */
+
+        // Address can be IP address or Domain
+        if ($aOptions['I'] === '{0}') {       // IP Address Not Allowed
+            $address       = '(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . ')';
+        } elseif ($aOptions['I'] === '') {  // IP Address Required
+            $address       = '(' . $ipaddress . ')';
+        } else {                            // IP Address Optional
+            $address       = '((' . $ipaddress . ')|(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . '))';
+        }
+        $address = $address . $aOptions['a'];
+
+        // Port Number - :80 or :8080 or :65534 Allows range of :0 to :65535
+        //    (0-59999)         |(60000-64999)   |(65000-65499)    |(65500-65529)  |(65530-65535)
+        $port_number       = '(:(([0-5]?[0-9]{1,4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5])))' . $aOptions['p'];
+
+        // Path - Can be as simple as '/' or have multiple folders and filenames
+        $path              = '(/((;)?(' . $unreserved . '|' . $escaped . '|' . '[:@&=+$,]' . ')+(/)?)*)' . $aOptions['f'];
+
+        // Query Section - Accepts ?var1=value1&var2=value2 or ?2393,1221 and much more
+        $querystring       = '(\?(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['q'];
+
+        // Fragment Section - Accepts anchors such as #top
+        $fragment          = '(\#(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['r'];
+
+
+        // Building Regular Expression
+        $regexp = '#^' . $scheme . $userinfo . $address . $port_number . $path . $querystring . $fragment . '$#i';
+
+        // DEBUGGING - Uncomment Line Below To Display The Regular Expression Built
+        // echo '<pre>' . htmlentities(wordwrap($regexp,70,"\n",1)) . '</pre>';
+
+        // Running the regular expression
+        if (preg_match( $regexp, $urladdr ))
+        {
+            return true; // The domain passed
+        }
+        else
+        {
+            return false; // The domain didn't pass the expression
+        }
+
+    }
+
+    function validateEmailSyntax( $emailaddr, $options="" ){
+
+        // Check Options Parameter
+        if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
+        {
+            trigger_error("Options attribute malformed", E_USER_ERROR);
+        }
+
+        // Set Options Array, set defaults if options are not specified
+        // Scheme
+        if (strpos( $options, 's') === false) $aOptions['s'] = '-';
+        else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
+        // http://
+        if (strpos( $options, 'H') === false) $aOptions['H'] = '-';
+        else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
+        // https:// (SSL)
+        if (strpos( $options, 'S') === false) $aOptions['S'] = '-';
+        else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
+        // mailto: (email)
+        if (strpos( $options, 'E') === false) $aOptions['E'] = '?';
+        else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
+        // ftp://
+        if (strpos( $options, 'F') === false) $aOptions['F'] = '-';
+        else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
+        // User section
+        if (strpos( $options, 'u') === false) $aOptions['u'] = '+';
+        else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
+        // Password in user section
+        if (strpos( $options, 'P') === false) $aOptions['P'] = '-';
+        else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
+        // Address Section
+        if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
+        else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
+        // IP Address in address section
+        if (strpos( $options, 'I') === false) $aOptions['I'] = '-';
+        else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
+        // Port number
+        if (strpos( $options, 'p') === false) $aOptions['p'] = '-';
+        else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
+        // File Path
+        if (strpos( $options, 'f') === false) $aOptions['f'] = '-';
+        else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
+        // Query Section
+        if (strpos( $options, 'q') === false) $aOptions['q'] = '-';
+        else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
+        // Fragment (Anchor)
+        if (strpos( $options, 'r') === false) $aOptions['r'] = '-';
+        else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
+
+        // Generate options
+        $newoptions = '';
+        foreach($aOptions as $key => $value)
+        {
+            $newoptions .= $key . $value;
+        }
+
+        // DEBUGGING - Uncomment line below to display generated options
+        // echo '<pre>' . $newoptions . '</pre>';
+
+        // Send to validateUrlSyntax() and return result
+        return validateUrlSyntax( $emailaddr, $newoptions);
+
+    }
+
+    function validateFtpSyntax( $ftpaddr, $options="" ){
+
+        // Check Options Parameter
+        if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
+        {
+            trigger_error("Options attribute malformed", E_USER_ERROR);
+        }
+
+        // Set Options Array, set defaults if options are not specified
+        // Scheme
+        if (strpos( $options, 's') === false) $aOptions['s'] = '?';
+        else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
+        // http://
+        if (strpos( $options, 'H') === false) $aOptions['H'] = '-';
+        else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
+        // https:// (SSL)
+        if (strpos( $options, 'S') === false) $aOptions['S'] = '-';
+        else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
+        // mailto: (email)
+        if (strpos( $options, 'E') === false) $aOptions['E'] = '-';
+        else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
+        // ftp://
+        if (strpos( $options, 'F') === false) $aOptions['F'] = '+';
+        else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
+        // User section
+        if (strpos( $options, 'u') === false) $aOptions['u'] = '?';
+        else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
+        // Password in user section
+        if (strpos( $options, 'P') === false) $aOptions['P'] = '?';
+        else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
+        // Address Section
+        if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
+        else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
+        // IP Address in address section
+        if (strpos( $options, 'I') === false) $aOptions['I'] = '?';
+        else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
+        // Port number
+        if (strpos( $options, 'p') === false) $aOptions['p'] = '?';
+        else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
+        // File Path
+        if (strpos( $options, 'f') === false) $aOptions['f'] = '?';
+        else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
+        // Query Section
+        if (strpos( $options, 'q') === false) $aOptions['q'] = '-';
+        else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
+        // Fragment (Anchor)
+        if (strpos( $options, 'r') === false) $aOptions['r'] = '-';
+        else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
+
+        // Generate options
+        $newoptions = '';
+        foreach($aOptions as $key => $value)
+        {
+            $newoptions .= $key . $value;
+        }
+
+        // DEBUGGING - Uncomment line below to display generated options
+        // echo '<pre>' . $newoptions . '</pre>';
+
+        // Send to validateUrlSyntax() and return result
+        return validateUrlSyntax( $ftpaddr, $newoptions);
+
+    }
+
+
+}

+ 129 - 0
src/RequestResponse/Response.php

@@ -0,0 +1,129 @@
+<?php
+namespace RequestResponse;
+
+/*
+ *
+ *
+ */
+class Response{
+
+    private static $_instance;
+
+    /*
+     *
+     */
+    public $_headers = Array();
+
+    /*
+     *
+     */
+    public $_body = Array();
+
+    /*
+     *
+     */
+    public $_code = 200;
+
+    //SINGLETON==============================================
+
+    private function __construct(){
+    }
+
+    private static function newObj(){
+        if (!isset( self::$_instance )) {
+            self::$_instance = new Response();
+        }
+        return self::$_instance;
+    }
+
+    public function getInstance(){
+        if (!isset(self::$_instance)) {
+            return self::newObj();
+        }
+        return self::$_instance;
+    }
+
+    //=======================================================
+
+    public static function header($key, $value){
+        $istance = self::getInstance();
+        $istance->_headers[$key] = $value;
+        return $istance;
+    }
+
+    public static function body_prepend($body = null){
+        $instance = self::getInstance();
+        if (null !== $body) {
+            $instance->_body = (string) $body . $instance->_body;
+            return $instance;
+        }
+        return $instance;
+    }
+
+    public static function body($body = null){
+        $instance = self::getInstance();
+        if (null !== $body) {
+            $instance->_body = (string) $body;
+            return $instance;
+        }
+        return $instance;
+    }
+
+    public static function body_append($body = null){
+        $instance = self::getInstance();
+        if (null !== $body) {
+            $instance->_body .= (string) $body;
+            return $instance;
+        }
+        return $instance;
+    }
+
+    private function send_headers(){
+        foreach ($this->_headers as $key => $value) {
+            header($key .': '. $value, false);
+        }
+        return $this;
+    }
+
+    private function send_body(){
+        echo (string) $this->_body;
+        return $this;
+    }
+
+    public static function send(){
+        $instance = self::getInstance();
+        $instance->send_headers();
+        $instance->send_body();
+        return $instance;
+    }
+
+    public static function json($object, $jsonp_prefix = null){
+        $instance = self::getInstance();
+
+        $instance->body('');
+
+        $json = json_encode($object);
+        if (null !== $jsonp_prefix) {
+            $instance->header('Content-Type', 'text/javascript');
+            $instance->body("$jsonp_prefix($json);");
+        } else {
+            $instance->header('Content-Type', 'application/json');
+            $instance->body($json);
+        }
+        return $instance;
+    }
+
+    public static function redirect($url, $code = 302){
+        $instance = self::getInstance();
+
+        $instance->_code = $code;
+        $instance->header('Location', $url);
+
+        $instance->body('');
+        $instance->send();
+    }
+
+    function done(){
+        die;
+    }
+}