/** * Method to log login failures * * @param array $response * @return void */ public function onUserLoginFailure($response) { if (!App::has('log')) { return; } $errorlog = array(); switch ($response['status']) { case Hubzero\Auth\Status::SUCCESS: $errorlog['status'] = $response['type'] . ' CANCELED: '; $errorlog['comment'] = $response['error_message']; break; case Hubzero\Auth\Status::FAILURE: $errorlog['status'] = $response['type'] . ' FAILURE: '; $errorlog['comment'] = $response['error_message']; if ($this->params->get('log_username', 0)) { $errorlog['comment'] .= ' ("' . $response['username'] . '")'; } break; default: $errorlog['status'] = $response['type'] . ' UNKNOWN ERROR: '; $errorlog['comment'] = $response['error_message']; break; } App::get('log')->logger('auth')->info(implode('', $errorlog)); }
/** * Get an item from the applcation * * @param string $key * @return mixed */ protected static function app($key) { if (\App::has($key)) { return \App::get($key); } return null; }
/** * Constructor * * @param array $config A named configuration array for object construction.<br/> * name: the name (optional) of the view (defaults to the view class name suffix).<br/> * charset: the character set to use for display<br/> * escape: the name (optional) of the function to use for escaping strings<br/> * base_path: the parent path (optional) of the views directory (defaults to the component folder)<br/> * template_plath: the path (optional) of the layout directory (defaults to base_path + /views/ + view name<br/> * helper_path: the path (optional) of the helper files (defaults to base_path + /helpers/)<br/> * layout: the layout (optional) to use to display the view * @return void */ public function __construct($config = array()) { // Set the override path // // NOTE: This needs to come before getName() // as it calls setPath() if (!array_key_exists('override_path', $config)) { $config['override_path'] = ''; if (\App::has('template')) { $config['override_path'] = \App::get('template')->path; } } $this->_overridePath = $config['override_path']; // Set the view name if (!array_key_exists('name', $config)) { $config['name'] = $this->getName(); } $this->_name = $config['name']; // Set the charset (used by the variable escaping functions) if (array_key_exists('charset', $config)) { $this->_charset = $config['charset']; } // User-defined escaping callback if (array_key_exists('escape', $config)) { $this->setEscape($config['escape']); } // Set a base path for use by the view if (!array_key_exists('base_path', $config)) { $config['base_path'] = ''; if (defined('JPATH_COMPONENT')) { $config['base_path'] = JPATH_COMPONENT; } } $this->_basePath = $config['base_path']; // Set the default template search path if (!array_key_exists('template_path', $config)) { $config['template_path'] = $this->_basePath . '/views/' . $this->getName() . '/tmpl'; } $this->setPath('template', $config['template_path']); // Set the default helper search path if (!array_key_exists('helper_path', $config)) { $config['helper_path'] = $this->_basePath . '/helpers'; } $this->setPath('helper', $config['helper_path']); // Set the layout if (!array_key_exists('layout', $config)) { $config['layout'] = $this->_layout; } $this->setLayout($config['layout']); // Set the site's base URL $this->baseurl = \App::get('request')->base(true); }
/** * [!] HUBZERO - Moved from Hubzero Factory * * Get the auth logger, creating it if it doesn't exist * * @return object */ public static function getAuthLogger() { if (class_exists('\\App')) { if (\App::has('log')) { return \App::get('log')->logger('auth'); } } static $instance; if (!$instance instanceof \Hubzero\Log\Writer) { $instance = new \Hubzero\Log\Writer(new \Monolog\Logger(self::getConfig()->get('application_env')), \JDispatcher::getInstance()); $path = self::getConfig()->get('log_path'); if (is_dir('/var/log/hubzero')) { $path = '/var/log/hubzero'; } $instance->useFiles($path . '/cmsauth.log', 'info', "%datetime% %message%\n", 'Y-m-d H:i:s', 0640); } return $instance; }
/** * Checks for a honeypot in the request * * @param string $name * @param integer $delay * @return boolean True if found and valid, false otherwise. */ public static function checkHoneypot($name = null, $delay = 3) { $name = $name ?: \Hubzero\Spam\Honeypot::getName(); if ($honey = self::getVar($name, array(), 'post')) { if (!\Hubzero\Spam\Honeypot::isValid($honey['p'], $honey['t'], $delay)) { if (\App::has('log')) { $fallback = 'option=' . self::getCmd('option') . '&controller=' . self::getCmd('controller') . '&task=' . self::getCmd('task'); $from = self::getVar('REQUEST_URI', $fallback, 'server'); $from = $from ?: $fallback; \App::get('log')->logger('spam')->info('spam honeypot ' . self::ip() . ' ' . \User::get('id') . ' ' . \User::get('username') . ' ' . $from); } return false; } } return true; }
/** * Log results of the check * * @param string $isSpam Spam detection result * @param array $data Data being checked * @return void */ protected function log($isSpam, $data) { if (!\App::has('log')) { return; } $request = \App::get('request'); $fallback = 'option=' . $request->getCmd('option'); $fallback .= '&controller=' . $request->getCmd('controller'); $fallback .= '&task=' . $request->getCmd('task'); $from = $request->getVar('REQUEST_URI', $fallback, 'server'); $from = $from ?: $fallback; $info = array($isSpam ? 'spam' : 'ham', $data['ip'], $data['id'], $data['username'], md5($data['text']), $from); \App::get('log')->logger('spam')->info(implode(' ', $info)); }
/** * Returns the application JPathway object. * * @param string $name The name of the application/client. * @param array $options An optional associative array of configuration settings. * * @return JMenu JMenu object. * * @since 11.1 */ public function getMenu($name = null, $options = array()) { if (class_exists('\\App')) { if (\App::has('menu')) { return \App::get('menu'); } } if (!isset($name)) { $name = $this->_name; } jimport('joomla.application.menu'); $menu = JMenu::getInstance($name, $options); if ($menu instanceof Exception) { return null; } return $menu; }
/** * Loads the published plugins. * * @return array An array of published plugins */ public function all() { if (self::$plugins !== null) { return self::$plugins; } if (!\App::has('cache.store') || !($cache = \App::get('cache.store'))) { $cache = new \Hubzero\Cache\Storage\None(); } $levels = implode(',', User::getAuthorisedViewLevels()); if (!(self::$plugins = $cache->get('com_plugins.' . $levels))) { $db = \App::get('db'); $query = $db->getQuery(true); $query->select('folder AS type, element AS name, protected, params')->from('#__extensions')->where('enabled >= 1')->where('type =' . $db->quote('plugin'))->where('state >= 0')->where('access IN (' . $levels . ')')->order('ordering'); self::$plugins = $db->setQuery($query)->loadObjectList(); if ($error = $db->getErrorMsg()) { throw new Exception($error, 500); } $cache->put('com_plugins.' . $levels, self::$plugins, \App::get('config')->get('cachetime', 15)); } return self::$plugins; }
/** * Log profiler info * * @return void */ protected function logProfile() { if (!App::has('log')) { return; } // This method is only called once per request App::get('log')->register('profile', array('file' => 'cmsprofile.log', 'level' => 'info', 'format' => "%datetime% %message%\n", 'dateFormat' => "Y-m-d\\TH:i:s.uP")); $logger = App::get('log')->logger('profile'); $hubname = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'unknown'; $uri = Request::path(); $uri = strtr($uri, array(" " => "%20")); $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'; $query = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : 'unknown'; $memory = memory_get_usage(true); $querycount = App::get('db')->getCount(); $querytime = App::get('db')->getTimer(); $client = App::get('client')->name; $time = microtime(true) - App::get('profiler')->started(); // <timstamp> <hubname> <ip-address> <app> <url> <query> <memory> <querycount> <timeinqueries> <totaltime> $logger->info("{$hubname} {$ip} {$client} {$uri} [{$query}] {$memory} {$querycount} {$querytime} {$time}"); // Now log post data if applicable if (Request::method() == 'POST' && App::get('config')->get('log_post_data', false)) { App::get('log')->register('post', array('file' => 'cmspost.log', 'level' => 'info', 'format' => "%datetime% %message%\n", 'dateFormat' => "Y-m-d\\TH:i:s.uP")); $logger = App::get('log')->logger('post'); $post = json_encode($_POST); $referrer = $_SERVER['HTTP_REFERER']; // Encrypt for some reasonable level of obscurity $key = md5(App::get('config')->get('secret')); // Compute needed iv size and random iv $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND); $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $post, MCRYPT_MODE_CBC, $iv); // Prepend iv for decoding later $ciphertext = $iv . $ciphertext; // Encode the resulting cipher text so it can be represented by a string $ciphertextEncoded = base64_encode($ciphertext); $logger->info("{$uri} {$referrer} {$ciphertextEncoded}"); } }
/** * Constructor * * @param array $config A named configuration array for object construction. * @return void */ public function __construct($config = array()) { // Set the override path if (!array_key_exists('override_path', $config)) { $config['override_path'] = ''; if (\App::has('template')) { $config['override_path'] = \App::get('template')->path; } } $this->_overridePath = $config['override_path']; // Set the view name if (!array_key_exists('folder', $config)) { $config['folder'] = $this->getFolder(); } $this->_folder = $config['folder']; // Set the view name if (!array_key_exists('element', $config)) { $config['element'] = $this->getElement(); } $this->_element = $config['element']; // Set the view name if (!array_key_exists('name', $config)) { $config['name'] = $this->getName(); } $this->_name = $config['name']; // Set the charset (used by the variable escaping functions) if (array_key_exists('charset', $config)) { $this->_charset = $config['charset']; } // User-defined escaping callback if (array_key_exists('escape', $config)) { $this->setEscape($config['escape']); } // Set a base path for use by the view if (!array_key_exists('base_path', $config)) { if (defined('PATH_APP')) { $config['base_path'] = PATH_APP . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $this->_folder . DIRECTORY_SEPARATOR . $this->_element; if (!file_exists($config['base_path']) && defined('PATH_CORE')) { $config['base_path'] = PATH_CORE . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $this->_folder . DIRECTORY_SEPARATOR . $this->_element; } } } $this->_basePath = $config['base_path']; // Set the default template search path if (!array_key_exists('template_path', $config)) { $config['template_path'] = $this->_basePath . '/views/' . $this->getName() . '/tmpl'; } $this->setPath('template', $config['template_path']); // Set the default helper search path if (!array_key_exists('helper_path', $config)) { $config['helper_path'] = $this->_basePath . '/helpers'; } $this->setPath('helper', $config['helper_path']); // Set the layout if (!array_key_exists('layout', $config)) { $config['layout'] = 'default'; } $this->setLayout($config['layout']); // Set the site's base URL $this->baseurl = \Request::base(true); }
/** * Set a variable in one of the request variables. * * @param string $name Name * @param string $value Value * @param string $hash Hash * @param boolean $overwrite Boolean * * @return string Previous value * * @since 11.1 * * @deprecated 12.1 */ public static function setVar($name, $value = null, $hash = 'method', $overwrite = true) { if (class_exists('\\App')) { if (\App::has('request')) { return \App::get('request')->setVar($name, $value, $hash, $overwrite); } } // If overwrite is true, makes sure the variable hasn't been set yet if (!$overwrite && array_key_exists($name, $_REQUEST)) { return $_REQUEST[$name]; } // Clean global request var $GLOBALS['_JREQUEST'][$name] = array(); // Get the request hash value $hash = strtoupper($hash); if ($hash === 'METHOD') { $hash = strtoupper($_SERVER['REQUEST_METHOD']); } $previous = array_key_exists($name, $_REQUEST) ? $_REQUEST[$name] : null; switch ($hash) { case 'GET': $_GET[$name] = $value; $_REQUEST[$name] = $value; break; case 'POST': $_POST[$name] = $value; $_REQUEST[$name] = $value; break; case 'COOKIE': $_COOKIE[$name] = $value; $_REQUEST[$name] = $value; break; case 'FILES': $_FILES[$name] = $value; break; case 'ENV': $_ENV['name'] = $value; break; case 'SERVER': $_SERVER['name'] = $value; break; } // Mark this variable as 'SET' $GLOBALS['_JREQUEST'][$name]['SET.' . $hash] = true; $GLOBALS['_JREQUEST'][$name]['SET.REQUEST'] = true; return $previous; }
/** * Wrapper method for the {@link raise()} method with predefined error * level of E_NOTICE and backtrace set to false. * * @param string $code The application-internal error code for this error * @param string $msg The error message, which may also be shown the user if need be. * @param mixed $info Optional: Additional error information (usually only * developer-relevant information that the user * should never see, like a database DSN). * * @return object The configured JError object * * @deprecated 12.1 Use PHP Exception * @see raise() * @since 11.1 */ public static function raiseNotice($code, $msg, $info = null) { // [!] Hubzero if (class_exists('\\App')) { if (\App::has('notification')) { \App::get('notification')->warning($msg); return; } } // Deprecation warning. JLog::add('JError::raiseNotice() is deprecated.', JLog::WARNING, 'deprecated'); return JError::raise(E_NOTICE, $code, $msg, $info); }
public static function getSingleton($className = '', $type = 'model', $arguments = array()) { $type = ucfirst($type); $registryKey = 'app/singleton/'.$type.'/'.$className; if(!App::has($registryKey)){ switch ($type){ case 'Model': App::register($registryKey, self::getModel($className, $arguments)); break; case 'Block': App::register($registryKey, self::getBlock($className, $arguments)); break; default: self::throwException($type . ' no supported in the application.'); break; } } return App::get($registryKey); }
/** * Save cached data * * @return void */ public function onAfterRender() { if (App::isAdmin() || Config::get('debug')) { return; } if (Notify::any() || !App::has('cache')) { return; } if (User::isGuest() && $this->params->get('pagecache', false)) { $path = trim(str_replace(Request::base(), '', Request::current())); $path = trim($path, '/'); if ($this->isExempt($path) || $this->isExempt(Request::current())) { return; } // We need to check again here, because auto-login plugins // have not been fired before the first aid check App::get('cache')->put($this->getId(), App::get('response')->getContent(), App::get('config')->get('lifetime', 45)); } }
/** * This method should handle any login logic and report back to the subject * * @param array $user Holds the user data * @param array $options Array holding options (remember, autoregister, group) * @return boolean True on success */ public function onUserLogin($user, $options = array()) { $instance = $this->_getUser($user, $options); // If _getUser returned an error, then pass it back. if ($instance instanceof Exception) { return false; } // If the user is blocked, redirect with an error if ($instance->get('block') == 1) { Notify::warning(Lang::txt('JERROR_NOLOGIN_BLOCKED')); return false; } // Authorise the user based on the group information if (!isset($options['group'])) { $options['group'] = 'USERS'; } // Chek the user can login. $result = $instance->authorise($options['action']); if (!$result) { Notify::warning(Lang::txt('JERROR_LOGIN_DENIED')); return false; } // Mark the user as logged in $instance->set('guest', 0); // Register the needed session variables $session = App::get('session'); $session->set('user', $instance); // Check to see the the session already exists. if (App::get('config')->get('session_handler') != 'database' && (time() % 2 || $session->isNew()) || App::get('config')->get('session_handler') == 'database' && $session->isNew()) { if (App::get('config')->get('session_handler') == 'database' && App::has('db')) { $db = App::get('db'); $query = $db->getQuery(true); $query->select($query->qn('session_id'))->from($query->qn('#__session'))->where($query->qn('session_id') . ' = ' . $query->q($session->getId())); $db->setQuery($query, 0, 1); $exists = $db->loadResult(); // If the session record doesn't exist initialise it. if (!$exists) { $query->clear(); $ip = Request::ip(); if ($session->isNew()) { $query->insert($query->qn('#__session'))->columns($query->qn('session_id') . ', ' . $query->qn('client_id') . ', ' . $query->qn('time') . ', ' . $query->qn('ip'))->values($query->q($session->getId()) . ', ' . (int) App::get('client')->id . ', ' . $query->q((int) time()) . ', ' . $query->q($ip)); $db->setQuery($query); } else { $query->insert($query->qn('#__session'))->columns($query->qn('session_id') . ', ' . $query->qn('client_id') . ', ' . $query->qn('guest') . ', ' . $query->qn('time') . ', ' . $query->qn('userid') . ', ' . $query->qn('username') . ', ' . $query->q('ip'))->values($query->q($session->getId()) . ', ' . (int) App::get('client')->id . ', ' . (int) $instance->get('guest') . ', ' . $query->q((int) $session->get('session.timer.start')) . ', ' . (int) $instance->get('id') . ', ' . $query->q($instance->get('username')) . ', ' . $query->q($ip)); $db->setQuery($query); } // If the insert failed, exit the application. if (App::get('client')->id != 4 && !$db->execute()) { exit($db->getErrorMsg()); } } } // Session doesn't exist yet, so create session variables if ($session->isNew()) { $session->set('registry', new Hubzero\Config\Registry('session')); $session->set('user', $instance); } } if (App::get('config')->get('session_handler') == 'database') { // Update the user related fields for the Joomla sessions table. $db = App::get('db'); $db->setQuery('UPDATE ' . $db->quoteName('#__session') . ' SET ' . $db->quoteName('guest') . ' = ' . $db->quote($instance->get('guest')) . ',' . ' ' . $db->quoteName('username') . ' = ' . $db->quote($instance->get('username')) . ',' . ' ' . $db->quoteName('userid') . ' = ' . (int) $instance->get('id') . ' WHERE ' . $db->quoteName('session_id') . ' = ' . $db->quote($session->getId())); $db->query(); } // Hit the user last visit field $instance->setLastVisit(); return true; }
/** * Sets an entire array of search paths for templates or resources. * * @param string $type The type of path to set, typically 'template'. * @param string|array $path The new set of search paths. If null or false, resets to the current directory only. * @return void */ protected function _setPath($type, $path) { // clear out the prior search dirs $this->_path[$type] = array(); // actually add the user-specified directories $this->_addPath($type, $path); // always add the fallback directories as last resort switch (strtolower($type)) { case 'template': $option = 'plg_' . $this->_folder . '_' . $this->_element; $option = preg_replace('/[^A-Z0-9_\\.-]/i', '', $option); // set the alternative template search dir if (\App::has('template')) { $this->_addPath('template', \App::get('template')->path . DS . 'html' . DS . $option . DS . $this->getName()); } break; } }