Beispiel #1
0
 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());
             }
         }
     }
 }
Beispiel #2
0
 /**
  * This method should handle any logout logic and report back to the subject
  *
  * @param   array   $user     Holds the user data.
  * @param   array   $options  Array holding options (client, ...).
  * @return  object  True on success
  */
 public function onUserLogout($user, $options = array())
 {
     if (App::isSite()) {
         // Create the cookie
         $hash = App::hash('plgSystemLogout');
         $cookie_domain = Config::get('config.cookie_domain', '');
         $cookie_path = Config::get('config.cookie_path', '/');
         setcookie($hash, true, time() + 86400, $cookie_path, $cookie_domain);
     }
     return true;
 }
Beispiel #3
0
 /**
  * Retrieve a cookie
  *
  * @param  (string) $namespace - make sure the cookie name is unique
  * @return (object) $cookie data
  **/
 public static function eat($namespace)
 {
     $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));
     if ($str = \App::get('request')->getString($hash, '', 'cookie', JREQUEST_ALLOWRAW | JREQUEST_NOTRIM)) {
         $sstr = $crypt->decrypt($str);
         $cookie = @unserialize($sstr);
         return (object) $cookie;
     }
     return false;
 }
Beispiel #4
0
 public function createSession($user)
 {
     if (empty($user)) {
         return;
     }
     try {
         Db::begin();
         $user->last_login = Db::now();
         $user->store();
         $session = Orm::collection('Session')->load();
         $session->user = $user;
         $session->token = App::hash(uniqid(rand(), true));
         $session->store();
         Db::commit();
     } catch (Exception $e) {
         Db::rollback();
         throw $e;
     }
     return $session->token;
 }
Beispiel #5
0
 /**
  * Send out local password set confirmation token
  *
  * @return void - redirect to confirm token view
  */
 private function sendtoken()
 {
     // Import helpers/classes
     jimport('joomla.mail.helper');
     jimport('joomla.user.helper');
     // Make sure they're logged in
     if ($this->user->get('guest')) {
         App::redirect(Route::url('index.php?option=com_users&view=login&return=' . base64_encode(Route::url('index.php?option=' . $this->option . '&task=myaccount&active=account&action=sendtoken'))), Lang::txt('You must be a logged in to access this area.'), 'warning');
         return;
     }
     // Make sure this is an auth link account (i.e. no password set)
     $hzup = \Hubzero\User\Password::getInstance($this->member->get('uidNumber'));
     if (!empty($hzup->passhash)) {
         App::abort(404, Lang::txt('PLG_MEMBERS_ACCOUNT_NOT_LINKED_ACCOUNT'));
         return;
     }
     // Generate a new random token and hash it
     $token = App::hash(JUserHelper::genRandomPassword());
     $salt = JUserHelper::getSalt('crypt-md5');
     $hashedToken = md5($token . $salt) . ':' . $salt;
     // Store the hashed token
     $this->setToken($hashedToken);
     // Send the email with the token
     $this->sendEmail($token);
     // Redirect user to confirm token view page
     App::redirect(Route::url($this->member->getLink() . '&active=account&task=confirmtoken'), Lang::txt('Please check the email associated with this account (' . $this->member->get('email') . ') for your confirmation token!'), 'warning');
     return;
 }
Beispiel #6
0
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * HUBzero is a registered trademark of Purdue University.
 *
 * @package   hubzero-cms
 * @author    Sam Wilson <*****@*****.**>
 * @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
 * @license   http://opensource.org/licenses/MIT MIT
 */
// no direct access
defined('_HZEXEC_') or die;
$hash = App::hash(App::get('client')->name . ':authenticator');
if (($cookie = \Hubzero\Utility\Cookie::eat('authenticator')) && !Request::getInt('reset', false)) {
    $primary = $cookie->authenticator;
    $user = User::getInstance($cookie->user_id);
    $user_img = $cookie->user_img;
    Request::setVar('primary', $primary);
}
$usersConfig = Component::params('com_members');
$primary = Request::getWord('primary', false);
// use some reflections to inspect plugins for special behavior (added for shibboleth)
$refl = array();
foreach ($authenticators as $a) {
    $refl[$a['name']] = new \ReflectionClass("plgAuthentication{$a['name']}");
}
$current = Hubzero\Utility\Uri::getInstance()->toString();
$current .= strstr($current, '?') ? '&' : '?';
Beispiel #7
0
 /**
  * Method to determine a hash for anti-spoofing variable names
  *
  * @param   boolean  $forceNew  If true, force a new token to be created
  * @return  string   Hashed var name
  */
 public static function getFormToken($forceNew = false)
 {
     $hash = \App::hash(\User::get('id', 0) . \App::get('session')->getToken($forceNew));
     return $hash;
 }
Beispiel #8
0
 public function getUserByCredentials($login, $password)
 {
     return $this->driver->getUserByCredentials($login, App::hash($password));
 }
Beispiel #9
0
 /**
  * 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;
 }
Beispiel #10
0
        foreach ($a as $b) {
            if (strstr($b, ':')) {
                $b = explode(':', $b);
                $bits[] = trim($b[0]) . '="' . trim($b[1]) . '"';
            }
        }
    }
    $attributes = implode(' ', $bits);
}
// Formats that can be previewed via Google viewer
$docs = array('pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pages', 'ai', 'psd', 'tiff', 'dxf', 'eps', 'ps', 'ttf', 'xps', 'svg');
$html5video = array("mp4", "m4v", "webm", "ogv");
$token = '';
if (!User::isGuest()) {
    $session_id = App::get('session')->getId();
    $key = App::hash(@$_SERVER['HTTP_USER_AGENT']);
    $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key));
    $token = base64_encode($crypter->encrypt($session_id));
}
$downloadUrl = Route::url('index.php?option=com_publications&id=' . $this->publication->id . '&task=serve&aid=' . $this->aid . '&render=download&token=' . $token);
$viewUrl = Route::url('index.php?option=com_publications&id=' . $this->publication->id . '&task=serve&aid=' . $this->aid . '&render=download&disposition=inline&token=' . $token);
?>
<div class="sample">
	<p><?php 
echo Lang::txt('COM_PUBLICATIONS_PUBLICATION') . ': <strong>' . $this->publication->title . '</strong>';
?>
 <?php 
if ($this->primary->role != 1) {
    echo '&nbsp;&nbsp; Supporting Doc: <strong>' . $this->primary->path . '</strong>';
}
?>
Beispiel #11
0
 /**
  * Get the encrypter utility
  *
  * @return  void
  */
 protected static function getEncrypter()
 {
     $key = \App::hash(@$_SERVER['HTTP_USER_AGENT']);
     $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key));
     return $crypt;
 }
Beispiel #12
0
 /**
  * Get session id from cookie
  *
  * [!] This will determine if the user has an active session via browser
  * 
  * @return  bool  Result of test
  */
 public function getSessionIdFromCookie()
 {
     // get session id key name
     $sessionName = md5(\App::hash('site'));
     // return session id stored in cookie
     return !empty($_COOKIE[$sessionName]) ? $_COOKIE[$sessionName] : null;
 }
Beispiel #13
0
 /**
  * Generate a Windows tool invoke URL to redirect to
  *
  * @param   string  $option  Name of the component
  * @return  void
  */
 public function invoke($option)
 {
     $no_html = Request::getInt('no_html', 0);
     $response = new StdClass();
     $response->success = false;
     $response->message = Lang::txt('No invoke URL found.');
     // Check for an imconing token.
     if ($token = Request::getVar('token', '', 'get')) {
         $dtoken = base64_decode($token);
         $key = App::hash(@$_SERVER['HTTP_USER_AGENT']);
         $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key));
         $session_id = $crypter->decrypt($dtoken);
         $session = \Hubzero\Session\Helper::getSession($session_id);
         $user = User::getInstance($session->userid);
         $user->set('guest', 0);
         $user->set('id', $session->userid);
         $user->set('username', $session->username);
         $ip = $session->ip;
     } else {
         $user = User::getInstance();
         $ip = Request::ip();
     }
     // Is the user validated?
     if ($user->isGuest()) {
         $response->message = Lang::txt('Login is required to perform this action.');
     } else {
         $appid = Request::getVar('appid');
         // Generate the URL
         $url = $this->generateInvokeUrl($option, $appid, $user, $ip);
         if ($url) {
             if (!$token) {
                 $session = App::get('session');
                 $session_id = $session->getId();
                 $key = App::hash(@$_SERVER['HTTP_USER_AGENT']);
                 $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key));
                 $token = base64_encode($crypter->encrypt($session_id));
             }
             $rurl = rtrim($this->params->get('invoke_url', 'http://wapps.hubzero.org'), '/') . '/v1?';
             //standaloneUrl=' . $url;
             $params = array();
             $params[] = 'token=' . $token;
             if ($appid) {
                 $params[] = 'appid=' . $appid;
             }
             $params[] = 'standaloneUrl=' . $url;
             $rurl .= implode('&', $params);
             $response->success = true;
             $response->message = $rurl;
             if (!$no_html) {
                 $this->view('invoke', 'display')->set('url', $rurl)->set('rurl', $_SERVER['HTTP_REFERER'])->display();
                 exit;
                 App::redirect($url);
             }
         }
     }
     if (!$no_html) {
         App::abort(404, Lang::txt('No invoke URL found.'));
     }
     $response = json_encode($response);
     if ($callback = Request::getVar('callback')) {
         $response = $callback . '(' . $response . ')';
     }
     echo $response;
     exit;
 }
Beispiel #14
0
 /**
  * Get the encrypter utility
  *
  * @return  void
  */
 protected static function getEncrypter()
 {
     $key = \App::hash('newletter');
     $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key));
     return $crypt;
 }
Beispiel #15
0
 /**
  * Provides a secure hash based on a seed
  *
  * @param   string  $seed  Seed string.
  *
  * @return  string  A secure hash
  *
  * @since   11.1
  */
 public static function getHash($seed)
 {
     if (class_exists('\\App')) {
         return \App::hash($seed);
     }
     return md5(JFactory::getConfig()->get('secret') . $seed);
 }
Beispiel #16
0
 /**
  * Get cookie value
  *
  * @param string $key name of the cookie
  * @return string|false cookie value or false if cookie is invalid or doesn't exists
  * @static
  */
 public static function getCookie($key)
 {
     if (!isset($_COOKIE[$key])) {
         return false;
     }
     $cookie_val = $_COOKIE[$key];
     if (strpos($cookie_val, '~~') !== false) {
         list($cookie_hash, $cookie_val) = explode('~~', $cookie_val);
         if (!strlen($cookie_hash) && !strlen($cookie_val)) {
             return false;
         }
         $cookie_secret = Config::getVar('secret_key');
         if (!$cookie_secret) {
             throw new BakedCarrotException('Cannot set cookie without "secret_key" parameter');
         }
         if (extension_loaded('mcrypt')) {
             $cookie_val = base64_decode($cookie_val);
             $iv_size = mcrypt_get_iv_size(self::$mcrypt_cipher, self::$mcrypt_mode);
             $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
             $cookie_val = mcrypt_decrypt(self::$mcrypt_cipher, Config::getVar('secret_key'), $cookie_val, self::$mcrypt_mode, $iv);
             $cookie_val = rtrim($cookie_val, "");
         }
         $hash_to_test = App::hash($key . $cookie_val . $cookie_secret);
         if ($hash_to_test != $cookie_hash) {
             self::deleteCookie($key);
             $cookie_val = false;
         }
     }
     return $cookie_val;
 }
Beispiel #17
0
 /**
  * Add a vote to an option
  */
 public function voteTask()
 {
     // Check for request forgeries
     Request::checkToken();
     $poll_id = Request::getVar('id', 0, '', 'int');
     $option_id = Request::getVar('voteid', 0, 'post', 'int');
     $poll = new Poll($this->database);
     if (!$poll->load($poll_id) || $poll->published != 1) {
         throw new Exception(Lang::txt('JERROR_ALERTNOAUTHOR'), 404);
     }
     $cookieName = \App::hash(\App::get('client')->name . 'poll' . $poll_id);
     // ToDo - may be adding those information to the session?
     $voted = Request::getVar($cookieName, '0', 'COOKIE', 'INT');
     if ($voted || !$option_id) {
         if ($voted) {
             $msg = Lang::txt('COM_POLL_ALREADY_VOTED');
         }
         if (!$option_id) {
             $msg = Lang::txt('COM_POLL_WARNSELECT');
         }
     } else {
         // 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($cookieName, '1', time() + $poll->lag, '/', '', $secure, true);
         $poll->vote($poll_id, $option_id);
         $msg = Lang::txt('COM_POLL_THANK_YOU');
     }
     // set Itemid id for links
     $menu = \App::get('menu');
     $items = $menu->getItems('link', 'index.php?option=com_poll&view=poll');
     $itemid = isset($items[0]) ? '&Itemid=' . $items[0]->id : '';
     App::redirect(Route::url('index.php?option=com_poll&id=' . $poll_id . ':' . $poll->alias . $itemid, false), $msg);
 }
 /**
  * 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
  * @since	1.5
  */
 public function onUserLogin($user, $options = array())
 {
     $app = JFactory::getApplication();
     $menu = App::get('menu');
     if (App::isSite() && $this->params->get('automatic_change', 1)) {
         // Load associations
         $assoc = isset($app->menu_associations) ? $app->menu_associations : 0;
         if ($assoc) {
             $active = $menu->getActive();
             if ($active) {
                 $associations = MenusHelper::getAssociations($active->id);
             }
         }
         $lang_code = $user['language'];
         if (empty($lang_code)) {
             $lang_code = self::$default_lang;
         }
         if ($lang_code != self::$tag) {
             // Change language
             self::$tag = $lang_code;
             // Create a cookie
             $cookie_domain = Config::get('cookie_domain', '');
             $cookie_path = Config::get('cookie_path', '/');
             setcookie(App::hash('language'), $lang_code, $this->getLangCookieTime(), $cookie_path, $cookie_domain);
             // Change the language code
             Lang::setLanguage($lang_code);
             // Change the redirect (language have changed)
             if (isset($associations[$lang_code]) && $menu->getItem($associations[$lang_code])) {
                 $itemid = $associations[$lang_code];
                 User::setState('users.login.form.return', 'index.php?&Itemid=' . $itemid);
             } else {
                 $itemid = isset(self::$homes[$lang_code]) ? self::$homes[$lang_code]->id : self::$homes['*']->id;
                 User::setState('users.login.form.return', 'index.php?&Itemid=' . $itemid);
             }
         }
     }
 }
Beispiel #19
0
 /**
  * Hook for after app initialization
  *
  * @return   void
  */
 public function onAfterInitialise()
 {
     // Get the session object
     $session = App::get('session');
     if ($session->isNew()) {
         $tracker = array();
         // Transfer tracking cookie data to session
         jimport('joomla.utilities.utility');
         jimport('joomla.user.helper');
         $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));
         if ($str = Request::getString($hash, '', 'cookie', 1 | 2)) {
             $sstr = $crypt->decrypt($str);
             $tracker = @unserialize($sstr);
             if ($tracker === false) {
                 //Create the encryption key, apply extra hardening using the user agent string
                 $key = App::hash(@$_SERVER['HTTP_USER_AGENT']);
                 $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key));
                 $sstr = $crypt->decrypt($str);
                 $tracker = @unserialize($sstr);
             }
         }
         if (!is_array($tracker)) {
             $tracker = array();
         }
         if (empty($tracker['user_id'])) {
             $session->clear('tracker.user_id');
         } else {
             $session->set('tracker.user_id', $tracker['user_id']);
         }
         if (empty($tracker['username'])) {
             $session->clear('tracker.username');
         } else {
             $session->set('tracker.username', $tracker['username']);
         }
         if (empty($tracker['sid'])) {
             $session->clear('tracker.psid');
         } else {
             $session->set('tracker.psid', $tracker['sid']);
         }
         $session->set('tracker.sid', $session->getId());
         if (empty($tracker['ssid'])) {
             $session->set('tracker.ssid', $session->getId());
         } else {
             $session->set('tracker.ssid', $tracker['ssid']);
         }
         if (empty($tracker['rsid'])) {
             $session->set('tracker.rsid', $session->getId());
         } else {
             $session->set('tracker.rsid', $tracker['rsid']);
         }
         // log tracking cookie detection to auth log
         $username = empty($tracker['username']) ? '-' : $tracker['username'];
         $user_id = empty($tracker['user_id']) ? 0 : $tracker['user_id'];
         App::get('log')->logger('auth')->info($username . ' ' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '') . ' detect');
         // set new tracking cookie with current data
         $tracker = array();
         $tracker['user_id'] = $session->get('tracker.user_id');
         $tracker['username'] = $session->get('tracker.username');
         $tracker['sid'] = $session->get('tracker.sid');
         $tracker['rsid'] = $session->get('tracker.rsid');
         $tracker['ssid'] = $session->get('tracker.ssid');
         $cookie = $crypt->encrypt(serialize($tracker));
         $lifetime = time() + 365 * 24 * 60 * 60 * 10;
         // 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);
     }
     // all page loads set apache log data
     if (strpos(php_sapi_name(), 'apache') !== false) {
         apache_note('jsession', $session->getId());
         if (User::get('id') != 0) {
             apache_note('auth', 'session');
             apache_note('userid', User::get('id'));
         } else {
             if (!empty($tracker['user_id'])) {
                 apache_note('auth', 'cookie');
                 apache_note('userid', $tracker['user_id']);
                 apache_note('tracker', $tracker['rsid']);
             }
         }
     }
 }
Beispiel #20
0
 /**
  * Method to start the password reset process.
  *
  * @since	1.6
  */
 public function processResetRequest($data)
 {
     // Get the form.
     $form = $this->getForm();
     // Check for an error.
     if ($form instanceof Exception) {
         return $form;
     }
     // Filter and validate the form data.
     $data = $form->filter($data);
     $return = $form->validate($data);
     // Check for an error.
     if ($return instanceof Exception) {
         return $return;
     }
     // Check the validation results.
     if ($return === false) {
         // Get the validation messages from the form.
         foreach ($form->getErrors() as $message) {
             $this->setError($message);
         }
         return false;
     }
     // Find the user id for the given username
     $db = $this->getDbo();
     $query = $db->getQuery(true);
     $query->select('id');
     $query->from($db->quoteName('#__users'));
     $query->where($db->quoteName('username') . ' = ' . $db->Quote($data['username']));
     // Get the user object.
     $db->setQuery((string) $query);
     $userId = $db->loadResult();
     // Check for an error.
     if ($db->getErrorNum()) {
         $this->setError(Lang::txt('COM_USERS_DATABASE_ERROR', $db->getErrorMsg()), 500);
         return false;
     }
     // Check for a user.
     if (empty($userId)) {
         $this->setError(Lang::txt('COM_USERS_INVALID_USERNAME'));
         return false;
     }
     // Get the user object.
     $user = JUser::getInstance($userId);
     // Make sure the user isn't blocked.
     if ($user->block) {
         $this->setError(Lang::txt('COM_USERS_USER_BLOCKED'));
         return false;
     }
     // Make sure the user isn't a Super Admin.
     if ($user->authorise('core.admin')) {
         $this->setError(Lang::txt('COM_USERS_REMIND_SUPERADMIN_ERROR'));
         return false;
     }
     // Make sure the user has not exceeded the reset limit
     if (!$this->checkResetLimit($user)) {
         $resetLimit = (int) JFactory::getApplication()->getParams()->get('reset_time');
         $this->setError(Lang::txts('COM_USERS_REMIND_LIMIT_ERROR_N_HOURS', $resetLimit));
         return false;
     }
     // Set the confirmation token.
     $token = App::hash(JUserHelper::genRandomPassword());
     $salt = JUserHelper::getSalt('crypt-md5');
     $hashedToken = md5($token . $salt) . ':' . $salt;
     $user->activation = $hashedToken;
     // Save the user to the database.
     if (!$user->save(true)) {
         return new Exception(Lang::txt('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500);
     }
     // Assemble the password reset confirmation link.
     $mode = Config::get('force_ssl', 0) == 2 ? 1 : -1;
     $itemid = UsersHelperRoute::getLoginRoute();
     $itemid = $itemid !== null ? '&Itemid=' . $itemid : '';
     $link = 'index.php?option=com_users&view=reset&layout=confirm' . $itemid;
     // Put together the email template data.
     $data = $user->getProperties();
     $data['fromname'] = Config::get('fromname');
     $data['mailfrom'] = Config::get('mailfrom');
     $data['sitename'] = Config::get('sitename');
     $data['link_text'] = Route::url($link, false, $mode);
     $data['link_html'] = Route::url($link, true, $mode);
     $data['token'] = $token;
     $subject = Lang::txt('COM_USERS_EMAIL_PASSWORD_RESET_SUBJECT', $data['sitename']);
     $body = Lang::txt('COM_USERS_EMAIL_PASSWORD_RESET_BODY', $data['sitename'], $data['token'], $data['link_text']);
     // Send the password reset request email.
     $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body);
     // Check for an error.
     if ($return !== true) {
         return new Exception(Lang::txt('COM_USERS_MAIL_FAILED'), 500);
     }
     // Push the user data into the session.
     $app = JFactory::getApplication();
     $app->setUserState('com_users.reset.user', $user->id);
     return true;
 }
 /**
  * Method to save the form data.
  *
  * @param	array		The form data.
  * @return	mixed		The user id on success, false on failure.
  * @since	1.6
  */
 public function register($temp)
 {
     $db = $this->getDbo();
     $params = Component::params('com_users');
     // Initialise the table with JUser.
     $user = new JUser();
     $data = (array) $this->getData();
     // Merge in the registration data.
     foreach ($temp as $k => $v) {
         $data[$k] = $v;
     }
     // Prepare the data for the user object.
     $data['email'] = $data['email1'];
     $data['password'] = $data['password1'];
     $useractivation = $params->get('useractivation');
     $sendpassword = $params->get('sendpassword', 1);
     // Check if the user needs to activate their account.
     if ($useractivation == 1 || $useractivation == 2) {
         $data['activation'] = App::hash(JUserHelper::genRandomPassword());
         $data['block'] = 1;
     }
     // Bind the data.
     if (!$user->bind($data)) {
         $this->setError(Lang::txt('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
         return false;
     }
     // Load the users plugin group.
     Plugin::import('user');
     // Store the data.
     if (!$user->save()) {
         $this->setError(Lang::txt('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
         return false;
     }
     // Compile the notification mail values.
     $data = $user->getProperties();
     $data['fromname'] = Config::get('fromname');
     $data['mailfrom'] = Config::get('mailfrom');
     $data['sitename'] = Config::get('sitename');
     $data['siteurl'] = Request::root();
     // Handle account activation/confirmation emails.
     if ($useractivation == 2) {
         // Set the link to confirm the user email.
         $uri = JURI::getInstance();
         $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
         $data['activate'] = $base . Route::url('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
         $emailSubject = Lang::txt('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
         if ($sendpassword) {
             $emailBody = Lang::txt('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'], $data['password_clear']);
         } else {
             $emailBody = Lang::txt('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username']);
         }
     } elseif ($useractivation == 1) {
         // Set the link to activate the user account.
         $uri = JURI::getInstance();
         $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
         $data['activate'] = $base . Route::url('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
         $emailSubject = Lang::txt('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
         if ($sendpassword) {
             $emailBody = Lang::txt('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'], $data['password_clear']);
         } else {
             $emailBody = Lang::txt('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username']);
         }
     } else {
         $emailSubject = Lang::txt('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
         $emailBody = Lang::txt('COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl']);
     }
     // Send the registration email.
     $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody);
     //Send Notification mail to administrators
     if ($params->get('useractivation') < 2 && $params->get('mail_to_admin') == 1) {
         $emailSubject = Lang::txt('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
         $emailBodyAdmin = Lang::txt('COM_USERS_EMAIL_REGISTERED_NOTIFICATION_TO_ADMIN_BODY', $data['name'], $data['username'], $data['siteurl']);
         // get all admin users
         $query = 'SELECT name, email, sendEmail' . ' FROM #__users' . ' WHERE sendEmail=1';
         $db->setQuery($query);
         $rows = $db->loadObjectList();
         // Send mail to all superadministrators id
         foreach ($rows as $row) {
             $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $row->email, $emailSubject, $emailBodyAdmin);
             // Check for an error.
             if ($return !== true) {
                 $this->setError(Lang::txt('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'));
                 return false;
             }
         }
     }
     // Check for an error.
     if ($return !== true) {
         $this->setError(Lang::txt('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'));
         // Send a system message to administrators receiving system mails
         $db = App::get('db');
         $q = "SELECT id\n\t\t\t\tFROM #__users\n\t\t\t\tWHERE block = 0\n\t\t\t\tAND sendEmail = 1";
         $db->setQuery($q);
         $sendEmail = $db->loadColumn();
         if (count($sendEmail) > 0) {
             $jdate = new \Hubzero\Utility\Date();
             // Build the query to add the messages
             $q = "INSERT INTO " . $db->quoteName('#__messages') . " (" . $db->quoteName('user_id_from') . ", " . $db->quoteName('user_id_to') . ", " . $db->quoteName('date_time') . ", " . $db->quoteName('subject') . ", " . $db->quoteName('message') . ") VALUES ";
             $messages = array();
             foreach ($sendEmail as $userid) {
                 $messages[] = "(" . $userid . ", " . $userid . ", '" . $jdate->toSql() . "', '" . Lang::txt('COM_USERS_MAIL_SEND_FAILURE_SUBJECT') . "', '" . Lang::txt('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']) . "')";
             }
             $q .= implode(',', $messages);
             $db->setQuery($q);
             $db->query();
         }
         return false;
     }
     if ($useractivation == 1) {
         return "useractivate";
     } elseif ($useractivation == 2) {
         return "adminactivate";
     } else {
         return $user->id;
     }
 }