/** * Method to catch the onAfterRoute event. * * @return boolean */ public function onAfterRoute() { $task = Request::getVar('task', 'none'); if (User::isGuest() || !App::isSite() || $task == 'user.logout') { return false; } $menuId = $this->params->get('menuId', 0); if (!$menuId) { return false; } $menu = App::get('menu'); $activeMenu = $menu->getActive(); $defaultMenu = $menu->getDefault(); // If routing to the home page... if ($activeMenu == $defaultMenu) { // Reset the active menu item and // overwrite request vars $menu->setActive($menuId); $menu->setDefault($menuId, $defaultMenu->language); $item = $menu->getItem($menuId); $vars = $item->query; $vars['Itemid'] = $menuId; foreach ($vars as $key => $var) { Request::setVar($key, $var); } } return true; }
/** * Hook for after routing application * * @return void */ public function onAfterRoute() { if (!App::isAdmin() && !App::isSite()) { return; } $client = 'Site'; if (App::isAdmin()) { $client = 'Admin'; return; } // Check if active for this client (Site|Admin) if (!$this->params->get('activate' . $client) || Request::getVar('format') == 'pdf') { return; } Html::behavior('framework'); if ($this->params->get('jqueryui')) { Html::behavior('framework', true); } if ($this->params->get('jqueryfb')) { Html::behavior('modal'); } if ($this->params->get('noconflict' . $client)) { Document::addScript(Request::root(true) . '/core/assets/js/jquery.noconflict.js'); } }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (User::isGuest()) { $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; if (App::isSite()) { $pages = ['com_users.login']; $granted = Session::get('user_consent', false); if (in_array($current, $pages) && !$granted) { Request::setVar('option', 'com_users'); Request::setVar('view', 'userconsent'); } } else { if (App::isAdmin()) { $exceptions = ['com_login.grantconsent']; $granted = Session::get('user_consent', false); if (!in_array($current, $exceptions) && !$granted) { Request::setVar('option', 'com_login'); Request::setVar('task', 'consent'); } } } } }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_users.userlogout', 'com_support.tickets.save.index', 'com_members.changepassword', 'com_members.media.download.profiles']; $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; $badpassword = Session::get('badpassword', false); $expiredpassword = Session::get('expiredpassword', false); // If guest, proceed as normal and they'll land on the login page if (!in_array($current, $exceptions) && ($badpassword || $expiredpassword)) { Request::setVar('option', 'com_members'); Request::setVar('task', 'changepassword'); Request::setVar('id', 0); if ($badpassword) { Request::setVar('Your password does not meet current site requirements. Please change your password now.'); } if ($expiredpassword) { Request::setVar('Your password has expired. Please change your password now.'); } $this->event->stop(); } } }
/** * Constructor * * @return boolean */ public function onAfterRoute() { $task = Request::getVar('task', 'none'); if (User::isGuest() || !App::isSite() || $task == 'user.logout') { return false; } /*$ignoredURLs = (string) $this->params->get('ignore_urls', ''); if ($ignoredURLs) { $ignoredURLArray = explode("\r\n",$ignoredURLs); $fullURL = Request::current(); foreach ($ignoredURLArray as $str) { $pos = strpos($fullURL, $str); if ($pos !== false) { return false; } } } $ignoredOptions = (string) $this->params->get('ignore_options', ''); if ($ignoredOptions) { $option = Request::getCmd('option', ''); $ignoredOptionsArray = explode("\r\n", $ignoredOptions); foreach ($ignoredOptionsArray as $str) { if ($str == $option) { return false; } } }*/ $menuId = $this->params->get('menuId', 0); if (!$menuId) { return false; } $menu = App::get('menu'); $activeMenu = $menu->getActive(); $defaultMenu = $menu->getDefault(); if ($activeMenu == $defaultMenu) { $menu->setActive($menuId); $menu->setDefault($menuId, $defaultMenu->language); $item = $menu->getItem($menuId); $vars = $item->query; $vars['Itemid'] = $menuId; foreach ($vars as $key => $var) { Request::setVar($key, $var); } //Request::set($vars, 'method', true); //App::redirect(Route::url('index.php?Itemid=' . $menuId, false)); } return true; }
/** * Object Constructor. * * @param object The object to observe -- event dispatcher. * @param object The configuration object for the plugin. * @return void * @since 1.0 */ public function __construct(&$subject, $config) { parent::__construct($subject, $config); if (App::isSite()) { // Set the error handler for E_ERROR to be the class handleError method. set_exception_handler(array('plgSystemRedirect', 'handleError')); } }
/** * Check if caching should be re-enabled for this page if it was disabled and * set the site config accordingly * * @return void */ public function onAfterDispatch() { if ($this->_checkRules() && \App::isSite()) { if ($this->params->def('reenable_afterdispatch', 0)) { \Config::set('caching', $this->_caching); } } }
/** * Before save content method * * Article is passed by reference, but after the save, so no changes will be saved. * Method is called right after the content is saved * * @param string $context The context of the content passed to the plugin (added in 1.6) * @param object $article Model * @param boolean $isNew If the content is just about to be created * @return void * @since 2.5 */ public function onContentBeforeSave($context, $article, $isNew) { if (!App::isSite()) { return; } if ($article instanceof \Hubzero\Base\Object || $article instanceof \Hubzero\Database\Relational) { $key = $this->_key($context); $content = ltrim($article->get($key)); } else { if (is_object($article) || is_array($article)) { return; } else { $content = $article; } } $content = preg_replace('/^<!-- \\{FORMAT:.*\\} -->/i', '', $content); $content = trim($content); if (!$content) { return; } // Get the detector manager $service = new \Hubzero\Spam\Checker(); foreach (Event::trigger('antispam.onAntispamDetector') as $detector) { if (!$detector) { continue; } $service->registerDetector($detector); } // Check content $data = array('name' => User::get('name'), 'email' => User::get('email'), 'username' => User::get('username'), 'id' => User::get('id'), 'ip' => Request::ip(), 'user_agent' => Request::getVar('HTTP_USER_AGENT', null, 'server'), 'text' => $content); $result = $service->check($data); // Log errors any of the service providers may have thrown if ($service->getError() && App::has('log')) { App::get('log')->logger('debug')->info(implode(' ', $service->getErrors())); } // If the content was detected as spam... if ($result->isSpam()) { // Learn from it? if ($this->params->get('learn_spam', 1)) { Event::trigger('antispam.onAntispamTrain', array($content, true)); } // If a message was set... if ($message = $this->params->get('message')) { Notify::error($message); } // Increment spam hits count...go to spam jail! \Hubzero\User\User::oneOrFail(User::get('id'))->reputation->incrementSpamCount(); if ($this->params->get('log_spam')) { $this->log($result->isSpam(), $data); } return false; } // Content was not spam. // Learn from it? if ($this->params->get('learn_ham', 0)) { Event::trigger('antispam.onAntispamTrain', array($content, false)); } }
/** * Log an activity * * @param array $activity * @param array $recipients * @return void */ public function logActivity($activity, $recipients = array()) { if (!App::isSite()) { return; } if (!$activity) { return; } \Hubzero\Activity\Log::log($activity, $recipients); }
public function onAfterInitialise() { // No remember me for admin if (!App::isSite()) { return; } if (User::isGuest()) { $hash = App::hash('JLOGIN_REMEMBER'); if ($str = Request::getString($hash, '', 'cookie', 1 | 2)) { $credentials = array(); $goodCookie = true; $filter = JFilterInput::getInstance(); // Create the encryption key, apply extra hardening using the user agent string. // Since we're decoding, no UA validity check is required. $privateKey = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $privateKey, $privateKey)); try { $str = $crypt->decrypt($str); if (!is_string($str)) { throw new Exception('Decoded cookie is not a string.'); } $cookieData = json_decode($str); if (null === $cookieData) { throw new Exception('JSON could not be docoded.'); } if (!is_object($cookieData)) { throw new Exception('Decoded JSON is not an object.'); } // json_decoded cookie could be any object structure, so make sure the // credentials are well structured and only have user and password. if (isset($cookieData->username) && is_string($cookieData->username)) { $credentials['username'] = $filter->clean($cookieData->username, 'username'); } else { throw new Exception('Malformed username.'); } if (isset($cookieData->password) && is_string($cookieData->password)) { $credentials['password'] = $filter->clean($cookieData->password, 'string'); } else { throw new Exception('Malformed password.'); } // We're only doing this for the site app, so we explicitly set the action here $return = App::get('auth')->login($credentials, array('silent' => true, 'action' => 'core.login.site')); if (!$return) { throw new Exception('Log-in failed.'); } } catch (Exception $e) { $cookie_domain = Config::get('cookie_domain', ''); $cookie_path = Config::get('cookie_path', '/'); // Clear the remember me cookie setcookie(App::hash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain); Log::warning('A remember me cookie was unset for the following reason: ' . $e->getMessage()); } } } }
/** * Handle an error * * @param object $error * @return void */ public static function handleError(&$error) { // Make sure the error is a 403 and we are in the frontend. if ($error->getCode() == 403 and App::isSite()) { // Redirect to the home page App::redirect('index.php', Lang::txt('PLG_SYSTEM_LOGOUT_REDIRECT'), null, true, false); } else { // Render the error page. $renderer = new \Hubzero\Error\Renderer\Page(App::get('document'), App::get('template')->template, App::get('config')->get('debug')); $renderer->render($error); } }
/** * Before save content method * * Article is passed by reference, but after the save, so no changes will be saved. * Method is called right after the content is saved * * @param string $context The context of the content passed to the plugin (added in 1.6) * @param object $article A JTableContent object * @param boolean $isNew If the content is just about to be created * @return void * @since 2.5 */ public function onContentBeforeSave($context, $article, $isNew) { if (!App::isSite()) { return; } if ($article instanceof \Hubzero\Base\Object) { $key = $this->_key($context); $content = ltrim($article->get($key)); } else { if (is_object($article) || is_array($article)) { return; } else { $content = $article; } } $content = preg_replace('/^<!-- \\{FORMAT:.*\\} -->/i', '', $content); $content = trim($content); if (!$content) { return; } // Get the detector manager $service = new \Hubzero\Spam\Checker(); foreach (Event::trigger('antispam.onAntispamDetector') as $detector) { if (!$detector) { continue; } $service->registerDetector($detector); } // Check content $data = array('name' => User::get('name'), 'email' => User::get('email'), 'username' => User::get('username'), 'id' => User::get('id'), 'text' => $content); $result = $service->check($data); // If the content was detected as spam... if ($result->isSpam()) { // Learn from it? if ($this->params->get('learn_spam', 1)) { Event::trigger('antispam.onAntispamTrain', array($content, true)); } // If a message was set... if ($message = $this->params->get('message')) { Notify::error($message); } // Increment spam hits count...go to spam jail! \Hubzero\User\User::oneOrFail(User::get('id'))->reputation->incrementSpamCount(); return false; } // Content was not spam. // Learn from it? if ($this->params->get('learn_ham', 0)) { Event::trigger('antispam.onAntispamTrain', array($content, false)); } }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_support.tickets.save.index', 'com_members.media.download.profiles']; $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; // If guest, proceed as normal and they'll land on the login page if (!in_array($current, $exceptions) && User::getInstance()->reputation->isJailed()) { Request::setVar('option', 'com_users'); Request::setVar('view', 'spamjail'); } } }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_users.userlogout', 'com_support.tickets.save.index', 'com_support.tickets.new.index', 'com_members.media.download.profiles', 'com_members.register.unconfirmed.profiles', 'com_members.register.change.profiles', 'com_members.register.resend.profiles', 'com_members.register.resend', 'com_members.register.confirm.profiles', 'com_members.register.confirm', 'com_members.save.profiles', 'com_members.profiles.save', 'com_members.profiles.save.profiles', 'com_members.changepassword']; $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; if (User::get('id') && User::get('activation') != 1 && User::get('activation') != 3 && !in_array($current, $exceptions)) { Request::setVar('option', 'com_members'); Request::setVar('controller', 'register'); Request::setVar('task', 'unconfirmed'); $this->event->stop(); } } }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_users.userlogout', 'com_support.tickets.save.index', 'com_support.tickets.new.index', 'com_members.media.download.profiles']; $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; // If guest, proceed as normal and they'll land on the login page if (!in_array($current, $exceptions) && !User::get('approved')) { Request::setVar('option', 'com_users'); Request::setVar('view', 'unapproved'); $this->event->stop(); } } }
/** * Return data on a resource view (this will be some form of HTML) * * @param object $resource Current resource * @param string $option Name of the component * @param array $areas Active area(s) * @param string $rtrn Data to be returned * @return void */ public function onResources($model, $option, $areas, $rtrn = 'all') { if (!App::isSite()) { return; } if (Request::getWord('tmpl') || Request::getWord('format') || Request::getInt('no_html')) { return; } $view = $this->view(); Document::addCustomTag('<meta property="og:title" content="' . $view->escape($model->resource->title) . '" />'); Document::addCustomTag('<meta property="og:description" content="' . $view->escape($model->resource->introtext) . '" />'); Document::addCustomTag('<meta property="og:type" content="article" />'); $url = Route::url('index.php?option=com_resources&' . ($model->resource->alias ? 'alias=' . $model->resource->alias : 'id=' . $model->resource->id)); $url = rtrim(Request::root(), '/') . '/' . trim($url, '/'); Document::addCustomTag('<meta property="og:url" content="' . $url . '" />'); }
/** * Method to handle an error condition. * * @param Exception &$error The Exception object to be handled. * @return void */ public static function handleError(&$error) { $renderer = new \Hubzero\Error\Renderer\Page(App::get('document'), App::get('template.loader'), App::get('config')->get('debug')); // Make sure the error is a 404 and we are not in the administrator. if (!App::isSite() || $error->getCode() != 404) { // Render the error page. return $renderer->render($error); } // Get the full current URI. $uri = Hubzero\Utility\Uri::getInstance(); $current = $uri->toString(array('scheme', 'host', 'port', 'path', 'query', 'fragment')); // Attempt to ignore idiots. if (strpos($current, 'mosConfig_') !== false || strpos($current, '=http://') !== false) { // Render the error page. return $renderer->render($error); } if (file_exists(PATH_CORE . DS . 'components' . DS . 'com_redirect' . DS . 'models' . DS . 'link.php')) { include_once PATH_CORE . DS . 'components' . DS . 'com_redirect' . DS . 'models' . DS . 'link.php'; // See if the current url exists in the database as a redirect. $link = \Components\Redirect\Models\Link::all()->whereEquals('old_url', $current)->row(); // If no published redirect was found try with the server-relative URL if (!$link->get('id') || $link->get('published') != 1) { $currRel = $uri->toString(array('path', 'query', 'fragment')); $link = \Components\Redirect\Models\Link::all()->whereEquals('old_url', $currRel)->row(); } // If a redirect exists and is published, permanently redirect. if ($link->get('id') && $link->get('published') == 1) { App::redirect($link->new_url, null, null, true, false); } $referer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']; $row = \Components\Redirect\Models\Link::all()->whereEquals('old_url', substr($current, 0, 255))->row(); if (!$row->get('id')) { $row->set(['old_url' => $current, 'new_url' => '', 'referer' => $referer, 'comment' => '', 'hits' => 1, 'published' => 0, 'created_date' => Date::toSql()]); } else { $row->set('hits', intval($row->get('hits', 0)) + 1); } try { $row->save(); } catch (Exception $e) { // Do nothing for now. // @TODO Log this? } } // Render the error page. $renderer->render($error); }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_users.userlogout', 'com_support.tickets.save.index', 'com_support.tickets.new.index', 'com_members.media.download.profiles', 'com_members.register.unconfirmed.profiles', 'com_members.register.change.profiles', 'com_members.register.resend.profiles', 'com_members.register.confirm.profiles']; $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; $xprofile = \Hubzero\User\Profile::getInstance(User::get('id')); if (is_object($xprofile) && $xprofile->get('emailConfirmed') != 1 && $xprofile->get('emailConfirmed') != 3 && !in_array($current, $exceptions)) { Request::setVar('option', 'com_members'); Request::setVar('controller', 'register'); Request::setVar('task', 'unconfirmed'); $this->event->stop(); } } }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_users.userlogout', 'com_support.tickets.save.index', 'com_support.tickets.new.index', 'com_members.media.download.profiles', 'com_members.save.profiles']; $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; if (!in_array($current, $exceptions) && Session::get('registration.incomplete')) { // First check if we're heading to the registration pages, and allow that through if (Request::getWord('option') == 'com_members' && (Request::getWord('controller') == 'register' || Request::getWord('view') == 'register')) { // Set linkaccount far to false at this point, otherwise we'd get stuck in a loop Session::set('linkaccount', false); $this->event->stop(); return; } // Joomla tmp users if (User::get('tmp_user')) { Request::setVar('option', 'com_members'); Request::setVar('controller', 'register'); Request::setVar('task', 'create'); Request::setVar('act', ''); } else { if (substr(User::get('email'), -8) == '@invalid') { $usersConfig = Component::params('com_users'); $simpleRegistration = $usersConfig->get('simple_registration', false); if (Session::get('linkaccount', true) && !$simpleRegistration) { Request::setVar('option', 'com_users'); Request::setVar('view', 'link'); } else { Request::setVar('option', 'com_members'); Request::setVar('controller', 'register'); Request::setVar('task', 'update'); Request::setVar('act', ''); } } else { Request::setVar('option', 'com_members'); Request::setVar('task', 'view'); Request::setVar('id', User::get('id')); Request::setVar('active', 'profile'); } } $this->event->stop(); } } }
/** * Converting the site URL to fit to the HTTP request * * @return bool */ public function onAfterRender() { if (!App::isSite() || !Config::get('sef')) { return true; } // Replace src links $base = Request::base(true) . '/'; $buffer = App::get('response')->getContent(); $regex = '#href="index.php\\?([^"]*)#m'; $buffer = preg_replace_callback($regex, array('plgSystemSef', 'route'), $buffer); $this->checkBuffer($buffer); $protocols = '[a-zA-Z0-9]+:'; //To check for all unknown protocals (a protocol must contain at least one alpahnumeric fillowed by : $regex = '#(src|href|poster)="(?!/|' . $protocols . '|\\#|\')([^"]*)"#m'; $buffer = preg_replace($regex, "\$1=\"{$base}\$2\"", $buffer); $this->checkBuffer($buffer); // Onclick $regex = '#(onclick="window.open\\(\')(?!/|' . $protocols . '|\\#)([^/]+[^\']*?\')#m'; $buffer = preg_replace($regex, '$1' . $base . '$2', $buffer); $this->checkBuffer($buffer); // ONMOUSEOVER / ONMOUSEOUT $regex = '#(onmouseover|onmouseout)="this.src=([\']+)(?!/|' . $protocols . '|\\#|\')([^"]+)"#m'; $buffer = preg_replace($regex, '$1="this.src=$2' . $base . '$3$4"', $buffer); $this->checkBuffer($buffer); // Background image $regex = '#style\\s*=\\s*[\'\\"](.*):\\s*url\\s*\\([\'\\"]?(?!/|' . $protocols . '|\\#)([^\\)\'\\"]+)[\'\\"]?\\)#m'; $buffer = preg_replace($regex, 'style="$1: url(\'' . $base . '$2$3\')', $buffer); $this->checkBuffer($buffer); // OBJECT <param name="xx", value="yy"> -- fix it only inside the <param> tag $regex = '#(<param\\s+)name\\s*=\\s*"(movie|src|url)"[^>]\\s*value\\s*=\\s*"(?!/|' . $protocols . '|\\#|\')([^"]*)"#m'; $buffer = preg_replace($regex, '$1name="$2" value="' . $base . '$3"', $buffer); $this->checkBuffer($buffer); // OBJECT <param value="xx", name="yy"> -- fix it only inside the <param> tag $regex = '#(<param\\s+[^>]*)value\\s*=\\s*"(?!/|' . $protocols . '|\\#|\')([^"]*)"\\s*name\\s*=\\s*"(movie|src|url)"#m'; $buffer = preg_replace($regex, '<param value="' . $base . '$2" name="$3"', $buffer); $this->checkBuffer($buffer); // OBJECT data="xx" attribute -- fix it only in the object tag $regex = '#(<object\\s+[^>]*)data\\s*=\\s*"(?!/|' . $protocols . '|\\#|\')([^"]*)"#m'; $buffer = preg_replace($regex, '$1data="' . $base . '$2"$3', $buffer); $this->checkBuffer($buffer); App::get('response')->setContent($buffer); return true; }
/** * Drop a cookie * * @param (string) $namespace - make sure the cookie name is unique * @param (time) $lifetime - how long the cookie should last * @param (array) $data - data to be saved in cookie * @return void **/ public static function bake($namespace, $lifetime, $data = array()) { $hash = \App::hash(\App::get('client')->name . ':' . $namespace); $key = \App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $cookie = $crypt->encrypt(serialize($data)); // Determine whether cookie should be 'secure' or not $secure = false; $forceSsl = \Config::get('force_ssl', false); if (\App::isAdmin() && $forceSsl >= 1) { $secure = true; } else { if (\App::isSite() && $forceSsl == 2) { $secure = true; } } // Set the actual cookie setcookie($hash, $cookie, $lifetime, '/', '', $secure, true); }
/** * Method to carry template setting in user session if * using the mobile template. * * @return void */ public function onAfterDispatch() { if (!App::isSite()) { return; } $session = App::get('session'); $tmpl = Request::getVar('tmpl', ''); if ($tmpl == 'mobile') { $session->set('mobile', true); } else { if ($session->get('mobile')) { Request::setVar('tmpl', 'mobile'); } } // Are we requesting to view full site again? if ($tmpl == 'fullsite') { $session->set('mobile', false); Request::setVar('tmpl', ''); App::redirect($_SERVER['SCRIPT_URI'] . '?' . str_replace('tmpl=fullsite', '', $_SERVER['QUERY_STRING'])); } }
/** * Plugin that change the language code used in the <html /> tag */ public function onAfterRender() { // Use this plugin only in site application if (App::isSite()) { // Get the response body $body = App::get('response')->getContent(); // Get the current language code $code = Document::getLanguage(); // Get the new code $new_code = $this->params->get($code); // Replace the old code by the new code in the <html /> tag if ($new_code) { // Replace the new code in the HTML document $patterns = array(chr(1) . '(<html.*\\s+xml:lang=")(' . $code . ')(".*>)' . chr(1) . 'i', chr(1) . '(<html.*\\s+lang=")(' . $code . ')(".*>)' . chr(1) . 'i'); $replace = array('${1}' . strtolower($new_code) . '${3}', '${1}' . strtolower($new_code) . '${3}'); } else { $patterns = array(); $replace = array(); } // Replace codes in <link hreflang="" /> attributes preg_match_all(chr(1) . '(<link.*\\s+hreflang=")([0-9a-z\\-]*)(".*\\s+rel="alternate".*/>)' . chr(1) . 'i', $body, $matches); foreach ($matches[2] as $match) { $new_code = $this->params->get(strtolower($match)); if ($new_code) { $patterns[] = chr(1) . '(<link.*\\s+hreflang=")(' . $match . ')(".*\\s+rel="alternate".*/>)' . chr(1) . 'i'; $replace[] = '${1}' . $new_code . '${3}'; } } preg_match_all(chr(1) . '(<link.*\\s+rel="alternate".*\\s+hreflang=")([0-9A-Za-z\\-]*)(".*/>)' . chr(1) . 'i', $body, $matches); foreach ($matches[2] as $match) { $new_code = $this->params->get(strtolower($match)); if ($new_code) { $patterns[] = chr(1) . '(<link.*\\s+rel="alternate".*\\s+hreflang=")(' . $match . ')(".*/>)' . chr(1) . 'i'; $replace[] = '${1}' . $new_code . '${3}'; } } App::get('response')->setContent(preg_replace($patterns, $replace, $body)); } }
/** * Method to catch the onAfterDispatch event. * * This is where we setup the click-through content highlighting for. * The highlighting is done with JavaScript so we just * need to check a few parameters and the JHtml behavior will do the rest. * * @return boolean True on success * * @since 2.5 */ public function onAfterDispatch() { // Check that we are in the site application. if (!App::isSite()) { return true; } // Set the variables $extension = Request::getCmd('option', ''); // Check if the highlighter is enabled. if (!Component::params($extension)->get('highlight_terms', 1)) { return true; } // Check if the highlighter should be activated in this environment. if (Document::getType() !== 'html' || Request::getCmd('tmpl', '') === 'component') { return true; } // Get the terms to highlight from the request. $terms = Request::getVar('highlight', null, 'base64'); $terms = $terms ? json_decode(base64_decode($terms)) : null; // Check the terms. if (empty($terms)) { return true; } // Clean the terms array $filter = JFilterInput::getInstance(); $cleanTerms = array(); foreach ($terms as $term) { $cleanTerms[] = htmlspecialchars($filter->clean($term, 'string')); } // Activate the highlighter. Html::behavior('highlighter', $cleanTerms); // Adjust the component buffer. $buf = Document::getBuffer('component'); $buf = '<br id="highlighter-start" />' . $buf . '<br id="highlighter-end" />'; Document::setBuffer($buf, 'component'); return true; }
/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { if (App::isSite() && !User::isGuest()) { $exceptions = ['com_users.logout', 'com_users.userlogout', 'com_support.tickets.save.index', 'com_support.tickets.new.index', 'com_members.media.download.profiles', 'com_members.save.profiles', 'com_members.profiles.save', 'com_members.profiles.save.profiles', 'com_members.changepassword', 'com_content.article', '/legal/terms']; if ($allowed = trim($this->params->get('exceptions'))) { $allowed = str_replace("\r", '', $allowed); $allowed = str_replace('\\n', "\n", $allowed); $allowed = explode("\n", $allowed); $allowed = array_map('trim', $allowed); $allowed = array_map('strtolower', $allowed); $exceptions = array_merge($exceptions, $allowed); $exceptions = array_unique($exceptions); } $current = Request::getWord('option', ''); $current .= ($controller = Request::getWord('controller', false)) ? '.' . $controller : ''; $current .= ($task = Request::getWord('task', false)) ? '.' . $task : ''; $current .= ($view = Request::getWord('view', false)) ? '.' . $view : ''; // If exception not found, let's try by raw URL path if (!in_array($current, $exceptions)) { $current = Request::path(); } if (!in_array($current, $exceptions) && Session::get('registration.incomplete')) { // First check if we're heading to the registration pages, and allow that through if (Request::getWord('option') == 'com_members' && (Request::getWord('controller') == 'register' || Request::getWord('view') == 'register')) { // Set linkaccount far to false at this point, otherwise we'd get stuck in a loop Session::set('linkaccount', false); $this->event->stop(); return; } // Tmp users if (User::get('tmp_user')) { Request::setVar('option', 'com_members'); Request::setVar('controller', 'register'); Request::setVar('task', 'create'); Request::setVar('act', ''); $this->event->stop(); } else { if (substr(User::get('email'), -8) == '@invalid') { $usersConfig = Component::params('com_users'); $simpleRegistration = $usersConfig->get('simple_registration', false); if (Session::get('linkaccount', true) && !$simpleRegistration) { Request::setVar('option', 'com_users'); Request::setVar('view', 'link'); } else { Request::setVar('option', 'com_members'); Request::setVar('controller', 'register'); Request::setVar('task', 'update'); Request::setVar('act', ''); } $this->event->stop(); } else { // Does the user even have access to the profile plugin? // If not, then we can't redirect them there $plugin = Plugin::byType('members', 'profile'); if (!empty($plugin)) { Request::setVar('option', 'com_members'); Request::setVar('task', 'view'); Request::setVar('id', User::get('id')); Request::setVar('active', 'profile'); $this->event->stop(); } else { // Nothing else we can do, so let them go // and mark the incompleteness state so we don't // keep checking on every page load Session::get('registration.incomplete', false); } } } } } }
/** * 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 onLoginUser($user, $options = array()) { jimport('joomla.user.helper'); $xuser = User::getRoot(); // get user from session (might be tmp_user, can't fetch from db) if ($xuser->get('guest')) { // joomla user plugin hasn't run or something went very badly $plugins = Plugin::byType('user'); $xuser_order = false; $joomla_order = false; $i = 0; foreach ($plugins as $plugin) { if ($plugin->name == 'xusers') { $xuser_order = $i; } if ($plugin->name == 'joomla') { $joomla_order = $i; } $i++; } if ($joomla_order === false) { return new Exception(Lang::txt('E_JOOMLA_USER_PLUGIN_MISCONFIGURED'), 500); } if ($xuser_order <= $joomla_order) { return new Exception(Lang::txt('E_HUBZERO_USER_PLUGIN_MISCONFIGURED'), 500); } return new Exception(Lang::txt('E_JOOMLA_USER_PLUGIN_FAILED'), 500); } // log login to auth log Log::auth($xuser->get('id') . ' [' . $xuser->get('username') . '] ' . $_SERVER['REMOTE_ADDR'] . ' login'); // correct apache log data apache_note('auth', 'login'); // Log attempt to the database Hubzero\User\User::oneOrFail($xuser->get('id'))->logger()->auth()->save(['username' => $xuser->get('username'), 'status' => 'success']); // update session tracking with new data $session = App::get('session'); $session->set('tracker.user_id', $xuser->get('id')); $session->set('tracker.username', $xuser->get('username')); if ($session->get('tracker.sid') == '') { $session->set('tracker.sid', $session->getId()); } $session->set('tracker.psid', $session->get('tracker.sid')); if ($session->get('tracker.rsid') == '') { $session->set('tracker.rsid', $session->getId()); } if ($session->get('tracker.user_id') != $xuser->get('id') || $session->get('tracker.ssid') == '') { $session->set('tracker.ssid', $session->getId()); } if (empty($user['type'])) { $session->clear('session.authenticator'); } else { $session->set('session.authenticator', $user['type']); } if (isset($options['silent']) && $options['silent']) { $session->set('session.source', 'cookie'); } else { $session->set('session.source', 'user'); } // update tracking data with changes related to login jimport('joomla.utilities.utility'); $hash = App::hash(App::get('client')->name . ':tracker'); $key = \App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $tracker = array(); $tracker['user_id'] = $session->get('tracker.user_id'); $tracker['username'] = $session->get('tracker.username'); $tracker['sid'] = $session->getId(); $tracker['rsid'] = $session->get('tracker.rsid', $tracker['sid']); $tracker['ssid'] = $session->get('tracker.ssid', $tracker['sid']); $cookie = $crypt->encrypt(serialize($tracker)); $lifetime = time() + 365 * 24 * 60 * 60; // Determine whether cookie should be 'secure' or not $secure = false; $forceSsl = \Config::get('force_ssl', false); if (\App::isAdmin() && $forceSsl >= 1) { $secure = true; } else { if (\App::isSite() && $forceSsl == 2) { $secure = true; } } setcookie($hash, $cookie, $lifetime, '/', '', $secure, true); /* Mark registration as incomplete so it gets checked on next page load */ $username = $xuser->get('username'); if (isset($user['auth_link']) && is_object($user['auth_link'])) { $hzal = $user['auth_link']; } else { $hzal = null; } if ($xuser->get('tmp_user')) { $email = $xuser->get('email'); if ($username[0] == '-') { $username = trim($username, '-'); if ($hzal) { $xuser->set('username', 'guest;' . $username); $xuser->set('email', $hzal->email); } } } else { if ($username[0] == '-') { $username = trim($username, '-'); if ($hzal) { $hzal->user_id = $xuser->get('id'); $hzal->update(); } } } if ($hzal) { $xuser->set('auth_link_id', $hzal->id); $session->set('linkaccount', true); } $session->set('registration.incomplete', true); // Check if quota exists for the user $params = Component::params('com_members'); if ($params->get('manage_quotas', false)) { require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'users_quotas.php'; require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'quotas_classes.php'; $quota = new \Components\Members\Tables\UsersQuotas($this->database); $quota->load(array('user_id' => $xuser->get('id'))); if (!$quota->id) { $class = new \Components\Members\Tables\QuotasClasses($this->database); $class->load(array('alias' => 'default')); if ($class->id) { $quota->set('user_id', $xuser->get('id')); $quota->set('class_id', $class->id); $quota->set('soft_blocks', $class->soft_blocks); $quota->set('hard_blocks', $class->hard_blocks); $quota->set('soft_files', $class->soft_files); $quota->set('hard_files', $class->hard_files); $quota->store(); } } else { if ($quota->class_id) { // Here, we're checking to make sure their class matches their actual quota values $class = new \Components\Members\Tables\QuotasClasses($this->database); $class->load($quota->class_id); if ($quota->get('soft_blocks') != $class->get('soft_blocks') || $quota->get('hard_blocks') != $class->get('hard_blocks') || $quota->get('soft_files') != $class->get('soft_files') || $quota->get('hard_files') != $class->get('hard_files')) { $quota->set('user_id', $xuser->get('id')); $quota->set('class_id', $class->id); $quota->set('soft_blocks', $class->soft_blocks); $quota->set('hard_blocks', $class->hard_blocks); $quota->set('soft_files', $class->soft_files); $quota->set('hard_files', $class->hard_files); $quota->store(); } } } } return true; }
/** * @since 1.6 */ public function onContentBeforeDisplay($context, &$row, &$params, $page = 0) { $view = Request::getCmd('view'); $print = Request::getBool('print'); if ($print) { return false; } if ($params->get('show_item_navigation') && $context == 'com_content.article' && $view == 'article') { $html = ''; $db = App::get('db'); $nullDate = $db->getNullDate(); $date = Date::of('now'); $now = $date->toSql(); $uid = $row->id; $option = 'com_content'; $canPublish = User::authorise('core.edit.state', $option . '.article.' . $row->id); // The following is needed as different menu items types utilise a different param to control ordering. // For Blogs the `orderby_sec` param is the order controlling param. // For Table and List views it is the `orderby` param. $params_list = $params->toArray(); if (array_key_exists('orderby_sec', $params_list)) { $order_method = $params->get('orderby_sec', ''); } else { $order_method = $params->get('orderby', ''); } // Additional check for invalid sort ordering. if ($order_method == 'front') { $order_method = ''; } // Determine sort order. switch ($order_method) { case 'date': $orderby = 'a.created'; break; case 'rdate': $orderby = 'a.created DESC'; break; case 'alpha': $orderby = 'a.title'; break; case 'ralpha': $orderby = 'a.title DESC'; break; case 'hits': $orderby = 'a.hits'; break; case 'rhits': $orderby = 'a.hits DESC'; break; case 'order': $orderby = 'a.ordering'; break; case 'author': $orderby = 'a.created_by_alias, u.name'; break; case 'rauthor': $orderby = 'a.created_by_alias DESC, u.name DESC'; break; case 'front': $orderby = 'f.ordering'; break; default: $orderby = 'a.ordering'; break; } $xwhere = ' AND (a.state = 1 OR a.state = -1)' . ' AND (publish_up = ' . $db->Quote($nullDate) . ' OR publish_up <= ' . $db->Quote($now) . ')' . ' AND (publish_down = ' . $db->Quote($nullDate) . ' OR publish_down >= ' . $db->Quote($now) . ')'; // Array of articles in same category correctly ordered. $query = $db->getQuery(true); //sqlsrv changes $case_when = ' CASE WHEN '; $case_when .= $query->charLength('a.alias'); $case_when .= ' THEN '; $a_id = $query->castAsChar('a.id'); $case_when .= $query->concatenate(array($a_id, 'a.alias'), ':'); $case_when .= ' ELSE '; $case_when .= $a_id . ' END as slug'; $case_when1 = ' CASE WHEN '; $case_when1 .= $query->charLength('cc.alias'); $case_when1 .= ' THEN '; $c_id = $query->castAsChar('cc.id'); $case_when1 .= $query->concatenate(array($c_id, 'cc.alias'), ':'); $case_when1 .= ' ELSE '; $case_when1 .= $c_id . ' END as catslug'; $query->select('a.id, a.language,' . $case_when . ',' . $case_when1); $query->from('#__content AS a'); $query->leftJoin('#__categories AS cc ON cc.id = a.catid'); $query->where('a.catid = ' . (int) $row->catid . ' AND a.state = ' . (int) $row->state . ($canPublish ? '' : ' AND a.access = ' . (int) $row->access) . $xwhere); $query->order($orderby); if (\App::isSite() && \App::get('language.filter')) { $query->where('a.language in (' . $db->quote(Lang::getTag()) . ',' . $db->quote('*') . ')'); } $db->setQuery($query); $list = $db->loadObjectList('id'); // This check needed if incorrect Itemid is given resulting in an incorrect result. if (!is_array($list)) { $list = array(); } reset($list); // Location of current content item in array list. $location = array_search($uid, array_keys($list)); $rows = array_values($list); $row->prev = null; $row->next = null; if ($location - 1 >= 0) { // The previous content item cannot be in the array position -1. $row->prev = $rows[$location - 1]; } if ($location + 1 < count($rows)) { // The next content item cannot be in an array position greater than the number of array postions. $row->next = $rows[$location + 1]; } $pnSpace = ""; if (Lang::txt('JGLOBAL_LT') || Lang::txt('JGLOBAL_GT')) { $pnSpace = " "; } if ($row->prev) { $row->prev = Route::url(ContentHelperRoute::getArticleRoute($row->prev->slug, $row->prev->catslug, $row->prev->language)); } else { $row->prev = ''; } if ($row->next) { $row->next = Route::url(ContentHelperRoute::getArticleRoute($row->next->slug, $row->next->catslug, $row->next->language)); } else { $row->next = ''; } // Output. if ($row->prev || $row->next) { $html = ' <ul class="pagenav">'; if ($row->prev) { $html .= ' <li class="pagenav-prev"> <a href="' . $row->prev . '" rel="prev">' . Lang::txt('JGLOBAL_LT') . $pnSpace . Lang::txt('JPREV') . '</a> </li>'; } if ($row->next) { $html .= ' <li class="pagenav-next"> <a href="' . $row->next . '" rel="next">' . Lang::txt('JNEXT') . $pnSpace . Lang::txt('JGLOBAL_GT') . '</a> </li>'; } $html .= ' </ul>'; $row->pagination = $html; $row->paginationposition = $this->params->get('position', 1); // This will default to the 1.5 and 1.6-1.7 behavior. $row->paginationrelative = $this->params->get('relative', 0); } } return; }
/** * This method adds alternate meta tags for associated menu items * * @return nothing * @since 1.7 */ public function onAfterDispatch() { if (App::isSite() && $this->params->get('alternate_meta') && Document::getType() == 'html') { // Get active menu item $active = App::get('menu')->getActive(); if (!$active) { return; } // Get menu item link if (Config::get('sef')) { $active_link = Route::url('index.php?Itemid=' . $active->id, false); } else { $active_link = Route::url($active->link . '&Itemid=' . $active->id, false); } if ($active_link == JUri::base(true) . '/') { $active_link .= 'index.php'; } // Get current link $current_link = Request::getUri(); if ($current_link == Request::base(true) . '/') { $current_link .= 'index.php'; } // Check the exact menu item's URL if ($active_link == $current_link) { // Get menu item associations JLoader::register('MenusHelper', PATH_CORE . '/components/com_menus/admin/helpers/menus.php'); $associations = MenusHelper::getAssociations($active->id); // Remove current menu item unset($associations[$active->language]); // Associated menu items in other languages if ($associations && $this->params->get('menu_associations')) { $menu = App::get('menu'); $server = JURI::getInstance()->toString(array('scheme', 'host', 'port')); foreach (JLanguageHelper::getLanguages() as $language) { if (isset($associations[$language->lang_code])) { $item = $menu->getItem($associations[$language->lang_code]); if ($item && Lang::exists($language->lang_code)) { if (Config::get('sef')) { $link = Route::url('index.php?Itemid=' . $associations[$language->lang_code] . '&lang=' . $language->sef); } else { $link = Route::url($item->link . '&Itemid=' . $associations[$language->lang_code] . '&lang=' . $language->sef); } // Check if language is the default site language and remove url language code is on if ($language->sef == self::$default_sef && $this->params->get('remove_default_prefix') == '1') { $relLink = preg_replace('|/' . $language->sef . '/|', '/', $link, 1); Document::addHeadLink($server . $relLink, 'alternate', 'rel', array('hreflang' => $language->lang_code)); } else { Document::addHeadLink($server . $link, 'alternate', 'rel', array('hreflang' => $language->lang_code)); } } } } } elseif ($active->home) { $menu = App::get('menu'); $server = JURI::getInstance()->toString(array('scheme', 'host', 'port')); foreach (JLanguageHelper::getLanguages() as $language) { $item = $menu->getDefault($language->lang_code); if ($item && $item->language != $active->language && $item->language != '*' && JLanguage::exists($language->lang_code)) { if (Config::get('sef')) { $link = Route::url('index.php?Itemid=' . $item->id . '&lang=' . $language->sef); } else { $link = Route::url($item->link . '&Itemid=' . $item->id . '&lang=' . $language->sef); } // Check if language is the default site language and remove url language code is on if ($language->sef == self::$default_sef && $this->params->get('remove_default_prefix') == '1') { $relLink = preg_replace('|/' . $language->sef . '/|', '/', $link, 1); Document::addHeadLink($server . $relLink, 'alternate', 'rel', array('hreflang' => $language->lang_code)); } else { Document::addHeadLink($server . $link, 'alternate', 'rel', array('hreflang' => $language->lang_code)); } } } } } } }
if (\App::get('config')->get('sef_suffix') && !(substr($route, -9) == 'index.php' || substr($route, -1) == '/')) { if ($format = $uri->getVar('format', 'html')) { $route .= '.' . $format; $uri->delVar('format'); } } if (\App::get('config')->get('sef_rewrite')) { if ($route == 'index.php') { $route = ''; } else { $route = str_replace('index.php/', '', $route); } } // Add basepath to the uri $base = \App::get('request')->base(true); if (!\App::isSite()) { $base = '/' . ltrim(substr(ltrim($base, '/'), strlen(\App::get('client')->name)), '/'); } $uri->setPath($base . '/' . $route); return $uri; }); /* | SEF Groups | | Remove the base URI path. This will strip everything up to the bas */ $router->rules('build')->append('groups', function ($uri) { if (!empty($_SERVER['REWROTE_FROM'])) { if (stripos($uri->toString(), $_SERVER['REWROTE_TO']->getPath()) !== false) { $uri->setPath(str_replace($_SERVER['REWROTE_TO']->getPath(), '', $uri->getPath())); $uri->setHost($_SERVER['REWROTE_FROM']->getHost());
/** * Gets menu items by attribute * * @param string $attributes The field name * @param string $values The value of the field * @param boolean $firstonly If true, only returns the first item found * @return array */ public function getItems($attributes, $values, $firstonly = false) { $attributes = (array) $attributes; $values = (array) $values; if (\App::isSite()) { // Filter by language if not set if (($key = array_search('language', $attributes)) === false) { if (\App::get('language.filter')) { $attributes[] = 'language'; $values[] = array(\App::get('language')->getTag(), '*'); } } elseif ($values[$key] === null) { unset($attributes[$key]); unset($values[$key]); } // Filter by access level if not set if (($key = array_search('access', $attributes)) === false) { $attributes[] = 'access'; $values[] = \User::getAuthorisedViewLevels(); } elseif ($values[$key] === null) { unset($attributes[$key]); unset($values[$key]); } } return parent::getItems($attributes, $values, $firstonly); }