/** * Set a property's value * * @param string $property Property name * @param mixed $value Property value * @return boolean True on success, False on error */ public function set($property, $value = null) { if ($property == 'password') { if ($value != '') { $this->userPassword = \Hubzero\User\Password::getPasshash($value); } else { $this->userPassword = ''; } $this->_password = $value; return true; } if ('_' == substr($property, 0, 1)) { $this->setError("Can't access private properties"); return false; } if (!property_exists(__CLASS__, $property)) { if (property_exists(__CLASS__, '_auxs_' . $property)) { $property = '_auxs_' . $property; } else { if (property_exists(__CLASS__, '_auxv_' . $property)) { $property = '_auxv_' . $property; } else { $this->setError("Unknown property: {$property}"); return false; } } } if ('_auxv_' == substr($property, 0, 6)) { if (empty($value)) { $value = array(); } else { if (!is_array($value)) { $value = array($value); } $list = array_unique($value); sort($list); unset($value); foreach ($list as $v) { $value[] = strval($v); } } } else { $value = strval($value); } $this->{$property} = $value; if ($property == 'userPassword') { $this->_password = ''; } return true; }
/** * Authenticate Subscription Requests * * @return void */ private function authenticateSubscriptionRequest() { $realm = '[' . Config::get('sitename') . '] Group Calendar: ' . $this->group->get('description'); if (empty($_SERVER['PHP_AUTH_USER'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="' . $realm . '"'); echo Lang::txt('You are not authorized to view this calendar.'); exit; } //get the username and password $httpBasicUsername = $_SERVER['PHP_AUTH_USER']; $httpBasicPassword = $_SERVER['PHP_AUTH_PW']; //make sure we have a username and password if (!isset($httpBasicUsername) || !isset($httpBasicPassword) || $httpBasicUsername == '' || $httpBasicPassword == '') { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="' . $realm . '"'); die(Lang::txt('You must enter a valid username and password.')); } //get the user based on username $sql = "SELECT u.id, u.username, up.passhash\n\t\t FROM #__users AS u, #__users_password AS up\n\t\t WHERE u.id=up.user_id\n\t\t AND u.username="******"' . $realm . '"'); die(Lang::txt('You must enter a valid username and password.')); } //make sure password matches stored password if (!\Hubzero\User\Password::comparePasswords($user->passhash, $httpBasicPassword)) { App::get('log')->logger('auth')->info($httpBasicUsername . ' ' . $_SERVER['REMOTE_ADDR'] . ' invalid group calendar subscription auth for ' . $this->group->get('cn')); apache_note('auth', 'invalid'); header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="' . $realm . '"'); die(Lang::txt('You must enter a valid username and password.')); } return $user; }
</legend> <label<?php echo $this->change && $this->oldpass && !\Hubzero\User\Password::passwordMatches($this->profile->get('uidNumber'), $this->oldpass, true) ? ' class="fieldWithErrors"' : ''; ?> > <?php echo Lang::txt('COM_MEMBERS_FIELD_CURRENT_PASS'); ?> <input name="oldpass" id="oldpass" type="password" value="" /> </label> <?php if ($this->change && !$this->oldpass) { echo '<p class="error">' . Lang::txt('COM_MEMBERS_PASS_BLANK') . '</p>'; } if ($this->change && $this->oldpass && !\Hubzero\User\Password::passwordMatches($this->profile->get('uidNumber'), $this->oldpass, true)) { echo '<p class="error">' . Lang::txt('COM_MEMBERS_PASS_INCORRECT') . '</p>'; } ?> <div class="grid"> <div class="col span6"> <label<?php echo $this->change && (!$this->newpass || $this->newpass != $this->newpass2) ? ' class="fieldWithErrors"' : ''; ?> > <?php echo Lang::txt('COM_MEMBERS_FIELD_NEW_PASS'); ?> <input name="newpass" id="newpass" type="password" value="" /> <?php
/** * Save profile * * @return void */ private function _saveEntryData() { $isNew = !$this->_profile->get('uidNumber'); if (!isset($this->raw->password)) { $this->raw->password = null; } if ($isNew) { if (!$this->_profile->get('username')) { $valid = false; // Try to create from name $username = preg_replace('/[^a-z9-0_]/i', '', strtolower($this->_profile->get('name'))); if (\Hubzero\Utility\Validate::username($username)) { if (!$this->_usernameExists($username)) { $valid = true; } } // Try to create from portion preceeding @ in email address if (!$valid) { $username = strstr($this->_profile->get('email'), '@', true); if (\Hubzero\Utility\Validate::username($username)) { if ($this->_usernameExists($username)) { $valid = true; } } } // Try to create from whole email address if (!$valid) { for ($i = 0; $i <= 99; $i++) { $username = preg_replace('/[^a-z9-0_]/i', '', strtolower($this->_profile->get('name'))) . $i; if (\Hubzero\Utility\Validate::username($username)) { if ($this->_usernameExists($username)) { $valid = true; break; } } } } if ($valid) { $this->_profile->set('username', $username); } } if (!$this->raw->password) { //\Hubzero\User\Helper::random_password(); $this->raw->password = $this->_profile->get('username'); } $usersConfig = Component::params('com_users'); $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = \App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } $user = User::getRoot(); $user->set('username', $this->_profile->get('username')); $user->set('name', $this->_profile->get('name')); $user->set('email', $this->_profile->get('email')); $user->set('id', 0); $user->set('groups', array($newUsertype)); $user->set('registerDate', Date::of('now')->toSql()); $user->set('password', $this->raw->password); $user->set('password_clear', $this->raw->password); $user->save(); $user->set('password_clear', ''); // Attempt to get the new user $profile = \Hubzero\User\Profile::getInstance($user->get('id')); $result = is_object($profile); // Did we successfully create an account? if ($result) { if (!$this->record->entry->get('emailConfirmed', null)) { $this->_profile->set('emailConfirmed', -rand(1, pow(2, 31) - 1)); } $this->_profile->set('uidNumber', $user->get('id')); $this->_profile->set('gidNumber', $profile->get('gidNumber')); if (!$this->_profile->get('homeDirectory')) { $this->_profile->set('homeDirectory', $profile->get('homeDirectory')); } if (!$this->_profile->get('loginShell')) { $this->_profile->set('loginShell', $profile->get('loginShell')); } if (!$this->_profile->get('ftpShell')) { $this->_profile->set('ftpShell', $profile->get('ftpShell')); } if (!$this->_profile->get('jobsAllowed')) { $this->_profile->set('jobsAllowed', $profile->get('jobsAllowed')); } } } if (!$this->_profile->store()) { throw new Exception(Lang::txt('Unable to save the entry data.')); } if ($password = $this->raw->password) { /*if ($isNew) { // We need to bypass any hashing $this->raw->password = '******'; \Hubzero\User\Password::changePasshash($this->_profile->get('uidNumber'), $password); } else {*/ \Hubzero\User\Password::changePassword($this->_profile->get('uidNumber'), $password); //} } \Hubzero\User\Password::expirePassword($this->_profile->get('uidNumber')); if ($isNew && $this->_options['emailnew'] == 1) { $eview = new \Hubzero\Component\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'site', 'name' => 'emails', 'layout' => 'confirm')); $eview->option = 'com_members'; $eview->controller = 'register'; $eview->sitename = Config::get('sitename'); $eview->login = $this->_profile->get('username'); $eview->name = $this->_profile->get('name'); $eview->registerDate = $this->_profile->get('registerDate'); $eview->confirm = $this->_profile->get('emailConfirmed'); $eview->baseURL = Request::base(); $msg = new \Hubzero\Mail\Message(); $msg->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'))->addTo($this->_profile->get('email'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', 'com_members'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('confirm_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { array_push($this->record->errors, Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION')); } } }
/** * Show a form for changing user password * * @return void */ public function changepasswordTask() { // Check if they're logged in if (User::isGuest()) { $rtrn = Request::getVar('REQUEST_URI', Route::url('index.php?option=' . $this->_controller . '&task=changepassword', false, true), 'server'); App::redirect(Route::url('index.php?option=com_users&view=login&return=' . base64_encode($rtrn), false)); } // Incoming $id = Request::getInt('id', 0); $id = $id ?: User::get('id'); // Ensure we have an ID if (!$id) { App::abort(404, Lang::txt('COM_MEMBERS_NO_ID')); } // Check authorization if (!User::authorise('core.manage', $this->_option) && User::get('id') != $id) { App::abort(403, Lang::txt('MEMBERS_NOT_AUTH')); } // Initiate profile class $profile = Member::oneOrFail($id); // Ensure we have a member if (!$profile->get('id')) { App::abort(404, Lang::txt('COM_MEMBERS_NOT_FOUND')); } // Set the page title $title = Lang::txt(strtoupper($this->_option)); $title .= $this->_task ? ': ' . Lang::txt(strtoupper($this->_option . '_' . $this->_task)) : ''; Document::setTitle($title); // Set the pathway if (Pathway::count() <= 0) { Pathway::append(Lang::txt(strtoupper($this->_option)), 'index.php?option=' . $this->_option); } Pathway::append(stripslashes($profile->get('name')), 'index.php?option=' . $this->_option . '&id=' . $profile->get('id')); Pathway::append(Lang::txt('COM_MEMBERS_' . strtoupper($this->_task)), 'index.php?option=' . $this->_option . '&id=' . $profile->get('id') . '&task=' . $this->_task); // Load some needed libraries if (\Hubzero\User\Helper::isXDomainUser(User::get('id'))) { App::abort(403, Lang::txt('COM_MEMBERS_PASS_CHANGE_LINKED_ACCOUNT')); } // Incoming data $change = Request::getVar('change', '', 'post'); $oldpass = Request::getVar('oldpass', '', 'post'); $newpass = Request::getVar('newpass', '', 'post'); $newpass2 = Request::getVar('newpass2', '', 'post'); $message = Request::getVar('message', ''); if (!empty($message)) { $this->setError($message); } $this->view->title = $title; $this->view->profile = $profile; $this->view->change = $change; $this->view->oldpass = $oldpass; $this->view->newpass = $newpass; $this->view->newpass2 = $newpass2; $this->view->validated = true; $password_rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows(); $this->view->password_rules = array(); foreach ($password_rules as $rule) { if (!empty($rule['description'])) { $this->view->password_rules[] = $rule['description']; } } if (!empty($newpass)) { $msg = \Hubzero\Password\Rule::verify($newpass, $password_rules, $profile->get('username')); } else { $msg = array(); } // Blank form request (no data submitted) if (empty($change)) { $this->view->setErrors($this->getErrors())->display(); return; } $passrules = false; if (!\Hubzero\User\Password::passwordMatches($profile->get('id'), $oldpass, true)) { $this->setError(Lang::txt('COM_MEMBERS_PASS_INCORRECT')); } elseif (!$newpass || !$newpass2) { $this->setError(Lang::txt('COM_MEMBERS_PASS_MUST_BE_ENTERED_TWICE')); } elseif ($newpass != $newpass2) { $this->setError(Lang::txt('COM_MEMBERS_PASS_NEW_CONFIRMATION_MISMATCH')); } elseif ($oldpass == $newpass) { // make sure the current password and new password are not the same // this should really be done in the password rules validation step $this->setError(Lang::txt('Your new password must be different from your current password')); } elseif (!empty($msg)) { $this->setError(Lang::txt('Password does not meet site password requirements. Please choose a password meeting all the requirements listed below.')); $this->view->set('validated', $msg); $passrules = true; } if ($this->getError()) { $change = array(); $change['_missing']['password'] = $this->getError(); if (!empty($msg) && $passrules) { $change['_missing']['password'] .= '<ul>'; foreach ($msg as $m) { $change['_missing']['password'] .= '<li>'; $change['_missing']['password'] .= $m; $change['_missing']['password'] .= '</li>'; } $change['_missing']['password'] .= '</ul>'; } if (Request::getInt('no_html', 0)) { echo json_encode($change); exit; } else { $this->view->setError($this->getError())->display(); return; } } // Encrypt the password and update the profile $result = \Hubzero\User\Password::changePassword($profile->get('id'), $newpass); // Save the changes if (!$result) { $this->view->setError(Lang::txt('MEMBERS_PASS_CHANGE_FAILED'))->display(); return; } // Redirect user back to main account page $return = base64_decode(Request::getVar('return', '', 'method', 'base64')); $this->_redirect = $return ? $return : Route::url('index.php?option=' . $this->_option . '&id=' . $id); $session = App::get('session'); // Redirect user back to main account page if (Request::getInt('no_html', 0)) { if ($session->get('badpassword', '0') || $session->get('expiredpassword', '0')) { $session->set('badpassword', '0'); $session->set('expiredpassword', '0'); } echo json_encode(array("success" => true)); exit; } else { if ($session->get('badpassword', '0') || $session->get('expiredpassword', '0')) { $session->set('badpassword', '0'); $session->set('expiredpassword', '0'); } } }
/** * Short description for 'create' * * Long description (if any) ... * * @return mixed Return description (if any) ... */ public function createTask() { if (!User::isGuest() && !User::get('tmp_user')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=myaccount'), Lang::txt('COM_MEMBERS_REGISTER_ERROR_NONGUEST_SESSION_CREATION'), 'warning'); return; } if (!isset($this->_taskMap[$this->_task])) { $this->_task = 'create'; Request::setVar('task', 'create'); } // Set the pathway $this->_buildPathway(); // Set the page title $this->_buildTitle(); $usersConfig = Component::params('com_users'); if ($usersConfig->get('allowUserRegistration') == '0') { return App::abort(404, Lang::txt('JGLOBAL_RESOURCE_NOT_FOUND')); } $hzal = null; if (User::get('auth_link_id')) { $hzal = \Hubzero\Auth\Link::find_by_id(User::get('auth_link_id')); } // Instantiate a new registration object $xregistration = new \Components\Members\Models\Registration(); if (Request::getMethod() == 'POST') { // Check for request forgeries Request::checkToken(); // Load POSTed data $xregistration->loadPost(); // Perform field validation if ($xregistration->check('create')) { // Get required system objects $user = clone User::getRoot(); $authorize = \JFactory::getACL(); // If user registration is not allowed, show 403 not authorized. if ($usersConfig->get('allowUserRegistration') == '0') { App::abort(403, Lang::txt('Access Forbidden')); return; } // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } $user->set('username', $xregistration->get('login')); $user->set('name', $xregistration->get('name')); $user->set('email', $xregistration->get('email')); /* // Bind the post array to the user object if (!$user->bind(Request::get('post'), 'usertype')) { App::abort(500, $user->getError()); } */ // Set some initial user values $user->set('id', 0); $user->set('groups', array($newUsertype)); $date = Date::of('now'); $user->set('registerDate', $date->toSql()); // Check user activation setting // 0 = automatically confirmed // 1 = require email confirmation (the norm) // 2 = require admin confirmation $useractivation = $usersConfig->get('useractivation', 1); // If requiring admin approval, set user to block if ($useractivation == 2) { $user->set('approved', 0); } // If there was an error with registration, set the message and display form if ($user->save()) { /* // Send registration confirmation mail $password = Request::getString('password', '', 'post', JREQUEST_ALLOWRAW); $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email UserController::_sendMail($user, $password); // Everything went fine, set relevant message depending upon user activation state and display message if ($useractivation == 1) { $message = Lang::txt('REG_COMPLETE_ACTIVATE'); } else { $message = Lang::txt('REG_COMPLETE'); } App::redirect(Route::url('index.php'), $message); */ // Get some settings $params = Component::params('com_members'); $hubHomeDir = rtrim($params->get('homedir'), '/'); // Attempt to get the new user $xprofile = \Hubzero\User\Profile::getInstance($user->get('id')); $result = is_object($xprofile); // Did we successfully create an account? if ($result) { $xprofile->loadRegistration($xregistration); if (is_object($hzal)) { if ($xprofile->get('email') == $hzal->email) { $xprofile->set('emailConfirmed', 3); } else { $xprofile->set('emailConfirmed', -rand(1, pow(2, 31) - 1)); } } else { if ($useractivation == 0) { $xprofile->set('emailConfirmed', 1); } } $xprofile->set('public', 0); // Do we have a return URL? $regReturn = Request::getVar('return', ''); if ($regReturn) { $xprofile->setParam('return', $regReturn); } // Unset password here so that change password below can be in charge of setting it initially $xprofile->set('password', ''); $result = $xprofile->update(); } // add member interests $interests = $xregistration->get('interests'); $mt = new \Components\Members\Models\Tags($xprofile->get('uidNumber')); if (!empty($interests)) { $mt->setTags($interests, $xprofile->get('uidNumber')); } if ($result) { $result = \Hubzero\User\Password::changePassword($xprofile->get('uidNumber'), $xregistration->get('password')); // Set password back here in case anything else down the line is looking for it $xprofile->set('password', $xregistration->get('password')); } // Did we successfully create/update an account? if (!$result) { return App::abort(500, Lang::txt('COM_MEMBERS_REGISTER_ERROR_CREATING_ACCOUNT')); } if ($xprofile->get('emailConfirmed') < 0) { // Notify the user $subject = Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'); $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'create')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->sitename = Config::get('sitename'); $eview->xprofile = $xprofile; $eview->baseURL = $this->baseURL; $eview->xregistration = $xregistration; $msg = new \Hubzero\Mail\Message(); $msg->setSubject($subject)->addTo($xprofile->get('email'), $xprofile->get('name'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', $this->_option); $message = $eview->loadTemplate(false); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('create_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION')); // @FIXME: LOG ERROR SOMEWHERE } } // Notify administration if ($usersConfig->get('mail_to_admin', 0)) { $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'admincreate_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->sitename = Config::get('sitename'); $eview->xprofile = $xprofile; $eview->baseUrl = $this->baseURL; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('admincreate_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $hubMonitorEmail = Config::get('mailfrom'); $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_ACCOUNT_CREATION'))->addTo($hubMonitorEmail)->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', $this->_option)->addHeader('X-Component-Object', 'user_creation_admin_notification')->addPart($plain, 'text/plain')->addPart($html, 'text/html'); // Send mail if (!$message->send()) { \Log::error('Members admin notification email failed: ' . Lang::txt('Failed to mail %s', $hubMonitorEmail)); } } // Instantiate a new view $this->view->setLayout('create'); $this->view->title = Lang::txt('COM_MEMBERS_REGISTER_CREATE_ACCOUNT'); $this->view->sitename = Config::get('sitename'); $this->view->xprofile = $xprofile; if ($this->getError()) { $this->view->setError($this->getError()); } $this->view->display(); if (is_object($hzal)) { $hzal->user_id = $user->get('id'); if ($hzal->user_id > 0) { $hzal->update(); } } User::set('auth_link_id', null); User::set('tmp_user', null); User::set('username', $xregistration->get('login')); User::set('email', $xregistration->get('email')); User::set('id', $user->get('id')); return; } } } if (Request::method() == 'GET') { if (User::get('tmp_user')) { $xregistration->loadAccount(User::getRoot()); $username = $xregistration->get('login'); $email = $xregistration->get('email'); if (is_object($hzal)) { $xregistration->set('login', $hzal->username); $xregistration->set('email', $hzal->email); $xregistration->set('confirmEmail', $hzal->email); } } } return $this->_show_registration_form($xregistration, 'create'); }
/** * Show a form for registering * * @return void */ public function createTask() { if (!User::isGuest() && !User::get('tmp_user')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=myaccount'), Lang::txt('COM_MEMBERS_REGISTER_ERROR_NONGUEST_SESSION_CREATION'), 'warning'); } if (!isset($this->_taskMap[$this->_task])) { $this->_task = 'create'; Request::setVar('task', 'create'); } // If user registration is not allowed, show 403 not authorized. $usersConfig = Component::params('com_members'); if ($usersConfig->get('allowUserRegistration') == '0') { return App::abort(404, Lang::txt('JGLOBAL_RESOURCE_NOT_FOUND')); } $hzal = null; if (User::get('auth_link_id')) { $hzal = \Hubzero\Auth\Link::find_by_id(User::get('auth_link_id')); } // Instantiate a new registration object $xregistration = new \Components\Members\Models\Registration(); if (Request::getMethod() == 'POST') { // Check for request forgeries Request::checkToken(); // Load POSTed data $xregistration->loadPost(); // Perform field validation $result = $xregistration->check('create'); // Incoming profile edits $profile = Request::getVar('profile', array(), 'post', 'none', 2); // Compile profile data foreach ($profile as $key => $data) { if (isset($profile[$key]) && is_array($profile[$key])) { $profile[$key] = array_filter($profile[$key]); } if (isset($profile[$key . '_other']) && trim($profile[$key . '_other'])) { if (is_array($profile[$key])) { $profile[$key][] = $profile[$key . '_other']; } else { $profile[$key] = $profile[$key . '_other']; } unset($profile[$key . '_other']); } } // Validate profile data $fields = \Components\Members\Models\Profile\Field::all()->including(['options', function ($option) { $option->select('*'); }])->where('action_create', '!=', \Components\Members\Models\Profile\Field::STATE_HIDDEN)->ordered()->rows(); // Validate profile fields if ($fields->count()) { $form = new \Hubzero\Form\Form('profile', array('control' => 'profile')); $form->load(\Components\Members\Models\Profile\Field::toXml($fields, 'create', $profile)); $form->bind(new \Hubzero\Config\Registry($profile)); if (!$form->validate($profile)) { $result = false; foreach ($form->getErrors() as $key => $error) { if ($error instanceof \Hubzero\Form\Exception\MissingData) { $xregistration->_missing[$key] = $error; } $xregistration->_invalid[$key] = $error; } } } // Passed validation? if ($result) { // Get required system objects $user = clone User::getInstance(); // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } $user->set('username', $xregistration->get('login', '')); $user->set('name', $xregistration->get('name', '')); $user->set('givenName', $xregistration->get('givenName', '')); $user->set('middleName', $xregistration->get('middleName', '')); $user->set('surname', $xregistration->get('surname', '')); $user->set('email', $xregistration->get('email', '')); $user->set('usageAgreement', (int) $xregistration->get('usageAgreement', 0)); $user->set('sendEmail', -1); if ($xregistration->get('sendEmail') >= 0) { $user->set('sendEmail', (int) $xregistration->get('sendEmail')); } // Set home directory $hubHomeDir = rtrim($this->config->get('homedir'), '/'); if (!$hubHomeDir) { // try to deduce a viable home directory based on sitename or live_site $sitename = strtolower(Config::get('sitename')); $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1); $sitename = trim($sitename, '/ '); $sitename_e = explode('.', $sitename, 2); if (isset($sitename_e[1])) { $sitename = $sitename_e[0]; } if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) { $sitename = ''; } if (empty($sitename)) { $sitename = strtolower(Request::base()); $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1); $sitename = trim($sitename, '/ '); $sitename_e = explode('.', $sitename, 2); if (isset($sitename_e[1])) { $sitename = $sitename_e[0]; } if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) { $sitename = ''; } } $hubHomeDir = DS . 'home'; if (!empty($sitename)) { $hubHomeDir .= DS . $sitename; } } $user->set('homeDirectory', $hubHomeDir . DS . $user->get('username')); $user->set('loginShell', '/bin/bash'); $user->set('ftpShell', '/usr/lib/sftp-server'); // Set some initial user values $user->set('id', 0); $user->set('accessgroups', array($newUsertype)); $user->set('registerDate', Date::toSql()); // Check user activation setting // 0 = automatically confirmed // 1 = require email confirmation (the norm) // 2 = require admin confirmation $useractivation = $usersConfig->get('useractivation', 1); // If requiring admin approval, set user to block if ($useractivation == 2) { $user->set('approved', 0); } $user->set('access', 5); $user->set('activation', -rand(1, pow(2, 31) - 1)); if (is_object($hzal)) { if ($user->get('email') == $hzal->email) { $user->set('activation', 3); } } else { if ($useractivation == 0) { $user->set('activation', 1); $user->set('access', (int) $this->config->get('privacy', 1)); } } $user->set('password', \Hubzero\User\Password::getPasshash($xregistration->get('password'))); // Do we have a return URL? $regReturn = Request::getVar('return', ''); if ($regReturn) { $user->setParam('return', $regReturn); } // If we managed to create a user if ($user->save()) { $access = array(); foreach ($fields as $field) { $access[$field->get('name')] = $field->get('access'); } $profile = $xregistration->_registration['_profile']; // Save profile data $member = Member::oneOrNew($user->get('id')); if (!$member->saveProfile($profile, $access)) { \Notify::error($member->getError()); // Don't stop the registration process! // At this point, the account was successfully created. // The profile info, however, may have issues. But, it's not crucial. //$result = false; } } else { \Notify::error($user->getError()); $result = false; } // If everything is OK so far... if ($result) { $result = \Hubzero\User\Password::changePassword($user->get('id'), $xregistration->get('password')); // Set password back here in case anything else down the line is looking for it $user->set('password', $xregistration->get('password')); // Did we successfully create/update an account? if (!$result) { return App::abort(500, Lang::txt('COM_MEMBERS_REGISTER_ERROR_CREATING_ACCOUNT')); } // Send confirmation email if ($user->get('activation') < 0) { \Components\Members\Helpers\Utility::sendConfirmEmail($user, $xregistration); } // Instantiate a new view $this->view->set('title', Lang::txt('COM_MEMBERS_REGISTER_CREATE_ACCOUNT'))->set('sitename', Config::get('sitename'))->set('xprofile', $user)->setErrors($this->getErrors())->setLayout('create')->display(); if (is_object($hzal)) { $hzal->user_id = $user->get('id'); if ($hzal->user_id > 0) { $hzal->update(); } } User::set('auth_link_id', null); User::set('tmp_user', null); User::set('username', $xregistration->get('login')); User::set('email', $xregistration->get('email')); User::set('id', $user->get('id')); return; } } } if (Request::method() == 'GET') { if (User::get('tmp_user')) { $xregistration->loadAccount(User::getInstance()); $username = $xregistration->get('login'); $email = $xregistration->get('email'); if (is_object($hzal)) { $xregistration->set('login', $hzal->username); $xregistration->set('email', $hzal->email); $xregistration->set('confirmEmail', $hzal->email); } } } // Set the pathway $this->_buildPathway(); // Set the page title $this->_buildTitle(); return $this->_show_registration_form($xregistration, 'create'); }
/** * Check if a password exists for a user * * @param string $password * @param string $since * @return boolean */ public function exists($password = null, $since = null) { $db = \App::get('db'); if (empty($db)) { return false; } $query = "SELECT `passhash` FROM `#__users_password_history` WHERE user_id = " . $db->quote($this->user_id); if (!empty($since)) { $query .= " AND invalidated >= " . $db->quote($since); } $db->setQuery($query); $results = $db->loadObjectList(); if ($results && count($results) > 0) { foreach ($results as $result) { $compare = \Hubzero\User\Password::comparePasswords($result->passhash, $password); if ($compare) { return true; } } } return false; }
/** * Short description for 'access_token' * * Long description (if any) ... * * @return unknown Return description (if any) ... */ private function access_token() { if (empty($this->_provider)) { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=bad oauth provider', 501, 'Internal Server Error'); return; } JLoader::import('Hubzero.User.Password'); $xauth_request = false; $header = ''; if (isset($_SERVER['HTTP_AUTHORIZATION'])) { $header = $_SERVER['HTTP_AUTHORIZATION']; } // @FIXME: header check is inexact and could give false positives // @FIXME: pecl oauth provider doesn't handle x_auth in header // @FIXME: api application should convert xauth variables in // header to form/query data as workaround // @FIXME: this code is here for future use if/when pecl oauth // provider is fixed // if (isset($_GET['x_auth_mode']) || isset($_GET['x_auth_username']) || isset($_GET['x_auth_password']) || isset($_POST['x_auth_mode']) || isset($_POST['x_auth_username']) || isset($_POST['x_auth_password']) || strpos($header, 'x_auth_mode') !== false || strpos($header, 'x_auth_username') !== false || strpos($header, 'x_auth_mode') !== false) { $xauth_request = true; } if ($xauth_request) { if ($this->_provider->getConsumerData()->xauth == '0') { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=permission_denied', 401, 'Unauthorized0'); return; } if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off') { $this->_response->setErrorMessage('SSL Required', 403, 'Forbidden'); return; } if (isset($this->_provider->x_auth_mode)) { $x_auth_mode = $this->_provider->x_auth_mode; } else { if (isset($_POST['x_auth_mode'])) { $x_auth_mode = $_POST['x_auth_mode']; } else { if (isset($_GET['x_auth_mode'])) { $x_auth_mode = $_GET['x_auth_mode']; } else { $x_auth_mode = ''; } } } if (isset($this->_provider->x_auth_username)) { $x_auth_username = $this->_provider->x_auth_username; } else { if (isset($_POST['x_auth_username'])) { $x_auth_username = $_POST['x_auth_username']; } else { if (isset($_GET['x_auth_username'])) { $x_auth_username = $_GET['x_auth_username']; } else { $x_auth_username = ''; } } } if (isset($this->_provider->x_auth_password)) { $x_auth_password = $this->_provider->x_auth_password; } else { if (isset($_POST['x_auth_password'])) { $x_auth_password = $_POST['x_auth_password']; } else { if (isset($_GET['x_auth_password'])) { $x_auth_password = $_GET['x_auth_password']; } else { $x_auth_password = ''; } } } if ($x_auth_mode != 'client_auth') { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=permission_denied', 400, 'Bad Request'); return; } $match = \Hubzero\User\Password::passwordMatches($x_auth_username, $x_auth_password, true); if (!$match) { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=permission_denied', 401, 'Unauthorized'); return; } $useraccount = User::getInstance(JUserHelper::getUserId($x_auth_username)); $db = App::get('db'); $db->setQuery("SELECT token,token_secret FROM #__oauthp_tokens WHERE consumer_id=" . $db->Quote($this->_provider->getConsumerData()->id) . " AND user_id =" . $db->Quote($useraccount->get('id')) . " LIMIT 1;"); $result = $db->loadObject(); if ($result === false) { $this->_response->setErrorMessage(500, 'Internal Server Error'); return; } if (!is_object($result)) { if ($this->_provider->getConsumerData()->xauth_grant < 1) { $this->_response->setErrorMessage(501, 'Internal Server Error'); return; } $token = sha1(OAuthProvider::generateToken(20, false)); $token_secret = sha1(OAuthProvider::generateToken(20, false)); $db = App::get('db'); $db->setQuery("INSERT INTO #__oauthp_tokens (consumer_id,user_id,state,token,token_secret,callback_url) VALUE (" . $db->Quote($this->_provider->getConsumerData()->id) . "," . $db->Quote($useraccount->get('id')) . "," . "'1'," . $db->Quote($token) . "," . $db->Quote($token_secret) . "," . $db->Quote($this->_provider->getConsumerData()->callback_url) . ");"); if (!$db->query()) { $this->_response->setErrorMessage(502, 'Internal Server Error'); return; } if ($db->getAffectedRows() < 1) { $this->_response->setErrorMessage(503, 'Internal Server Error'); return; } $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setMessage("oauth_token=" . $token . "&oauth_token_secret=" . $token_secret, 200, "OK"); } else { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setMessage("oauth_token=" . $result->token . "&oauth_token_secret=" . $result->token_secret, 200, "OK"); } return; } else { $this->_response->setErrorMessage(503, 'Internal Server Error'); return; // @FIXME: we don't support 3-legged auth yet // lookup request token to access token, give out access token // check verifier // check used flag $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setMessage("oauth_token=" . $token . "&oauth_token_secret=" . $token_secret, 200, "OK"); return; } }
/** * This method should handle any authentication and report back to the subject * * @param array $credentials Array holding the user credentials * @param array $options Array of extra options * @param object $response Authentication response object * @return boolean */ public function onUserAuthenticate($credentials, $options, &$response) { jimport('joomla.user.helper'); // For JLog $response->type = 'hubzero'; // HUBzero does not like blank passwords if (empty($credentials['password'])) { $response->status = \Hubzero\Auth\Status::FAILURE; $response->error_message = Lang::txt('PLG_AUTHENTICATION_HUBZERO_ERROR_EMPTY_PASS'); return false; } // Initialize variables $conditions = ''; // Get a database object $db = \App::get('db'); // Determine if attempting to log in via username or email address if (strpos($credentials['username'], '@')) { $conditions = ' WHERE email=' . $db->Quote($credentials['username']); } else { $conditions = ' WHERE username='******'username']); } $query = 'SELECT `id`, `username`, `password`' . ' FROM `#__users`' . $conditions . ' AND `block` != 1'; $db->setQuery($query); $result = $db->loadObjectList(); if (is_array($result) && count($result) > 1) { $response->status = \Hubzero\Auth\Status::FAILURE; $response->error_message = Lang::txt('PLG_AUTHENTICATION_HUBZERO_UNKNOWN_USER'); return false; } elseif (is_array($result) && isset($result[0])) { $result = $result[0]; } // Now make sure they haven't made too many failed login attempts if (\Hubzero\User\User::oneOrFail($result->id)->hasExceededLoginLimit()) { $response->status = \Hubzero\Auth\Status::FAILURE; $response->error_message = Lang::txt('PLG_AUTHENTICATION_HUBZERO_TOO_MANY_ATTEMPTS'); return false; } if ($result) { if (\Hubzero\User\Password::passwordMatches($result->username, $credentials['password'], true)) { $user = User::getInstance($result->id); $response->username = $user->username; $response->email = $user->email; $response->fullname = $user->name; $response->status = \Hubzero\Auth\Status::SUCCESS; $response->error_message = ''; // Check validity and age of password $password_rules = \Hubzero\Password\Rule::getRules(); $msg = \Hubzero\Password\Rule::validate($credentials['password'], $password_rules, $result->username); if (is_array($msg) && !empty($msg[0])) { App::get('session')->set('badpassword', '1'); } if (\Hubzero\User\Password::isPasswordExpired($result->username)) { App::get('session')->set('expiredpassword', '1'); } // Set cookie with login preference info $prefs = array('user_id' => $user->get('id'), 'user_img' => \Hubzero\User\Profile::getInstance($user->get('id'))->getPicture(0, false), 'authenticator' => 'hubzero'); $namespace = 'authenticator'; $lifetime = time() + 365 * 24 * 60 * 60; \Hubzero\Utility\Cookie::bake($namespace, $lifetime, $prefs); } else { $response->status = \Hubzero\Auth\Status::FAILURE; $response->error_message = Lang::txt('PLG_AUTHENTICATION_HUBZERO_AUTHENTICATION_FAILED'); } } else { $response->status = \Hubzero\Auth\Status::FAILURE; $response->error_message = Lang::txt('PLG_AUTHENTICATION_HUBZERO_AUTHENTICATION_FAILED'); } }
/** * Create a user profile * * @apiMethod POST * @apiUri /members * @return void */ public function createTask() { $this->requiresAuthentication(); // Initialize new usertype setting $usersConfig = Component::params('com_users'); $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } // Incoming $user = User::getInstance(); $user->set('id', 0); $user->set('groups', array($newUsertype)); $user->set('registerDate', Date::toSql()); $user->set('name', Request::getVar('name', '', 'post')); if (!$user->get('name')) { App::abort(500, Lang::txt('No name provided.')); } $user->set('username', Request::getVar('username', '', 'post')); if (!$user->get('username')) { App::abort(500, Lang::txt('No username provided.')); } if (!\Hubzero\Utility\Validate::username($user->get('username'))) { App::abort(500, Lang::txt('Username not valid.')); } $user->set('email', Request::getVar('email', '', 'post')); if (!$user->get('email')) { App::abort(500, Lang::txt('No email provided.')); } if (!\Hubzero\Utility\Validate::email($user->get('email'))) { App::abort(500, Lang::txt('Email not valid.')); } $name = explode(' ', $user->get('name')); $surname = $user->get('name'); $givenName = ''; $middleName = ''; if (count($name) > 1) { $surname = array_pop($name); $givenName = array_shift($name); $middleName = implode(' ', $name); } // Set the new info $user->set('givenName', $givenName); $user->set('middleName', $middleName); $user->set('surname', $surname); $user->set('activation', -rand(1, pow(2, 31) - 1)); $user->set('access', 1); $user->set('password', $password); //$user->set('password_clear', $password); $result = $user->save(); $user->set('password_clear', ''); $user->set('password', ''); if ($result) { $result = \Hubzero\User\Password::changePassword($user->get('id'), $password); // Set password back here in case anything else down the line is looking for it $user->set('password', $password); $user->save(); } // Did we successfully create/update an account? if (!$result) { App::abort(500, Lang::txt('Account creation failed.')); } if ($groups = Request::getVar('groups', array(), 'post')) { foreach ($groups as $id) { $group = \Hubzero\User\Group::getInstance($id); if ($group) { if (!in_array($user->get('id'), $group->get('members'))) { $group->add('members', array($user->get('id'))); $group->update(); } } } } // Create a response object $response = new stdClass(); $response->id = $user->get('id'); $response->name = $user->get('name'); $response->email = $user->get('email'); $response->username = $user->get('username'); $this->send($response); }
/** * Save an entry and return to main listing * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); if (!User::authorise('core.manage', $this->_option) && !User::authorise('core.admin', $this->_option) && !User::authorise('core.create', $this->_option) && !User::authorise('core.edit', $this->_option)) { App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR')); } // Incoming profile edits $fields = Request::getVar('fields', array(), 'post', 'none', 2); // Load the profile $user = Member::oneOrNew($fields['id']); // Get the user before changes so we can // compare how data changed later on $prev = clone $user; // Set the incoming data $user->set($fields); if ($user->isNew()) { $newUsertype = $this->config->get('new_usertype'); if (!$newUsertype) { $newUsertype = Accessgroup::oneByTitle('Registered')->get('id'); } $user->set('accessgroups', array($newUsertype)); // Check that username is filled if (!Validate::username($user->get('username'))) { Notify::error(Lang::txt('COM_MEMBERS_MEMBER_USERNAME_INVALID')); return $this->editTask($user); } // Check email is valid if (!Validate::email($user->get('email'))) { Notify::error(Lang::txt('COM_MEMBERS_MEMBER_EMAIL_INVALID')); return $this->editTask($user); } // Set home directory $hubHomeDir = rtrim($this->config->get('homedir'), '/'); if (!$hubHomeDir) { // try to deduce a viable home directory based on sitename or live_site $sitename = strtolower(Config::get('sitename')); $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1); $sitename = trim($sitename, '/ '); $sitename_e = explode('.', $sitename, 2); if (isset($sitename_e[1])) { $sitename = $sitename_e[0]; } if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) { $sitename = ''; } if (empty($sitename)) { $sitename = strtolower(Request::base()); $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1); $sitename = trim($sitename, '/ '); $sitename_e = explode('.', $sitename, 2); if (isset($sitename_e[1])) { $sitename = $sitename_e[0]; } if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) { $sitename = ''; } } $hubHomeDir = DS . 'home'; if (!empty($sitename)) { $hubHomeDir .= DS . $sitename; } } $user->set('homeDirectory', $hubHomeDir . DS . $user->get('username')); $user->set('loginShell', '/bin/bash'); $user->set('ftpShell', '/usr/lib/sftp-server'); $user->set('registerDate', Date::toSql()); } // Set the new info $user->set('givenName', preg_replace('/\\s+/', ' ', trim($fields['givenName']))); $user->set('middleName', preg_replace('/\\s+/', ' ', trim($fields['middleName']))); $user->set('surname', preg_replace('/\\s+/', ' ', trim($fields['surname']))); $name = array($user->get('givenName'), $user->get('middleName'), $user->get('surname')); $name = implode(' ', $name); $name = preg_replace('/\\s+/', ' ', $name); $user->set('name', $name); $user->set('modifiedDate', Date::toSql()); if ($ec = Request::getInt('activation', 0, 'post')) { $user->set('activation', $ec); } else { $user->set('activation', Helpers\Utility::genemailconfirm()); } // Can't block yourself if ($user->get('block') && $user->get('id') == User::get('id') && !User::get('block')) { Notify::error(Lang::txt('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF')); return $this->editTask($user); } // Make sure that we are not removing ourself from Super Admin group $iAmSuperAdmin = User::authorise('core.admin'); if ($iAmSuperAdmin && User::get('id') == $user->get('id')) { // Check that at least one of our new groups is Super Admin $stillSuperAdmin = false; foreach ($fields['accessgroups'] as $group) { $stillSuperAdmin = $stillSuperAdmin ? $stillSuperAdmin : \JAccess::checkGroup($group, 'core.admin'); } if (!$stillSuperAdmin) { Notify::error(Lang::txt('COM_USERS_USERS_ERROR_CANNOT_DEMOTE_SELF')); return $this->editTask($user); } } // Save the changes if (!$user->save()) { Notify::error($user->getError()); return $this->editTask($user); } // Save profile data $profile = Request::getVar('profile', array(), 'post', 'none', 2); $access = Request::getVar('profileaccess', array(), 'post', 'none', 2); foreach ($profile as $key => $data) { if (isset($profile[$key]) && is_array($profile[$key])) { $profile[$key] = array_filter($profile[$key]); } if (isset($profile[$key . '_other']) && trim($profile[$key . '_other'])) { if (is_array($profile[$key])) { $profile[$key][] = $profile[$key . '_other']; } else { $profile[$key] = $profile[$key . '_other']; } unset($profile[$key . '_other']); } } if (!$user->saveProfile($profile, $access)) { Notify::error($user->getError()); return $this->editTask($user); } // Do we have a new pass? $newpass = trim(Request::getVar('newpass', '', 'post')); if ($newpass) { // Get password rules and validate $password_rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows(); $validated = \Hubzero\Password\Rule::verify($newpass, $password_rules, $user->get('id')); if (!empty($validated)) { // Set error Notify::error(Lang::txt('COM_MEMBERS_PASSWORD_DOES_NOT_MEET_REQUIREMENTS')); $this->validated = $validated; $this->_task = 'apply'; } else { // Save password \Hubzero\User\Password::changePassword($user->get('username'), $newpass); } } $passinfo = \Hubzero\User\Password::getInstance($user->get('id')); if (is_object($passinfo)) { // Do we have shadow info to change? $shadowMax = Request::getInt('shadowMax', false, 'post'); $shadowWarning = Request::getInt('shadowWarning', false, 'post'); $shadowExpire = Request::getVar('shadowExpire', '', 'post'); if ($shadowMax || $shadowWarning || !is_null($passinfo->get('shadowExpire')) && empty($shadowExpire)) { if ($shadowMax) { $passinfo->set('shadowMax', $shadowMax); } if ($shadowExpire || !is_null($passinfo->get('shadowExpire')) && empty($shadowExpire)) { if (preg_match("/[0-9]{4}-[0-9]{2}-[0-9]{2}/", $shadowExpire)) { $shadowExpire = strtotime($shadowExpire) / 86400; $passinfo->set('shadowExpire', $shadowExpire); } elseif (preg_match("/[0-9]+/", $shadowExpire)) { $passinfo->set('shadowExpire', $shadowExpire); } elseif (empty($shadowExpire)) { $passinfo->set('shadowExpire', NULL); } } if ($shadowWarning) { $passinfo->set('shadowWarning', $shadowWarning); } $passinfo->update(); } } // Check for spam count $reputation = Request::getVar('spam_count', null, 'post'); if (!is_null($reputation)) { $user->reputation->set('spam_count', $reputation); $user->reputation->save(); } // Email the user that their account has been approved if (!$prev->get('approved') && $this->config->get('useractivation_email')) { if (!$this->emailApprovedUser($user)) { Notify::error(Lang::txt('COM_MEMBERS_ERROR_EMAIL_FAILED')); } } // Set success message Notify::success(Lang::txt('COM_MEMBERS_MEMBER_SAVED')); // Drop through to edit form? if ($this->getTask() == 'apply') { return $this->editTask($user); } // Redirect $this->cancelTask(); }
/** * Save an entry and return to main listing * * @param integer $redirect Redirect to main listing? * @return void */ public function saveTask($redirect = 1) { // Check for request forgeries Request::checkToken(); // Incoming user ID $id = Request::getInt('id', 0, 'post'); // Do we have an ID? if (!$id) { App::abort(500, Lang::txt('COM_MEMBERS_NO_ID')); return; } // Incoming profile edits $p = Request::getVar('profile', array(), 'post', 'none', 2); // Load the profile $profile = new Profile(); $profile->load($id); // Set the new info $profile->set('givenName', preg_replace('/\\s+/', ' ', trim($p['givenName']))); $profile->set('middleName', preg_replace('/\\s+/', ' ', trim($p['middleName']))); $profile->set('surname', preg_replace('/\\s+/', ' ', trim($p['surname']))); $name = trim($p['givenName']) . ' '; $name .= trim($p['middleName']) != '' ? trim($p['middleName']) . ' ' : ''; $name .= trim($p['surname']); $name = preg_replace('/\\s+/', ' ', $name); $profile->set('name', $name); if (isset($p['vip'])) { $profile->set('vip', $p['vip']); } else { $profile->set('vip', 0); } $profile->set('orcid', trim($p['orcid'])); $profile->set('url', trim($p['url'])); $profile->set('phone', trim($p['phone'])); $profile->set('orgtype', trim($p['orgtype'])); $profile->set('organization', trim($p['organization'])); $profile->set('bio', trim($p['bio'])); if (isset($p['public'])) { $profile->set('public', $p['public']); } else { $profile->set('public', 0); } $profile->set('modifiedDate', Date::toSql()); $profile->set('homeDirectory', trim($p['homeDirectory'])); $profile->set('loginShell', trim($p['loginShell'])); $ec = Request::getInt('emailConfirmed', 0, 'post'); if ($ec) { $profile->set('emailConfirmed', $ec); } else { $confirm = Helpers\Utility::genemailconfirm(); $profile->set('emailConfirmed', $confirm); } if (isset($p['email'])) { $profile->set('email', trim($p['email'])); } if (isset($p['mailPreferenceOption'])) { $profile->set('mailPreferenceOption', trim($p['mailPreferenceOption'])); } else { $profile->set('mailPreferenceOption', -1); } if (!empty($p['gender'])) { $profile->set('gender', trim($p['gender'])); } if (!empty($p['disability'])) { if ($p['disability'] == 'yes') { if (!is_array($p['disabilities'])) { $p['disabilities'] = array(); } if (count($p['disabilities']) == 1 && isset($p['disabilities']['other']) && empty($p['disabilities']['other'])) { $profile->set('disability', array('no')); } else { $profile->set('disability', $p['disabilities']); } } else { $profile->set('disability', array($p['disability'])); } } if (!empty($p['hispanic'])) { if ($p['hispanic'] == 'yes') { if (!is_array($p['hispanics'])) { $p['hispanics'] = array(); } if (count($p['hispanics']) == 1 && isset($p['hispanics']['other']) && empty($p['hispanics']['other'])) { $profile->set('hispanic', array('no')); } else { $profile->set('hispanic', $p['hispanics']); } } else { $profile->set('hispanic', array($p['hispanic'])); } } if (isset($p['race']) && is_array($p['race'])) { $profile->set('race', $p['race']); } // Save the changes if (!$profile->update()) { App::abort(500, $profile->getError()); return false; } // Do we have a new pass? $newpass = trim(Request::getVar('newpass', '', 'post')); if ($newpass != '') { // Get password rules and validate $password_rules = \Hubzero\Password\Rule::getRules(); $validated = \Hubzero\Password\Rule::validate($newpass, $password_rules, $profile->get('uidNumber')); if (!empty($validated)) { // Set error $this->setError(Lang::txt('COM_MEMBERS_PASSWORD_DOES_NOT_MEET_REQUIREMENTS')); $this->validated = $validated; $redirect = false; } else { // Save password \Hubzero\User\Password::changePassword($profile->get('username'), $newpass); } } $passinfo = \Hubzero\User\Password::getInstance($id); if (is_object($passinfo)) { // Do we have shadow info to change? $shadowMax = Request::getInt('shadowMax', false, 'post'); $shadowWarning = Request::getInt('shadowWarning', false, 'post'); $shadowExpire = Request::getVar('shadowExpire', '', 'post'); if ($shadowMax || $shadowWarning || !is_null($passinfo->get('shadowExpire')) && empty($shadowExpire)) { if ($shadowMax) { $passinfo->set('shadowMax', $shadowMax); } if ($shadowExpire || !is_null($passinfo->get('shadowExpire')) && empty($shadowExpire)) { if (preg_match("/[0-9]{4}-[0-9]{2}-[0-9]{2}/", $shadowExpire)) { $shadowExpire = strtotime($shadowExpire) / 86400; $passinfo->set('shadowExpire', $shadowExpire); } elseif (preg_match("/[0-9]+/", $shadowExpire)) { $passinfo->set('shadowExpire', $shadowExpire); } elseif (empty($shadowExpire)) { $passinfo->set('shadowExpire', NULL); } } if ($shadowWarning) { $passinfo->set('shadowWarning', $shadowWarning); } $passinfo->update(); } } // Get the user's interests (tags) $tags = trim(Request::getVar('tags', '')); // Process tags include_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'tags.php'; $mt = new \Components\Members\Models\Tags($id); $mt->setTags($tags, $id); // Make sure certain changes make it back to the user table $user = User::getInstance($id); $user->set('name', $name); $user->set('email', $profile->get('email')); if (!$user->save()) { App::abort('', Lang::txt($user->getError())); return false; } if ($redirect) { // Redirect App::redirect(Route::url('index.php?option=' . $this->_option), Lang::txt('COM_MEMBERS_MEMBER_SAVED')); } else { $this->editTask($id); } }
/** * @since 1.6 */ function processResetComplete($data) { // Get the form. $form = $this->getResetCompleteForm(); // 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; } // Get the token and user id from the confirmation process. $app = JFactory::getApplication(); $token = $app->getUserState('com_users.reset.token', null); $id = $app->getUserState('com_users.reset.user', null); // Check the token and user id. if (empty($token) || empty($id)) { return new Exception(Lang::txt('COM_USERS_RESET_COMPLETE_TOKENS_MISSING'), 403); } // Get the user object. $user = User::getInstance($id); // Check for a user and that the tokens match. if (empty($user) || $user->activation !== $token) { $this->setError(Lang::txt('COM_USERS_USER_NOT_FOUND')); return false; } // Make sure the user isn't blocked. if ($user->block) { $this->setError(Lang::txt('COM_USERS_USER_BLOCKED')); return false; } // Initiate profile classs $profile = User::getInstance($id); if (\Hubzero\User\Helper::isXDomainUser($user->get('id'))) { App::abort(403, Lang::txt('This is a linked account. To change your password you must change it using the procedures available where the account you are linked to is managed.')); return; } $password_rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows(); $password1 = $data['password1']; $password2 = $data['password2']; if (!empty($password1)) { $msg = \Hubzero\Password\Rule::verify($password1, $password_rules, $profile->get('username')); } else { $msg = array(); } include_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'helpers' . DS . 'utility.php'; if (!$password1 || !$password2) { $this->setError(Lang::txt('you must enter your new password twice to ensure we have it correct')); } elseif ($password1 != $password2) { $this->setError(Lang::txt('the new password and confirmation you entered do not match. Please try again')); } elseif (!\Components\Members\Helpers\Utility::validpassword($password1)) { $this->setError(Lang::txt('the password you entered was invalid password. You may be using characters that are not allowed')); } elseif (!empty($msg)) { $this->setError(Lang::txt('the password does not meet site password requirements. Please choose a password meeting all the requirements listed below.')); } if ($this->getError()) { $this->setError($this->getError()); return false; } // Encrypt the password and update the profile $result = \Hubzero\User\Password::changePassword($profile->get('username'), $password1); // Save the changes if (!$result) { $this->setError(Lang::txt('There was an error changing your password.')); return false; } // Flush the user data from the session. $app->setUserState('com_users.reset.token', null); $app->setUserState('com_users.reset.user', null); return true; }
/** * Check user credentials * * @param string $username User's username * @param string $password User's password * @return bool Result of username/password check */ public function checkUserCredentials($username, $password) { // allow authentication via email, just like in the hub if (strpos($username, '@')) { $username = $this->getUsernameFromEmail($username); } // use hubzero password library to compare stored password with sent password $match = Password::passwordMatches($username, $password, true); // return if match was found return (bool) $match; }
/** * Processes the password set form * * @return void */ public function settingpasswordTask() { // Check for request forgeries Session::checkToken('post') or exit(Lang::txt('JINVALID_TOKEN')); // Get the token and user id from the verification process $token = User::getState('com_users.reset.token', null); $id = User::getState('com_users.reset.user', null); $no_html = Request::getInt('no_html', 0); // Check the token and user id if (empty($token) || empty($id)) { throw new Exception(Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_TOKENS_MISSING'), 403); } // Get the user object $user = \Hubzero\User\User::oneOrFail($id); // Check for a user and that the tokens match if ($user->tokens()->latest()->token !== $token) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=setpassword', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_USER_NOT_FOUND'), 'warning'); return; } // Make sure the user isn't blocked if ($user->get('block')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=setpassword', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_USER_NOT_FOUND'), 'warning'); return; } if (\Hubzero\User\Helper::isXDomainUser($user->get('id'))) { throw new Exception(Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_LINKED_ACCOUNT'), 403); } $password_rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows(); $password1 = trim(Request::getVar('password1', null)); $password2 = trim(Request::getVar('password2', null)); if (!empty($password1)) { $msg = \Hubzero\Password\Rule::verify($password1, $password_rules, $user->get('username')); } else { $msg = array(); } require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'utility.php'; $error = false; $changing = true; if (!$password1 || !$password2) { $error = Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_PASSWORD_TWICE'); } elseif ($password1 != $password2) { $error = Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_PASSWORD_DONT_MATCH'); } elseif (!\Components\Members\Helpers\Utility::validpassword($password1)) { $error = Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_PASSWORD_INVALID'); } elseif (!empty($msg)) { $error = Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_PASSWORD_FAILS_REQUIREMENTS'); } // If we're resetting password to the current password, just return true // That way you can't reset the counter on your current password, or invalidate it by putting it into history if (\Hubzero\User\Password::passwordMatches($user->get('id'), $password1)) { $error = false; $changing = false; $result = true; } if ($error) { if ($no_html) { $response = array('success' => false, 'message' => $error); echo json_encode($response); die; } else { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=setpassword', false), $error, 'warning'); return; } } if ($changing) { // Encrypt the password and update the profile $result = \Hubzero\User\Password::changePassword($user->get('username'), $password1); } // Save the changes if (!$result) { if ($no_html) { $response = array('success' => false, 'message' => Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_GENERIC')); echo json_encode($response); die; } else { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=setpassword', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_GENERIC'), 'warning'); return; } } // Flush the user data from the session User::setState('com_users.reset.token', null); User::setState('com_users.reset.user', null); if ($no_html) { $response = array('success' => true, 'redirect' => Route::url('index.php?option=com_users&view=login', false)); echo json_encode($response); die; } else { // Everything went well...go to the login page App::redirect(Route::url('index.php?option=com_users&view=login', false), Lang::txt('COM_MEMBERS_CREDENTIALS_PASSWORD_RESET_COMPLETE'), 'passed'); } }
/** * Get information about the password expiration * * @return array - password expiration information */ private function getPassInfo() { $hzup = \Hubzero\User\Password::getInstance($this->member->get('uidNumber')); // Check to see if password expiration is even enforced if (empty($hzup->passhash) || $hzup->shadowMax === NULL) { return false; } $chgtime = time(); $chgtime = intval($chgtime / 86400); $diff = $hzup->shadowLastChange + $hzup->shadowMax - $chgtime; if ($diff > $hzup->shadowWarning) { $message_style = 'info'; } else { if ($diff <= $hzup->shadowWarning && $diff > 0) { $message_style = 'warning'; } else { $message_style = 'error'; } } return array('diff' => $diff, 'warning' => $hzup->shadowWarning, 'max' => $hzup->shadowMax, 'message_style' => $message_style); }
/** * Validate a password * * @param string $password * @param array $rules * @param mixed $user * @param string $name * @return array */ public static function verify($password, $rules, $user, $name = null) { if (empty($rules)) { return array(); } $fail = array(); $stats = self::analyze($password); foreach ($rules as $rule) { if ($rule['rule'] == 'minCharacterClasses') { if ($stats['uniqueClasses'] < $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'maxCharacterClasses') { if ($stats['uniqueClasses'] > $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'minPasswordLength') { if ($stats['count'][0] < $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'maxPasswordLength') { if ($stats['count'][0] > $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'maxClassCharacters') { if (empty($rule['class'])) { continue; } $class = $rule['class']; if (empty($stats['count'][$class])) { $stats['count'][$class] = 0; } if ($stats['count'][$class] > $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'minClassCharacters') { if (empty($rule['class'])) { continue; } $class = $rule['class']; if (empty($stats['count'][$class])) { $stats['count'][$class] = 0; } if ($stats['count'][$class] < $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'minUniqueCharacters') { if ($stats['uniqueCharacters'] < $rule['value']) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'notBlacklisted') { if (Blacklist::basedOnBlackList($password)) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'notNameBased') { if ($name == null) { if (is_numeric($user)) { $xuser = User::oneOrNew($user); } else { $xuser = User::oneByUsername($user); } if (!is_object($xuser)) { continue; } $givenName = $xuser->get('givenName'); $middleName = $xuser->get('middleName'); $surname = $xuser->get('surname'); $name = $givenName; if (!empty($middleName)) { if (empty($name)) { $name = $middleName; } else { $name .= ' ' . $middleName; } } if (!empty($surname)) { if (empty($name)) { $name = $surname; } else { $name .= ' ' . $surname; } } } if (self::isBasedOnName($password, $name)) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'notUsernameBased') { if (is_numeric($user)) { $xuser = User::oneOrNew($user); if (!is_object($xuser)) { continue; } $user = $xuser->get('username'); } if (self::isBasedOnUsername($password, $user)) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'notReused') { $date = new \DateTime('now'); $date->modify("-" . $rule['value'] . "day"); $phist = History::getInstance($user); if (!is_object($phist)) { continue; } if ($phist->exists($password, $date->format("Y-m-d H:i:s"))) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] == 'notRepeat') { if (Password::passwordMatches($user, $password, true)) { $fail[] = $rule['failuremsg']; } } else { if ($rule['rule'] === 'true') { } else { if ($rule['rule'] == 'notStale') { } else { $fail[] = $rule['failuremsg']; } } } } } } } } } } } } } } } if (empty($fail)) { $fail = array(); } return $fail; }
/** * Save profile * * @return void */ private function _saveEntryData() { $isNew = !$this->record->entry->get('id'); if (!isset($this->raw->password)) { $this->raw->password = null; } if ($isNew) { if (!$this->record->entry->get('username')) { $valid = false; // Try to create from name $username = preg_replace('/[^a-z9-0_]/i', '', strtolower($this->record->entry->get('name'))); if (Validate::username($username)) { if (!$this->_usernameExists($username)) { $valid = true; } } // Try to create from portion preceeding @ in email address if (!$valid) { $username = strstr($this->record->entry->get('email'), '@', true); if (Validate::username($username)) { if ($this->_usernameExists($username)) { $valid = true; } } } // Try to create from whole email address if (!$valid) { for ($i = 0; $i <= 99; $i++) { $username = preg_replace('/[^a-z9-0_]/i', '', strtolower($this->record->entry->get('name'))) . $i; if (Validate::username($username)) { if ($this->_usernameExists($username)) { $valid = true; break; } } } } if ($valid) { $this->record->entry->set('username', $username); } } if (!$this->raw->password) { $this->raw->password = $this->record->entry->get('username'); } $newUsertype = null; if (isset($this->raw->usertype)) { if (is_numeric($this->raw->usertype)) { $newUsertype = (int) $this->raw->usertype; } else { $db = \App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title=' . $db->quote($this->raw->usertype)); $db->setQuery($query); $newUsertype = (int) $db->loadResult(); } } if (!$newUsertype) { $usersConfig = Component::params('com_users'); $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = \App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } } $d = Date::of('now'); if ($this->raw->registerDate) { try { $d = Date::of($this->raw->registerDate); } catch (Exception $e) { array_push($this->record->errors, $e->getMessage()); } } $this->record->entry->set('id', 0); $this->record->entry->set('accessgroups', array($newUsertype)); $this->record->entry->set('registerDate', $d->toSql()); $this->record->entry->set('password', $this->raw->password); if (!$this->record->entry->get('activation', null)) { $this->record->entry->set('activation', -rand(1, pow(2, 31) - 1)); } } if (!$this->record->entry->save()) { throw new Exception(Lang::txt('Unable to save the entry data.')); } if (!empty($this->_profile)) { if (!$this->record->entry->saveProfile($this->_profile)) { throw new Exception($this->record->entry->getError()); } } if ($this->raw->password) { \Hubzero\User\Password::changePassword($this->record->entry->get('id'), $this->raw->password); \Hubzero\User\Password::expirePassword($this->record->entry->get('id')); } if ($isNew && $this->_options['emailnew'] == 1) { $eview = new \Hubzero\Component\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'site', 'name' => 'emails', 'layout' => 'confirm')); $eview->option = 'com_members'; $eview->controller = 'register'; $eview->sitename = Config::get('sitename'); $eview->login = $this->record->entry->get('username'); $eview->name = $this->record->entry->get('name'); $eview->registerDate = $this->record->entry->get('registerDate'); $eview->confirm = $this->record->entry->get('activation'); $eview->baseURL = Request::base(); $msg = new \Hubzero\Mail\Message(); $msg->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'))->addTo($this->record->entry->get('email'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', 'com_members'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('confirm_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { array_push($this->record->errors, Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION')); } } }