/** * Sends email. * * @param Email $email The name of the mailer action to trigger. * @return void */ public function send(Email $email) { if ($this->transport == NULL) { $this->transport = TransportFactory::build(Configuration::getInstance()->get("Mailer/transport", "Basic")); } $this->transport->send($email); }
public function __construct() { $this->sessionTable = Configuration::getInstance()->get("Session/Database/tableName"); $this->dataColumn = Configuration::getInstance()->get("Session/Database/DataColumn"); $this->idColumn = Configuration::getInstance()->get("Session/Database/IDColumn"); $this->lastActivityColumn = Configuration::getInstance()->get("Session/Database/activityColumn"); }
public function __construct() { $loader = new Twig_Loader_Filesystem(Configuration::getInstance()->get("View/viewFolder", ROOT . DIRECTORY_SEPARATOR . 'App/View')); $this->_twigEnv = new Twig_Environment($loader, array('cache' => false)); $this->_twigEnv->addFunction("cell", [$this, "cell"]); $this->_twigEnv->addFunction("fragment", [$this, "fragment"]); }
/** * Delete all keys from the cache * * @param bool $check if true will check expiration, otherwise delete all * @return bool True if the cache was successfully cleared, false otherwise */ public function clear($check) { $files = glob(Configuration::getInstance()->get("Cache/File/directory") . '/*'); foreach ($files as $file) { if ($check === true and file_exists($file) and time() - filemtime($file) <= Configuration::getInstance()->get("Cache/duration")) { continue; } unlink($file); } }
public static function getEngine() { $engineName = Configuration::getInstance()->get("Cache/engine", "File"); $className = Core::className($engineName, "Cache/Engine", "CacheEngine"); if (!$className) { throw new \RuntimeException(sprintf('Cache Engine class "%s" was not found.', $engineName)); } if (static::$_engine instanceof $className) { return static::$_engine; } return static::_build($className); }
/** * Returns true if the session is no longer valid because the last time it was * accessed was after the configured timeout. * * @return bool */ protected function _timedOut() { $time = $this->get('Session.time'); $result = false; $lifetime = Configuration::getInstance()->get("Session/lifetime"); $checkTime = $time !== null && $lifetime > 0; if ($checkTime && time() - $time > $lifetime) { $result = true; } $this->set('Session.time', time()); return $result; }
/** * Handle an incoming request. * * @param Request $request * @param \Closure $next * @return Response */ public function handle(Request $request, Closure $next) : Response { $storage = Configuration::getInstance()->get("FileUpload/storageDirectory"); if ($storage) { foreach ($request->files() as $file) { if (in_array($file->mimeType(), $this->_allowedTypes) or $this->_allowedTypes == FileUploadMiddleware::ALL) { $file->move($storage); } } } return $next($request); }
/** * Sets protected properties based on config provided * */ public function __construct() { $filename = Configuration::getInstance()->get("Log/coreLogFile", "coretyson.log"); if (substr($filename, -4) !== '.log') { $filename .= '.log'; } $this->_file = $filename; $this->_maxLine = Configuration::getInstance()->get("Log/maxFileLines", 50); $this->_path = rtrim(Configuration::getInstance()->get("Log/logFilePath", ROOT . "/logs"), "/\\") . DIRECTORY_SEPARATOR; if (!is_dir($this->_path)) { mkdir($this->_path, 0775, true); } }
/** * Load the plugin path configuration file. * * @return void */ protected static function _loadConfig() { $config = Configuration::getInstance(); if ($config->exists('plugins')) { return; } $vendorFile = $config->get("root") . DS . 'plugins/coretyson-plugins.json'; if (!file_exists($vendorFile)) { $config->insert('plugins', []); return; } $config->merge(json_decode(file_get_contents($vendorFile), true)); }
public static function getDatabaseConnection(string $name) : Database { if (isset(static::$_databaseList[$name])) { return static::$_databaseList[$name]; } $registry = Configuration::getInstance()->get("Database/Connection"); $config = []; if (isset($registry) and isset($registry[$name])) { $config = $registry[$name]; } static::$_databaseList[$name] = new Database($config); return static::$_databaseList[$name]; }
/** * Returns Email transport object out of a transport name * * @return \Psr\Log\AbstractLogger logger instance */ public static function getLogger() { if (static::$_logger) { return static::$_logger; } $className = __NAMESPACE__ . "\\LogEngine\\" . Configuration::getInstance()->get("Log/engine", "File") . "Engine"; if (!class_exists($className)) { throw new \RuntimeException(sprintf('Log engine class "%s" was not found.', $className)); } $logger = new $className(); if (!$logger instanceof AbstractLogger) { throw new \RuntimeException('Logger must extend AbstractLogger class.'); } static::$_logger = $logger; return static::$_logger; }
/** * Gets the shell command listing. * * @return array */ public function getShellList() { $skipFiles = ['AbstractShell']; $shellList = []; $appPath = Configuration::getInstance()->get('App/namespace', 'App') . '/Shell'; $appShells = $this->_scanDir($appPath[0]); $appShells = array_diff($appShells, $skipFiles); $shellList = $this->_appendShells($appShells, $shellList); $shells = $this->_scanDir(dirname(__DIR__) . "/Shell"); $shells = array_diff($shells, $appShells, $skipFiles); $shellList = $this->_appendShells($shells, $shellList); // TODO enable plugin shells /*foreach (PluginLoader::loadedPlugins() as $plugin) { $pluginPath = Plugin::classPath($plugin) . 'Shell'; $pluginShells = $this->_scanDir($pluginPath); $shellList = $this->_appendShells($pluginShells, $shellList); }*/ return array_filter($shellList); }
public function __construct($locale) { $locale_array = explode('_', $locale); $language = $locale_array[0]; $LocalePath = Configuration::getInstance()->get("i18n/localeDirectory", ROOT . '/App/Locale/'); if (empty($language)) { $files = glob($LocalePath . $locale . '/default.*'); } else { $files = glob($LocalePath . $language . '/' . $locale . ".*"); } if (empty($files) or $files === false) { throw new \RuntimeException("Catalog {$locale} not found."); } $file = $files[0]; $parserName = ucfirst(strtolower(pathinfo($locale)['extension'])); $parser = ParserFactory::getInstance()->getParser($parserName); $this->_catalog = $parser->parse($file); $this->_locale = $locale; }
/** * Return the class name namespaced. This method checks if the class is defined on the * application/plugin, otherwise try to load from the CoreTyson core * * @param string $class Class name * @param string $type Type of class * @param string $suffix Class name suffix * @return bool|string False if the class is not found or namespaced class name */ public static function className($class, $type = '', $suffix = '') { if (class_exists($class, true)) { return $class; } list($plugin, $class) = \CoreTyson\pluginSplit($class); $base = $plugin ?: Configuration::getInstance()->get('App/namespace', 'App'); $base = str_replace('/', '\\', rtrim($base, '\\')); if (!\CoreTyson\isEmpty($type)) { $class = $type . '/' . $class; } $fullname = '\\' . str_replace('/', '\\', $class) . $suffix; if (static::_classExistsInBase($fullname, $base)) { return $base . $fullname; } if ($plugin) { return false; } if (static::_classExistsInBase($fullname, 'CoreTyson')) { return 'CoreTyson' . $fullname; } return false; }
protected function _engine() : AbstractRenderingEngine { if ($this->_engine) { return $this->_engine; } $className = Configuration::getInstance()->get("View/renderingEngine", "Php"); $className = Core::className($className, "View/RenderingEngine", "RenderingEngine"); if (!$className) { throw new \RuntimeException('Rendering Engine class was not found.'); } $engine = new $className(); if (!$engine instanceof AbstractRenderingEngine) { throw new \RuntimeException('Rendering engine must extend AbstractRenderingEngine class.'); } return $this->_engine = $engine; }
/** * Finds an template filename, returns false on failure. * * @param string $name The name of the template to find. * @return mixed Either a string to the template filename or null when one can't be found. */ protected function _templateFileName($name) { if (file_exists($name)) { return $name; } $viewPath = Configuration::getInstance()->get("View/viewFolder", ROOT . DIRECTORY_SEPARATOR . 'App/View'); if (is_string($viewPath)) { $viewPath = [$viewPath]; } foreach ($viewPath as $path) { $templateFilename = $path . DIRECTORY_SEPARATOR . $name . static::$templateExtension; if (file_exists($templateFilename)) { return $templateFilename; } } return null; }
<?php require __DIR__ . '/../vendor/autoload.php'; define('TEST_ROOT', __DIR__ . "/testApp" . DIRECTORY_SEPARATOR); define('TMP', sys_get_temp_dir() . DIRECTORY_SEPARATOR); define('DS', DIRECTORY_SEPARATOR); // Ensure default test connection is defined if (!getenv('db_dsn')) { putenv('db_dsn=sqlite:///:memory:'); } \CoreTyson\Core\Configuration::getInstance()->loadFromPHP(__DIR__ . "/testConfig.php");
public function __construct() { $ident = Configuration::getInstance()->get("Log/syslogPrefix", ""); openlog($ident, LOG_ODELAY, LOG_USER); }
/** * loadFromYAML method * * @return void */ public function testLoadFromYAML() { Configuration::getInstance()->loadFromJSON(TEST_ROOT . "/App/config/configuration.json"); }
/** * Handle an incoming request. * * @param Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) : Response { $encryption = Configuration::getInstance()->get("Cookie/Encryption/method", "rijndael"); foreach ($request->cookie() as $name => $value) { if ($this->isExcepted($name)) { continue; } $this->_cookies[$name] = $this->_decryptCookie($value, $encryption); } $response = $next($request); $encryption = Configuration::getInstance()->get("Cookie/Encryption/method", "rijndael"); foreach ($response->cookie() as $name => $value) { if ($this->isExcepted($name)) { continue; } $response->cookie($name, $this->_encryptCookie($value, $encryption)); } return $response; }
public function __construct() { $this->_options = Configuration::getInstance()->get("View/PhpEngine", []) + static::$_defaultOptions; }
/** * Write value for a key into cache * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @return bool True if the data was successfully cached, false on failure */ public function write($key, $value) { return apc_store($key, $value, Configuration::getInstance()->get("Cache/Apc/duration")); }
/** * Get a table instance from the registry. * * Tables are only created once until the registry is flushed. * This means that aliases must be unique across your application. * This is important because table associations are resolved at runtime * and cyclic references need to be handled correctly. * * The options that can be passed are the same as in Cake\ORM\Table::__construct(), but the * `className` key is also recognized. * * ### Options * * - `className` Define the specific class name to use. If undefined, CakePHP will generate the * class name based on the alias. For example 'Users' would result in * `App\Model\Table\UsersTable` being used. If this class does not exist, * then the default `Cake\ORM\Table` class will be used. By setting the `className` * option you can define the specific class to use. The className option supports * plugin short class references {@link Cake\Core\App::shortName()}. * - `table` Define the table name to use. If undefined, this option will default to the underscored * version of the alias name. * - `connection` Inject the specific connection object to use. If this option and `connectionName` are undefined, * The table class' `defaultConnectionName()` method will be invoked to fetch the connection name. * - `connectionName` Define the connection name to use. The named connection will be fetched from * Cake\Datasource\ConnectionManager. * * *Note* If your `$alias` uses plugin syntax only the name part will be used as * key in the registry. This means that if two plugins, or a plugin and app provide * the same alias, the registry will only store the first instance. * * @param string $alias The alias name you want to get. * @param array $options The options you want to build the table with. * If a table has already been loaded the options will be ignored. * @return \Cake\ORM\Table * @throws \RuntimeException When you try to configure an alias that already exists. */ public function get($alias, array $options = []) { if (isset($this->_instances[$alias])) { if (!empty($options) && $this->_options[$alias] !== $options) { throw new RuntimeException(sprintf('You cannot configure "%s", it already exists in the registry.', $alias)); } return $this->_instances[$alias]; } $this->_options[$alias] = $options; list(, $classAlias) = pluginSplit($alias); $options = ['alias' => $classAlias] + $options; if (isset($this->_config[$alias])) { $options += $this->_config[$alias]; } if (empty($options['className'])) { $options['className'] = Inflector::camelize($alias); } $className = $this->_getClassName($alias, $options); if ($className) { $options['className'] = $className; } else { if (!isset($options['table']) && strpos($options['className'], '\\') === false) { list(, $table) = pluginSplit($options['className']); $options['table'] = Inflector::underscore($table); } $options['className'] = 'CoreTyson\\ORM\\Table'; } if (empty($options['connection'])) { if (!empty($options['connectionName'])) { $connectionName = $options['connectionName']; } else { $connectionName = $options['className']::defaultConnectionName(); } if (\CoreTyson\isEmpty(ConnectionManager::config($connectionName))) { ConnectionManager::config($connectionName, $this->_configAdapter(Configuration::getInstance()->get("Database/Connection/" . $connectionName, []))); } $options['connection'] = ConnectionManager::get($connectionName); } $options['registryAlias'] = $alias; $this->_instances[$alias] = $this->_create($options); if ($options['className'] === 'CoreTyson\\ORM\\Table') { $this->_fallbacked[$alias] = $this->_instances[$alias]; } return $this->_instances[$alias]; }
/** * Write value for a key into cache * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @return bool True if the data was successfully cached, false on failure */ public function write($key, $value) { return wincache_ucache_set($key, $value, Configuration::getInstance()->get("Cache/WinCache/duration")); }
/** * Displays an exception response body. * * @param \Exception $exception The exception to display * @return void * @throws \Exception When the chosen exception renderer is invalid. */ protected function _displayException($exception) { $config = Configuration::getInstance(); $renderer = Core::className($config->get("Error/exceptionRenderer", 'CoreTyson\\Error\\ExceptionRenderer'), 'Error'); try { if (!$renderer) { throw new Exception("{$renderer} is an invalid class."); } $error = new $renderer($exception); $response = $error->render(); $this->_clearOutput(); $this->_sendResponse($response); } catch (Exception $e) { // Disable trace for internal errors. $config->set("Error/printTrace", "false"); $message = sprintf("[%s] %s\n%s", get_class($e), $e->getMessage(), $e->getTraceAsString()); trigger_error($message, E_USER_ERROR); } }
/** * Handle an incoming request. * * @param Request $request * @param \Closure $next * @return Response */ public function handle(Request $request, Closure $next) : Response { $result = $this->_sentinel->authenticateFromRequest($request); if ($result instanceof User) { $this->_setUser($result); } if (!$this->_isAllowed($request->param('action'))) { if (!$this->isAuthenticated()) { Session::getInstance()->set("Auth/redirect", $request->url); if ($request->is('ajax')) { $response = new Response(); $response->statusCode(401); return $response; } else { return Response::redirect(Configuration::getInstance()->get("Auth/loginUrl", "/")); } } if (!$this->_sentinel->isAuthorized($result, $request)) { if ($request->is('ajax')) { $response = new Response(); $response->statusCode(403); return $response; } else { return Response::redirect($request->referer()); } } } return $next($request); }
/** * Sends the cookies that have been added before any * other output is sent to the client. Will set the cookies in the order they * have been set. * * @return void */ protected function _sendCookies() { foreach ($this->_cookies as $name => $value) { setcookie($name, $value, Configuration::getInstance()->get("Cookie/expiration", 0), Configuration::getInstance()->get("Cookie/path", "/"), Configuration::getInstance()->get("Cookie/domain", ""), Configuration::getInstance()->get("Cookie/secureCookies", false), Configuration::getInstance()->get("Cookie/httpOnly", false)); } }
public function processError($request, $exception) { $response = new Response(); $viewVars = ["exception" => $exception]; $code = 500; $errorCode = $exception->getCode(); if ($errorCode >= 400 && $errorCode < 506) { $code = $errorCode; } $response->statusCode($code); $viewVars["code"] = $code; if (method_exists($exception, 'responseHeader')) { $response->header($exception->responseHeader()); } if ($request) { $viewVars["url"] = $request->url(); } $isDebug = Configuration::getInstance()->get("debug"); if ($isDebug) { $viewVars['trace'] = Debugger::formatTrace($exception->getTrace(), ['format' => 'array', 'args' => false]); } $message = $exception->getMessage(); $isHttpException = $exception instanceof HttpException; if (!$isDebug && !$isHttpException) { if ($code < 500) { $message = \CoreTyson\tr('cake', 'Not Found'); } else { $message = \CoreTyson\tr('cake', 'An Internal Error Has Occurred.'); } } $viewVars["message"] = $message; $template = "error" . $code; if (!$isDebug && !$isHttpException) { $template = 'error500'; if ($code < 500) { $template = 'error400'; } } if ($isHttpException) { $template = 'error500'; if ($code < 500) { $template = 'error400'; } } if ($exception instanceof PDOException) { $template = 'pdo_error'; } try { $view = new View(); $response->body($view->render("Error/" . $template)); } catch (MissingTemplateException $e) { return $this->_outputMessageSafe('error500'); } catch (MissingPluginException $e) { $attributes = $e->getAttributes(); if (isset($attributes['plugin']) && $attributes['plugin'] === $this->controller->plugin) { $this->controller->plugin = null; } return $this->_outputMessageSafe('error500'); } catch (Exception $e) { return $this->_outputMessageSafe('error500'); } }
/** * Generates a formatted error message * * @param \Exception $exception Exception instance * @return string Formatted message */ protected function _getMessage(Exception $exception) { $exception = $exception instanceof PHP7ErrorException ? $exception->getError() : $exception; $config = Configuration::getInstance(); $message = sprintf("[%s] %s", get_class($exception), $exception->getMessage()); $debug = $config->get('debug'); if ($debug && method_exists($exception, 'getAttributes')) { $attributes = $exception->getAttributes(); if ($attributes) { $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true); } } $request = Router::getInstance()->request(); if ($request) { $message .= $this->_requestContext($request); } if ($config->get('Error/printTrace', false)) { $message .= "\nStack Trace:\n" . $exception->getTraceAsString() . "\n\n"; } return $message; }
/** * Write session data * @link http://php.net/manual/en/sessionhandlerinterface.write.php * @param string $session_id The session id. * @param string $session_data <p> * The encoded session data. This data is the * result of the PHP internally encoding * the $_SESSION superglobal to a serialized * string and passing it as this parameter. * Please note sessions use an alternative serialization method. * </p> * @return bool <p> * The return value (usually TRUE on success, FALSE on failure). * Note this value is returned internally to PHP for processing. * </p> * @since 5.4.0 */ public function write($session_id, $session_data) { return !(false === file_put_contents(Configuration::getInstance()->get("Session/FileHandler/directory") . '/' . $session_id, $session_data)); }