/** * Class constructor * * Setup Memcache(d) * * @return void */ public function __construct() { // Try to load memcached server info from the config file. $defaults = $this->_config['default']; $this->_config = Config::get('cache')->memcached; if (class_exists('Memcached', FALSE)) { $this->_memcached = new Memcached(); } elseif (class_exists('Memcache', FALSE)) { $this->_memcached = new Memcache(); } else { Logger::logError('Cache: Failed to create Memcache(d) object; extension not loaded?'); return; } foreach ($this->_config as $cache_server) { isset($cache_server['hostname']) or $cache_server['hostname'] = $defaults['host']; isset($cache_server['port']) or $cache_server['port'] = $defaults['port']; isset($cache_server['weight']) or $cache_server['weight'] = $defaults['weight']; if ($this->_memcached instanceof Memcache) { // Third parameter is persistance and defaults to TRUE. $this->_memcached->addServer($cache_server['hostname'], $cache_server['port'], TRUE, $cache_server['weight']); } elseif ($this->_memcached instanceof Memcached) { $this->_memcached->addServer($cache_server['hostname'], $cache_server['port'], $cache_server['weight']); } } }
/** * Load a helper. * * Supply the name and the helper will be loaded from the supplied directory, * or from one of the helperPaths (which you can add). * * @param string $helperName Name of the helper * @param string|null $directory Directory to load the helper from, will ignore $helperPaths * @return bool Whether the helper was succesfully loaded (true if yes) */ public function load($helperName, $directory = null) { // First determine the name of the helper $helperName = strtolower(str_replace(array('_helper', '.php'), '', $helperName) . '_helper'); // Determine what directories should be checked $directories = is_null($directory) ? $this->helperPaths : array($directory); // Check it is already loaded if (isset($this->helpers[$helperName])) { Logger::log("Helper '" . $helperName . "' is already loaded. Skipping"); return false; } // First check if there is an 'extension' class $extendedHelper = Config::get('main')->application_prefix . $helperName; $extendedHelperLoaded = false; foreach ($directories as $helperPath) { $file = $helperPath . DS . $extendedHelper . '.php'; if (file_exists($file)) { $extendedHelperLoaded = true; $extendedHelperFile = $file; } } // If an extension is loaded there needs to be a base helper if ($extendedHelperLoaded) { $baseHelper = Core::$coreDir . DS . 'Helpers' . DS . $helperName . '.php'; if (!file_exists($baseHelper)) { throw new HelperException("Could not load helper. Base Helper not found while Extension loaded", 1); } // Fire the associated event $event = Events::fireEvent('helperLoadEvent', $helperName, $baseHelper, $extendedHelper, $extendedHelperFile); if ($event->isCancelled()) { Logger::log("Not loading helper. Aborted by event"); return false; } include_once $event->extendedHelperFile; include_once $event->helperFile; $this->helpers[$event->helperName] = true; Logger::log("Loading base helper '" . $event->helperName . "' and extended helper '" . $event->extendedHelperName . "'"); return true; } // If no extension exists, try loading a regular helper foreach ($directories as $helperPath) { $file = $helperPath . DS . $helperName . '.php'; if (file_exists($file)) { // Fire the associated event $event = Events::fireEvent('helperLoadEvent', $helperName, $file); if ($event->isCancelled()) { Logger::log("Not loading helper. Aborted by event"); return false; } include_once $event->helperFile; $this->helpers[$event->helperName] = true; Logger::log("Loading helper '" . $event->helperName . "'"); return true; } } throw new HelperException("Could not load helper. Helper not found.", 1); }
/** * Load driver * * Separate load_driver call to support explicit driver load by library or user * * @param string Driver name (w/o parent prefix) * @return object Child class */ public function load_driver($child) { // Get the subclass prefix $prefix = Config::get('main')->application_prefix; if (!isset($this->lib_name)) { // Get library name without any prefix $this->lib_name = str_replace(array('FW_', $prefix), '{prefix}', get_class($this)); } // Sanitize the library name $clean_class = str_replace(array('Application\\Library\\', 'FuzeWorks\\Library\\', '{prefix}'), '', $this->lib_name); // The child will be prefixed with the parent lib $child_name = $this->lib_name . '_' . $child; // See if requested child is a valid driver if (!in_array($child, $this->valid_drivers)) { // The requested driver isn't valid! $msg = 'Invalid driver requested: ' . $child_name; throw new LibraryException($msg, 1); } // Get package paths and filename case variations to search $paths = Factory::getInstance()->libraries->getLibraryPaths(); // Is there an extension? $class_name = str_replace('{prefix}', $prefix, $child_name); $found = class_exists($class_name, FALSE); if (!$found) { // Check for subclass file foreach ($paths as $path) { // Does the file exist? $file = $path . DS . $clean_class . DS . 'drivers' . DS . $prefix . $clean_class . '_' . $child . '.php'; if (file_exists($file)) { // Yes - require base class from BASEPATH $basepath = Core::$coreDir . DS . 'Libraries' . DS . $clean_class . DS . 'drivers' . DS . $clean_class . '_' . $child . '.php'; if (!file_exists($basepath)) { $msg = 'Unable to load the requested class: FW_' . $child_name; throw new LibraryException($msg, 1); } // Include both sources and mark found include_once $basepath; include_once $file; $found = TRUE; break; } } } // Do we need to search for the class? if (!$found) { // Use standard class name $class_name = str_replace('{prefix}', 'FW_', $child_name); if (!class_exists($class_name, FALSE)) { // Check package paths foreach ($paths as $path) { // Does the file exist? $file = $path . DS . $clean_class . DS . 'drivers' . DS . $clean_class . '_' . $child . '.php'; if (file_exists($file)) { // Include source include_once $file; break; } } } } // Did we finally find the class? if (!class_exists($class_name, FALSE)) { if (class_exists($child_name, FALSE)) { $class_name = $child_name; } else { $msg = 'Unable to load the requested driver: ' . $class_name; throw new LibraryException($msg, 1); } } // Instantiate, decorate and add child $obj = new $class_name(); $obj->decorate($this); $this->{$child} = $obj; return $this->{$child}; }
/** * Initiates the Logger. * * Registers the error and exception handler, when required to do so by configuration */ public function __construct() { // Register the error handler, Untestable // @codeCoverageIgnoreStart if (Config::get('error')->error_reporting == true && self::$useTracy === false) { set_error_handler(array('\\FuzeWorks\\Logger', 'errorHandler'), E_ALL); set_Exception_handler(array('\\FuzeWorks\\Logger', 'exceptionHandler')); } // @codeCoverageIgnoreEnd error_reporting(false); self::$debug = ENVIRONMENT === 'DEVELOPMENT'; self::$log_to_file = Config::get('error')->log_to_file; self::$logger_template = Config::get('error')->logger_template; self::newLevel('Logger Initiated'); if (self::$useTracy) { LoggerTracyBridge::register(); } }
/** * Class constructor * * Setup Redis * * Loads Redis config file if present. Will halt execution * if a Redis connection can't be established. * * @return void * @see Redis::connect() */ public function __construct() { if (!$this->is_supported()) { Logger::logError('Cache: Failed to create Redis object; extension not loaded?'); return; } $config = array_merge(self::$_default_config, Config::get('cache')->redis); $this->_redis = new Redis(); try { if ($config['socket_type'] === 'unix') { $success = $this->_redis->connect($config['socket']); } else { $success = $this->_redis->connect($config['host'], $config['port'], $config['timeout']); } if (!$success) { Logger::logError('Cache: Redis connection failed. Check your configuration.'); } if (isset($config['password']) && !$this->_redis->auth($config['password'])) { Logger::logError('Cache: Redis authentication failed.'); } } catch (RedisException $e) { Logger::logError('Cache: Redis connection refused (' . $e->getMessage() . ')'); } // Initialize the index of serialized values. $serialized = $this->_redis->sMembers('_ci_redis_serialized'); empty($serialized) or $this->_serialized = array_flip($serialized); }
/** * Retrieve a language file and return the language array * * @param string $langfile * @param string $idiom * @param boolean $add_suffix * @param string $alt_path * @return type * @throws LanguageException */ public static function get($langfile, $idiom = '', $add_suffix = TRUE, $alt_path = '') { // First we determine the file that should be loaded $langfile = str_replace('.php', '', $langfile); if ($add_suffix === TRUE) { $langfile = preg_replace('/_lang$/', '', $langfile) . '_lang'; } $langfile .= '.php'; // Then we determine the idiom if (empty($idiom) or !preg_match('/^[a-z_-]+$/i', $idiom)) { $config = Config::get('main'); $idiom = empty($config->language) ? 'english' : $config->language; } // Is it already loaded? Return the entire language array if (isset(self::$is_loaded[$langfile]) && self::$is_loaded[$langfile] === $idiom) { return self::$language; } // Prepare the language variable $lang = array(); // Load the base file, so any others found can override it $basepath = Core::$coreDir . DS . 'Language' . DS . $idiom . DS . $langfile; if (($found = file_exists($basepath)) === TRUE) { $lang = array_merge($lang, (array) (include $basepath)); } // Do we have an alternative path to look in? if ($alt_path !== '') { $alt_path .= 'Language' . DS . $idiom . DS . $langfile; if (file_exists($alt_path)) { $lang = array_merge($lang, (array) (include $alt_path)); $found = TRUE; } } else { foreach (self::$languagePaths as $languagePath) { $languagePath .= DS . $idiom . DS . $langfile; if ($basepath !== $languagePath && file_exists($languagePath)) { $lang = array_merge($lang, (array) (include $languagePath)); $found = TRUE; break; } } } // If nothing is found, kill it if ($found !== TRUE) { throw new LanguageException('Unable to load the requested language file: language/' . $idiom . '/' . $langfile, 1); } // If only empty content is found, return the language array if (empty($lang)) { Logger::logError('Language file contains no data: language/' . $idiom . '/' . $langfile); return self::$language; } // Save the data and return it self::$is_loaded[$langfile] = $idiom; self::$language = array_merge(self::$language, $lang); Logger::log('Language file loaded: language/' . $idiom . '/' . $langfile); return self::$language; }
/** * Retrieve a template file using a string and a directory. * * What template file gets loaded depends on the template engine that is being used. * PHP for example uses .php files. Providing this function with 'home/dashboard' will load the home/view.dashboard.php file. * You can also provide no particular engine, and the manager will decide what template to load. * Remember that doing so will result in a LayoutException when multiple compatible files are found. * * @param string $file File to load * @param string $directory Directory to load it from * * @return string The output of the template * * @throws LayoutException On error */ public static function get($file, $directory = null) { $directory = is_null($directory) ? self::$directory : $directory; Logger::newLevel("Loading template file '" . $file . "' in '" . $directory . "'"); // First load the template engines self::loadTemplateEngines(); // First retrieve the filepath if (is_null(self::$current_engine)) { self::setFileFromString($file, $directory, array_keys(self::$file_extensions)); } else { self::setFileFromString($file, $directory, self::$current_engine->getFileExtensions()); } // Then assign some basic variables for the template self::$assigned_variables['wwwDir'] = Config::get('main')->base_url; self::$assigned_variables['siteURL'] = Config::get('main')->base_url; self::$assigned_variables['serverName'] = Config::get('main')->server_name; self::$assigned_variables['adminMail'] = Config::get('main')->administrator_mail; self::$assigned_variables['contact'] = Config::get('contact')->toArray(); // Select an engine if one is not already selected if (is_null(self::$current_engine)) { self::$current_engine = self::getEngineFromExtension(self::getExtensionFromFile(self::$file)); } self::$current_engine->setDirectory(self::$directory); // And run an Event to see what other parts have to say about it $event = Events::fireEvent('layoutLoadViewEvent', self::$file, self::$directory, self::$current_engine, self::$assigned_variables); // The event has been cancelled if ($event->isCancelled()) { return false; } // And refetch the data from the event self::$current_engine = $event->engine; self::$assigned_variables = $event->assigned_variables; Logger::stopLevel(); // And finally run it if (file_exists($event->file)) { return self::$current_engine->get($event->file, self::$assigned_variables); } throw new LayoutException('The requested file was not found', 1); }
/** * Class constructor * * @return void */ public function __construct() { $this->config = Config::get('routing'); // Determine the base_url if (empty(Config::get('main')->base_url)) { if (isset($_SERVER['SERVER_ADDR'])) { if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE) { $server_addr = '[' . $_SERVER['SERVER_ADDR'] . ']'; } else { $server_addr = $_SERVER['SERVER_ADDR']; } $base_url = (Core::isHttps() ? 'https' : 'http') . '://' . $server_addr . substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))); } else { $base_url = 'http://localhost/'; } Config::get('main')->base_url = $base_url; } // If query strings are enabled, we don't need to parse any segments. // However, they don't make sense under CLI. if (Core::isCli() or $this->config->enable_query_strings !== TRUE) { $this->_permitted_uri_chars = $this->config->permitted_uri_chars; // If it's a CLI request, ignore the configuration if (Core::isCli()) { $uri = $this->_parse_argv(); } else { $protocol = $this->config->uri_protocol; empty($protocol) && ($protocol = 'REQUEST_URI'); switch ($protocol) { case 'AUTO': // For BC purposes only // For BC purposes only case 'REQUEST_URI': $uri = $this->_parse_request_uri(); break; case 'QUERY_STRING': $uri = $this->_parse_query_string(); break; case 'PATH_INFO': default: $uri = isset($_SERVER[$protocol]) ? $_SERVER[$protocol] : $this->_parse_request_uri(); break; } } $this->_set_uri_string($uri); } }
/** * CSRF Set Cookie * * @codeCoverageIgnore * @return Security */ public function csrf_set_cookie() { $expire = time() + $this->_csrf_expire; $cfg = Config::get('main'); $secure_cookie = (bool) $cfg->cookie_secure; if ($secure_cookie && !is_https()) { return $this; } setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, $cfg->cookie_path, $cfg->cookie_domain, $secure_cookie, $cfg->cookie_httponly); Logger::log('CSRF cookie sent'); return $this; }
/** * Mime Types * * @param string * @return string */ protected function _mime_types($ext = '') { $ext = strtolower($ext); $mimes = Config::get('mimes')->toArray(); if (isset($mimes[$ext])) { return is_array($mimes[$ext]) ? current($mimes[$ext]) : $mimes[$ext]; } return 'application/x-unknown-content-type'; }
/** * Core Library Loader * * Loads, instantiates and returns a core library. * * @param string $class Classname * @param string $subdir Sub directory in which the final class can be found * @param array $params Optional parameters to pass to the library class constructor * @param array $directory Optional list of directories where the library can be found. Overrides default list * @param bool $newInstance Whether to return a new instance of the library or the same one * @return object * @throws LibraryException */ protected function loadCoreLibrary($class, $subdir, array $parameters = null, array $directories, $newInstance = false) { // First check if the input is correct if (!is_array($directories)) { throw new LibraryException("Could not load module. \$directory variable was not an array", 1); } // Retrieve the subclass prefix $corePrefix = '\\FuzeWorks\\Library\\FW_'; $appPrefix = '\\Application\\Library\\' . Config::get('main')->application_prefix; $prefix = $corePrefix; // Perform a check to see if the library is already loaded if (class_exists($prefix . $class, false)) { // Then check if an application extension also exists if (class_exists($appPrefix . $class, false)) { $prefix = $appPrefix; } if (!isset($this->libraries[$prefix . $class])) { return $this->initLibrary($prefix . $class, $parameters); } // If required to do so, return the existing instance or load a new one if ($newInstance) { $this->factory->logger->log("Library '" . $prefix . $class . "' already loaded. Returning existing instance"); return $this->libraries[$prefix . $class]; } $this->factory->logger->log("Library '" . $prefix . $class . "' already loaded. Returning new instance"); return $this->initLibrary($prefix . $class, $parameters); } // Remove the core directory from the checklist if (in_array(Core::$coreDir . DS . 'Libraries', $directories)) { array_shift($directories); } // First check the directories for the core library (the FW_ class) foreach ($directories as $directory) { $file = $directory . DS . $subdir . $class . '.php'; // Load if it exists if (file_exists($file)) { // First base; if an app library is found with FW_, load that one. There can be no extensions include_once $file; if (class_exists($prefix . $class, false)) { return $this->initLibrary($prefix . $class, $parameters); } else { // Otherwise log a message $this->factory->logger->logWarning("File " . $file . " exists but does not declare {$prefix}{$class}"); } } } // Second base; if no base class is found in the app folder, load it from the core folder include_once Core::$coreDir . DS . 'Libraries' . DS . $subdir . $class . '.php'; // Now let's check for extensions $subclass = $this->factory->config->getConfig('main')->application_prefix . $class; foreach ($directories as $directory) { $file = $directory . DS . $subdir . $subclass . '.php'; // Load if it exists if (file_exists($file)) { include_once $file; if (class_exists($appPrefix . $class, false)) { return $this->initLibrary($appPrefix . $class, $parameters); } else { $this->factory->logger->logWarning("File " . $file . " exists but does not declare {$prefix}{$class}"); } } } // Third and last base; just load the FW_ core class if (class_exists('\\FuzeWorks\\Library\\FW_' . $class, false)) { return $this->initLibrary('\\FuzeWorks\\Library\\FW_' . $class, $parameters); } throw new LibraryException("Could not load library. File " . 'Core' . DS . 'Libraries' . DS . $subdir . $class . '.php' . " exists but does not declare \\FuzeWorks\\Library\\FW_{$class}", 1); }
/** * Class constructor * * @param array $params Configuration parameters * @return void */ public function __construct(array $params = array()) { Logger::newLevel('Initializing Encryption Library'); $this->_drivers = array('mcrypt' => defined('MCRYPT_DEV_URANDOM'), 'openssl' => Core::isPHP('5.3.3') && extension_loaded('openssl')); if (!$this->_drivers['mcrypt'] && !$this->_drivers['openssl']) { throw new LibraryException('Encryption: Unable to find an available encryption driver.', 1); } isset(self::$func_override) or self::$func_override = extension_loaded('mbstring') && ini_get('mbstring.func_override'); $this->initialize($params); if (!isset($this->_key) && self::strlen($key = Config::get('encryption')->encryption_key) > 0) { $this->_key = $key; } Logger::log('Encryption Class Initialized'); Logger::stopLevel(); }
/** * Initializes the core. * * @throws \Exception */ public static function init() { // Set the CWD for usage in the shutdown function self::$cwd = getcwd(); // Set the core dir for when the loading of classes is required self::$coreDir = dirname(__DIR__); // If the environment is not yet defined, use production settings if (!defined('ENVIRONMENT')) { define('ENVIRONMENT', 'PRODUCTION'); } // Defines the time the framework starts. Used for timing functions in the framework if (!defined('STARTTIME')) { define('STARTTIME', microtime(true)); define('DS', DIRECTORY_SEPARATOR); } // Load basics ignore_user_abort(true); register_shutdown_function(array('\\FuzeWorks\\Core', 'shutdown')); // Load core functionality new Factory(); // Load the config file of the FuzeWorks core $config = Config::get('core'); // Disable events if requested to do so if (!$config->enable_events) { Events::disable(); } // Build all the registers for correct operation, if modules are enabled if ($config->enable_modules) { Modules::buildRegister($config->registry_caching, $config->registry_caching_method, $config->registry_caching_time); } // And fire the coreStartEvent $event = Events::fireEvent('coreStartEvent'); if ($event->isCancelled()) { return true; } // And initialize multiple classes Layout::init(); Language::init(); }