/** * Load details from configuration file and initialize * driver class */ public function initialize() { Event::fire("framework.session.initialize.before", array($this->_driver, $this->_options)); if (!$this->_driver) { $config = Configuration::get('session'); $this->driver = $config['driver']; unset($config['driver']); $this->options = $config; } if (!$this->_driver) { throw new \Exception("Invalid driver", 500); } Event::fire("framework.session.initialize.after", array($this->_driver, $this->_options)); switch ($this->_driver) { case 'server': return new Session\Driver\Server($this->_options); break; case 'file': return new Session\Driver\File($this->_options); break; default: throw new \Exception("Invalid driver", 500); break; } }
/** * Use the new resolving mechanism to call for local services. */ static function call($service, $method, $parameters = array(), $options = array()) { $hostname = System::getHostname('service'); if (!$hostname) { throw new ServiceException('Service hostname undefined.'); } if (is_string($options)) { $options = array('method' => $options); } if (isset($options['type']) && empty($options['method'])) { $options['method'] = $options['type']; } $options = (array) $options + self::$defaultOptions; $prefix = conf::get('web::resolvers.service.prefix', '/service'); $options['uri'] = array('scheme' => (bool) @$options['secure'] ? 'https' : 'http', 'host' => $hostname, 'path' => "{$prefix}/{$service}/{$method}/" . implode('/', array_map('urlencode', (array) $parameters))); unset($prefix); // Customizable Resolver if (@$options['resolver'] instanceof Resolver) { $serviceResolver = $options['resolver']; } else { $serviceResolver = Resolver::getActiveInstance(); } unset($options['resolver']); if (@$options['response'] instanceof Response) { $serviceResponse = $options['response']; } else { $serviceResponse = new Response(); } unset($options['response']); $serviceRequest = new Request($options); // Explicitly force this request to be local. $serviceRequest->__local = true; return $serviceRequest->send($serviceResolver, $serviceResponse); }
public function initialize() { Event::fire("framework.cache.initialize.before", array($this->_driver, $this->_options)); if (!$this->_driver) { $config = Configuration::get("cache"); $this->driver = $config['default']; $this->options = Configuration::get("cache.settings." . $this->_driver); } if (!$this->_driver) { throw new \Exception("Invalid type", 500); } Event::fire("framework.cache,.initializ.after", array($this->_driver, $this->_options)); switch ($this->_driver) { case "file": return new Cache\Driver\File($this->_options); break; case "memcached": return new Cache\Driver\Memcached($this->_options); break; case "wincache": return new Cache\Driver\Wincache($this->_options); break; default: throw new Exception("Ivalid type", 500); } }
public function all() { $sql = $this->_buildSelect(); list($statement, $result) = $this->connector->execute($sql, $this->bindings); if (!$result) { $error = $this->connector->lastError; throw new \Exception("There was an error with your SQL query: {$error}"); } $fetchStyle = Configuration::get('database.fetch'); return $this->connector->fetch($statement, $fetchStyle); }
/** * Create a new database connector instance using configuration * defined in application/configuration/Database * @return Database\Connectors\Connector */ public static function connection($type = null) { Event::fire("framework.database.connect.before", array($type)); if (is_null($type)) { $type = Configuration::get('database.default'); } if (!isset(static::$_connections[$type])) { $options = Configuration::get('database.connections.' . $type); if (is_null($options)) { throw new \Exception("Database connection is not defined for " . $type, 500); } static::$_connections[$type] = new Connection(static::connect($options), $type); } Event::fire("framework.database.connect.after", array($type)); return static::$_connections[$type]; }
public function schema($type = 'data') { switch ($type) { case 'form': $default = array('*'); break; default: $default = null; break; } $ret = conf::get("{$this->collectionName()}.model::{$type}", $default); if (!$ret) { $this->__response->status(404); } return $ret; }
/** * Get a MustacheResource object in the context with current server configurations. */ static function getResourceContext($locale = null) { static $resource; if ($resource) { return $resource; } $localeChain = Configuration::get('core.i18n::localeChain'); if (!$localeChain) { $localeChain = ['en_US']; } if ($locale) { array_unshift($localeChain, $locale); $localeChain = array_unique($localeChain); } $resource = new MustacheResource($localeChain); return $resource; }
<?php /*! HeadlessWorker.php | Takes care of headless process ahead. */ require_once '.private/scripts/Initialize.php'; use core\Database; use core\Log; use framework\Bayeux; use framework\Configuration as conf; use framework\Service; use models\WorkInstance; use models\TaskInstance; $taskInstance = new TaskInstance(); // Consumes Headless tasks ahead. $tasks = Database::fetchArray('SELECT `nextTask` FROM `WorkInstance` WHERE `nextTask` IN (SELECT `uuid` FROM `TaskInstance` WHERE `type` = \'Headless\') AND `state` = \'Open\';'); $tasks = array_map(compose('core\\Utility::unpackUuid', prop('nextTask')), $tasks); if ($tasks) { Log::debug(sprintf('%d headless tasks found!', count($tasks)), $tasks); } $serviceOptions = array('resolver' => new framework\Resolver()); $serviceOptions['resolver']->registerResolver(new resolvers\WebServiceResolver(array('prefix' => conf::get('web::resolvers.service.prefix', '/service')))); foreach ($tasks as $taskUuid) { // renew response object for each call $serviceOptions['response'] = new framework\Response(array('autoOutput' => false)); Service::call('_/WorkInstance', 'process', array($taskUuid), $serviceOptions); // todo: send bayeux update message to notify related users about the task update. }
/*! environment.php | Perform base functionality check, terminate the script if any of these doesn't presence. */ use core\Utility; use framework\Configuration as conf; use framework\System; //-------------------------------------------------- // // Environment definitions // //-------------------------------------------------- // CRYPT_SHA512 if (!constant('CRYPT_SHA512')) { throw new Exception('CRYPT_SHA512 method is not supported, please enable it on your system.'); } // Sets default Timezone, defaults to development locale (Hong Kong). date_default_timezone_set(conf::get('system.locale::timezone', 'Asia/Hong_Kong')); // Allow more nesting for functional programming. ini_set('xdebug.max_nesting_level', 1000); if (constant('PHP_SAPI') == 'cli') { // Turn on garbage collection gc_enable(); } else { // Starts HTTP session for browsers. session_start(); } //-------------------------------------------------- // // Compatibility // //-------------------------------------------------- if (!function_exists('curl_file_create')) {
// // Logger initialization // //------------------------------------------------------------------------------ /*! Note @ 7 Aug, 2015 * Here we started to make use of the Psr\Log interface and Seldaek\Monolog, * digging the original Log class empty as a wrapper to LoggerInterface, and * moved the backtrace and session info into separate processors in monolog. * * Specifically, backtrace context like file, subject and action are moved to * the BacktraceProcessor class, while session info is moved to the * SessionProcessor class. * * Node::set() invoke is migrated into NodeHandler class. */ Log::setLogger(new Logger('default')); // Log enabled if (conf::get('system::log.enabled', true)) { $level = Logger::toMonologLevel(conf::get('system::log.level', 'debug')); Log::getLogger()->pushProcessor(new BacktraceProcessor($level))->pushProcessor(new SessionProcessor($level))->pushProcessor(new ProcessProcessor($level))->pushHandler(new NodeHandler($level)); unset($level); } else { // This should not be necessary, no handlers will run nothing. Log::getLogger()->pushHandler(new NullHandler()); } //------------------------------------------------------------------------------ // // System shims // //------------------------------------------------------------------------------ require_once __DIR__ . '/framework/environment.php';
// fork mimic } else { $pid = pcntl_fork(); } // parent: $forked == false // child: $forked == true $forked = $pid == 0; // unset($pid); // parent will die here if (!$forked) { exit(1); } // Avoid forking connection crash, renew the connection. Database::disconnect(); // Get maximum allowed connections before table lock. $capLimit = (int) @conf::get('system::crontab.process_limit'); if (!$capLimit) { $capLimit = Process::MAXIMUM_CAPACITY; } // Start transaction before lock tables. Database::beginTransaction(); // Pick next awaiting process Database::locKTables([FRAMEWORK_COLLECTION_PROCESS . ' READ']); $res = (int) Database::fetchField('SELECT IFNULL(SUM(`capacity`), 0) as occupation FROM `' . FRAMEWORK_COLLECTION_PROCESS . '` WHERE `pid` IS NOT NULL AND `pid` > 0'); Database::unlockTables(true); if ($res >= $capLimit) { Log::debug('Active processes has occupied maximum server capacity, daemon exits.'); Database::rollback(); die;
$resolver->registerResolver(new resolvers\ExternalResolver(array('source' => conf::get('system::paths.external.src'))), 40); // Markdown handling $resolver->registerResolver(new resolvers\MarkdownResolver(), 30); // SCSS Compiler $resolver->registerResolver(new resolvers\ScssResolver(array('source' => conf::get('system::paths.scss.src'), 'output' => conf::get('system::paths.scss.dst', 'assets/css'))), 30); // LESS Compiler $resolver->registerResolver(new resolvers\LessResolver(array('source' => conf::get('system::paths.less.src'), 'output' => conf::get('system::paths.less.dst', 'assets/css'))), 30); // Css Minifier $resolver->registerResolver(new resolvers\CssMinResolver(array('source' => conf::get('system::paths.cssmin.src'), 'output' => conf::get('system::paths.cssmin.dst', 'assets/css'))), 20); // Js Minifier $resolver->registerResolver(new resolvers\JsMinResolver(array('source' => conf::get('system::paths.jsmin.src'), 'output' => conf::get('system::paths.jsmin.dst', 'assets/js'))), 20); // Physical file handling $fileResolver = array('directoryIndex' => conf::get('web::resolvers.file.indexes', 'Home index')); if (conf::get('web::http.output.buffer.enable')) { $fileResolver['outputBuffer']['size'] = conf::get('web::http.output.buffer.size', 1024); } $fileResolver = new resolvers\FileResolver($fileResolver); $resolver->registerResolver($fileResolver, 10); unset($fileResolver); // HTTP error pages in HTML or JSON $resolver->registerResolver(new resolvers\StatusDocumentResolver(array('prefix' => conf::get('web::resolvers.errordocs.directory'))), 5); // Logging $resolver->registerResolver(new resolvers\LogResolver(), 0); // Request context // We have no request context options currently, use defaults. // Response context if (conf::get('web::http.output.buffer.enable')) { $response = new framework\Response(array('outputBuffer' => array('size' => conf::get('web::http.output.buffer.size', 1024)))); } // Start the application $resolver->run(@$request, @$response);
/** * Hash a given string * @param string $value Value to be hashed * @return string */ protected function hash($value) { return hash_hmac('sha1', $value, Configuration::get('application.key')); }
/** * Run a select statement against the database. * @param string $query * @param array $bindings * @return array */ public function select($query, $bindings = array()) { list($statement, $result) = $this->execute($query, $bindings); if (!$result) { $error = oci_error(); throw new \Exception("There was an error with your SQL query: {$error}"); } $fetchStyle = Configuration::get('database.fetch'); return $this->fetch($statement, $fetchStyle); }
/** * Determine the proper error message for a give field or rule * @param string $field The field being validated * @param string $rule The rule being applied to the field * @return string The correct error message for the attribute/rule */ protected function message($field, $rule) { // Check for an attribute specific message $custom = $field . "_" . $rule; if (array_key_exists($custom, $this->_messages)) { return $this->_messages[$custom]; } else { if (Configuration::get("validation." . $custom)) { return Configuration::get("validation." . $custom); } } // Check for a rule specific message if (array_key_exists($rule, $this->_messages)) { return $this->_messages[$rule]; } // Resort to application wide config validation messages return Configuration::get("validation." . $rule); }
/** * Bootstrap system autoloading. */ public static function bootstrap() { if (function_exists('spl_autoload_register')) { spl_autoload_register(array(__CLASS__, '__autoload')); } // Make sure working directory the same as gateway.php @chdir(self::getPathname()); $prefixes = (array) conf::get('system::paths.autoload'); if ($prefixes) { self::$pathPrefixes = $prefixes; } // additional files foreach ((array) @conf::get('system::paths.requires') as $file) { require_once $file; } foreach ((array) @conf::get('system::paths.includes') as $file) { include_once $file; } }