Пример #1
0
 /**
  * Get a list of data models from the collection.
  */
 function find(array $filter = array())
 {
     if ($filter && !util::isAssoc($filter)) {
         $filter = array($this->_primaryKey => $filter);
     }
     $filter[Node::FIELD_COLLECTION] = self::collectionName();
     $collection = array();
     Node::getAsync($filter, function ($data) use(&$collection) {
         // create a new instance for retrieved data
         $model = get_called_class();
         $model = new $model($data);
         if (isset($this->__request)) {
             $model->__request = $this->__request;
         }
         if (isset($this->__response)) {
             $model->__response = $this->__response;
         }
         // force invoke internal function
         util::forceInvoke(array($model, 'afterLoad'));
         // add if model still has data
         if ($model->data()) {
             $collection[] = $model;
         }
     });
     return $collection;
 }
Пример #2
0
 private static function walkArray($node, &$writer, $ns = NULL, $currentNode = NULL)
 {
     $ns = (array) $ns;
     // Text value
     if (!is_array($node)) {
         if (strlen($node) > self::CDATA_THRESHOLD) {
             $writer->writeCData($node);
         } else {
             $writer->text($node);
         }
         return;
     }
     $nodeStarted = FALSE;
     if ($currentNode !== NULL) {
         //------------------------------
         //  startElement()
         //------------------------------
         // 1. Metadata exists
         // 2. Not numeric array
         if (Utility::isAssoc($node)) {
             self::startElement($currentNode, $writer, $ns);
             //------------------------------
             //  Metadata
             //-----------------------------
             // @attributes
             if (isset($node['@attributes'])) {
                 foreach ($node['@attributes'] as $key => $value) {
                     if (preg_match('/^(xmlns\\:?)(.*)$/', $key, $matches)) {
                         $ns[$matches[2]] = $value;
                     }
                     $key = explode(':', $key);
                     if (count($key) == 2) {
                         $writer->writeAttributeNS($key[0], $key[1], $ns[$key[0]], $value);
                     } else {
                         $writer->writeAttribute($key[0], $value);
                     }
                 }
                 unset($node['@attributes']);
             }
             // @comments
             if (isset($node['@comments'])) {
                 foreach ((array) $node['@comments'] as $value) {
                     $writer->writeComment($value);
                 }
                 unset($node['@comments']);
             }
             $nodeStarted = TRUE;
         }
     }
     if (isset($node['@value'])) {
         $node = (array) $node['@value'];
     }
     //------------------------------
     //  Children
     //------------------------------
     if (Utility::isAssoc($node)) {
         foreach ($node as $key => $value) {
             if (!is_array($value)) {
                 self::writeElement($key, $writer, $ns, $value);
             } else {
                 self::walkArray($value, $writer, $ns, $key);
             }
         }
     } else {
         foreach ($node as $value) {
             if (!$nodeStarted && !is_array($value)) {
                 self::writeElement($currentNode, $writer, $ns, $value);
             } else {
                 self::walkArray($value, $writer, $ns, $currentNode);
             }
         }
     }
     if ($nodeStarted) {
         $writer->endElement();
     }
 }
Пример #3
0
 /**
  * @constructor
  *
  * @param {?string|array} $options An array of request options, or the URI string.
  * @param {?string} $options['prefix'] Parameters keys start with this prefix
  *                                     will be treated as meta-parameters and
  *                                     not returned in param() related functions.
  *
  *                                     Parameters values start with this prefix
  *                                     will be tried to parsed as constants and
  *                                     booleans.
  *
  *                                     This defaults to the "@" character.
  *
  * @param {?string} $options['uri'] The request uri, defaults to $_SERVER['REQUEST_URI'].
  * @param {?string} $options['method'] Request method, defaults to $_SERVER['REQUEST_METHOD'].
  * @param {?array} $options['headers'] Request headers, defaults to the contents of getallhheaders()
  *                                     if the function is available.
  * @param {?array} $options['client'] Request client details, defaults to everything from $_SERVER.
  * @param {?array} $options['get'] GET parameters in array format.
  * @param {?array} $options['post'] POST parameters in array format.
  * @param {?array} $options['cookies'] COOKIES in array format.
  * @param {?array} $options['files'] Upload files along with this request. (Use with care)
  *                                   When doing CURL requests, files array must compatible with CURL.
  *                                   Otherwise this must obey the resolver-request format.
  * @param {?string} $options['locale'] Requesting locale, defaults to en_US.
  */
 public function __construct($options = array())
 {
     global $argv;
     if ($options instanceof Resolver) {
         $this->resolver = $options;
         $options = array();
     }
     if (@$options) {
         if (is_string($options)) {
             $options = array('uri' => $options);
         }
         // Special parameter prefix
         if (!empty($options['prefix'])) {
             $this->metaPrefix = $options['prefix'];
         }
         // Request URI
         if (empty($options['uri'])) {
             throw new FrameworkException('Request URI is required.');
         } else {
             $this->setUri($options['uri']);
         }
         // Request method
         if (isset($options['method'])) {
             $this->method = strtolower($options['method']);
         } else {
             $this->method = 'get';
         }
         // Request headers
         if (isset($options['headers'])) {
             $this->headers = (array) $options['headers'];
         }
         // Request client
         if (!empty($options['client'])) {
             $this->client = (array) $options['client'];
         }
         // Request parameters GET
         if (isset($options['get'])) {
             $this->paramCache['get'] = (array) $options['get'];
         }
         // Request parameters POST
         if (!empty($options['post'])) {
             $this->paramCache['post'] = (array) $options['post'];
         }
         // Cookies
         if (isset($options['cookies'])) {
             $this->paramCache['cookies'] = (array) $options['cookies'];
         }
         // File uploads
         if (isset($options['files'])) {
             $this->paramCache['files'] = (array) $options['files'];
         }
         // Request locale
         if (!empty($options['locale'])) {
             $this->locale = (string) $options['locale'];
         }
     } else {
         // Request client
         switch (constant('PHP_SAPI')) {
             case 'cli':
                 $this->client = array('type' => 'cli', 'host' => gethostname(), 'user' => get_current_user());
                 break;
             default:
                 $this->client = array_filter(array('type' => 'http', 'secure' => @$_SERVER['HTTPS'] && strtolower($_SERVER['HTTPS']) != 'off', 'address' => @$_SERVER['REMOTE_ADDR'], 'host' => @$_SERVER['REMOTE_HOST'], 'port' => @$_SERVER['REMOTE_PORT'], 'user' => @$_SERVER['REMOTE_USER'], 'referer' => @$_SERVER['HTTP_REFERER'], 'version' => @$_SERVER['SERVER_PROTOCOL'], 'userAgent' => @$_SERVER['HTTP_USER_AGENT'], 'forwarder' => @$_SERVER['HTTP_X_FORWARDED_FOR'], 'isAjax' => strtolower(@$_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'), compose('not', 'is_null'));
                 break;
         }
         // Request method
         switch ($this->client('type')) {
             case 'cli':
                 $this->method = 'cli';
                 break;
             default:
                 $this->method = strtolower(@$_SERVER['REQUEST_METHOD']);
                 break;
         }
         // Request headers
         switch ($this->client('type')) {
             case 'cli':
                 break;
             default:
                 $this->headers = getallheaders();
                 break;
         }
         // Request parameters
         switch ($this->client('type')) {
             case 'cli':
                 $this->paramCache['cli'] = new Optimist();
                 break;
             default:
                 // Request parameters GET
                 $this->paramCache['get'] = $_GET;
                 // Request parameters POST
                 if (preg_match('/^application\\/json/', $this->header('Content-Type'))) {
                     $this->paramCache['post'] = ContentDecoder::json(file_get_contents('php://input'), true);
                 } else {
                     $this->paramCache['post'] = $_POST;
                 }
                 // Cookies
                 $this->paramCache['cookies'] =& $_COOKIE;
                 // File uploads
                 if ($this->method() == 'put') {
                     $this->paramCache['files'] = new RequestPutFile($this->header('Content-Type'));
                 } else {
                     util::filesFix();
                     $parseFile = function ($file) use(&$parseFile) {
                         if (!is_array($file)) {
                             return $file;
                         }
                         if (util::isAssoc($file)) {
                             switch ($file['error']) {
                                 case UPLOAD_ERR_OK:
                                     return new RequestPostFile($file);
                                 case UPLOAD_ERR_NO_FILE:
                                     // Skip it.
                                     break;
                                 default:
                                     return $file['error'];
                             }
                         } else {
                             return array_mapdef($file, $parseFile);
                         }
                     };
                     $this->paramCache['files'] = array_mapdef(array_filter_keys($_FILES, compose('not', startsWith('@'))), $parseFile);
                     unset($parseFile);
                 }
                 break;
         }
         // Request URI
         // CLI requires request parameters
         switch ($this->client('type')) {
             case 'cli':
                 /*! Note @ 9 May, 2015
                  *  Usage: node-cli [OPTIONS] COMMAND
                  *  Only one command is supported, simply shift it out.
                  */
                 $this->uri = @$this->paramCache['cli']['_'][0];
                 if (!$this->uri) {
                     $this->uri = $argv[1];
                 }
                 break;
             default:
                 $uri = array('scheme' => $this->client('secure') ? 'https' : 'http', 'user' => @$_SERVER['REMOTE_USER'], 'host' => @$_SERVER['SERVER_NAME'], 'port' => @$_SERVER['SERVER_PORT'], 'path' => @$_SERVER['REQUEST_URI'], 'query' => $_GET);
                 if (empty($uri['user'])) {
                     $uri['user'] = @$_SERVER['PHP_AUTH_USER'];
                 }
                 $this->setUri(array_filter($uri));
                 // = parse_url(http_build_url($this->uri));
                 break;
         }
         // Parse special parameter values
         array_walk_recursive($this->paramCache, function (&$value) {
             if (is_string($value) && strpos($value, $this->metaPrefix) === 0) {
                 $_value = substr($value, strlen($this->metaPrefix));
                 switch (strtolower($_value)) {
                     case 'true':
                         $value = true;
                         break;
                     case 'false':
                         $value = false;
                         break;
                     default:
                         if (defined($_value)) {
                             $value = constant($_value);
                         }
                         break;
                 }
             }
         });
         // Request timestamp
         $this->timestamp = (double) @$_SERVER['REQUEST_TIME_FLOAT'];
     }
     // Unified params ($_REQUEST mimic)
     switch ($this->client('type')) {
         case 'cli':
             // $this->paramCache['request'] = $this->paramCache['cli'];
             break;
         default:
             $this->paramCache['request'] = array_merge((array) @$this->paramCache['cookies'], (array) @$this->paramCache['get'], (array) @$this->paramCache['post']);
             break;
     }
     // Failover in case of request time not exists.
     if (!$this->timestamp) {
         $this->timestamp = microtime(1);
     }
 }
Пример #4
0
function invokes($name, array $args = array())
{
    return function ($object) use($name, $args) {
        if (Utility::isAssoc($object)) {
            $func = @$object[$name];
        } else {
            if (method_exists($object, $name)) {
                $func = array($object, $name);
            } else {
                if (isset($object->{$name}) && is_callable($object->{$name})) {
                    $func = $object->{$name};
                } else {
                    if (is_object($object)) {
                        $object = get_class($object);
                    }
                    if (is_array($object)) {
                        $object = 'input array';
                    }
                    trigger_error("No callable {$name}() found in {$object}.", E_USER_WARNING);
                    unset($object);
                }
            }
        }
        return call_user_func_array($func, $args);
    };
}
Пример #5
0
 public function resolve(Request $req, Response $res)
 {
     $auth = $this->paths;
     $pathNodes = trim($req->uri('path'), '/');
     if ($pathNodes) {
         $pathNodes = explode('/', $pathNodes);
     } else {
         $pathNodes = ['/'];
     }
     $lastWildcard = @$auth['*'];
     foreach ($pathNodes as $index => $pathNode) {
         if (!util::isAssoc($auth)) {
             break;
             // No more definitions, break out.
         }
         if (isset($auth['*'])) {
             $lastWildcard = $auth['*'];
         }
         if (isset($auth[$pathNode])) {
             $auth = $auth[$pathNode];
         } else {
             unset($auth);
             break;
         }
     }
     if (!isset($auth) || !is_bool($auth) && (!is_array($auth) || util::isAssoc($auth))) {
         if (empty($lastWildcard)) {
             throw new FrameworkException('Unable to resolve authentication chain from request URI.');
         } else {
             $auth = $lastWildcard;
         }
     }
     unset($pathNodes, $lastWildcard);
     // Numeric array
     if (is_array($auth) && !util::isAssoc($auth)) {
         $auth = array_reduce($auth, function ($result, $auth) use($req) {
             if (!$result) {
                 return $result;
             }
             if (is_callable($auth)) {
                 $auth = $auth($req);
             } else {
                 if (is_string($auth)) {
                     if (strpos($auth, '/') === false) {
                         $auth = "authenticators\\{$auth}";
                     }
                     if (is_a($auth, 'framework\\interfaces\\IAuthenticator', true)) {
                         $result = $result && $auth::authenticate($req);
                     } else {
                         throw new FrameworkException('Unknown authenticator type, must be ' . 'instance of IAuthenticator or callable.');
                     }
                 } else {
                     throw new FrameworkException('Unknown authenticator type, must be ' . 'instance of IAuthenticator or callable.');
                 }
             }
             return $result && $auth;
         }, true);
     }
     // Boolean
     if (is_bool($auth) && !$auth) {
         $res->status($this->statusCode);
     }
     // TODO: Mark allowed or denied according to the new resolver mechanism.
 }
Пример #6
0
 /**
  * Spawns a daemon worker, this is called automatically when the spawn options is true upon calling enqueue.
  */
 public static function spawnWorker($env = null)
 {
     $proc = array(['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']);
     if (!util::isAssoc($env)) {
         $env = null;
     }
     $proc = proc_open(self::EXEC_PATH, $proc, $pipes, getcwd(), $env, array('suppress_errors' => true, 'bypass_shell' => true));
     if ($proc === false) {
         return false;
     }
     $stat = proc_get_status($proc);
     return $stat['pid'];
 }