Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Thu, Feb 6, 12:09 AM

in-portal

Index: branches/5.1.x/core/units/users/users_tag_processor.php
===================================================================
--- branches/5.1.x/core/units/users/users_tag_processor.php (revision 14477)
+++ branches/5.1.x/core/units/users/users_tag_processor.php (revision 14478)
@@ -1,352 +1,352 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class UsersTagProcessor extends kDBTagProcessor
{
function LogoutLink($params)
{
- $pass = Array('pass' => 'all,m,u', 'u_event' => 'OnLogout', 'm_cat_id'=>0);
+ $pass = Array('pass' => 'all,m,u', 'u_event' => 'OnLogout', 'm_cat_id' => 0, '__NO_REWRITE__' => 1);
$logout_template = $this->SelectParam($params, 'template,t');
return $this->Application->HREF($logout_template, '', $pass);
}
function UseUsernames($params)
{
return $this->Application->ConfigValue('Email_As_Login') != 1;
}
function RegistrationEnabled($params)
{
return $this->Application->ConfigValue('User_Allow_New') != 2;
}
function SuggestRegister($params)
{
return !$this->Application->LoggedIn() && !$this->Application->ConfigValue('Comm_RequireLoginBeforeCheckout') && $this->RegistrationEnabled($params);
}
function ConfirmPasswordLink($params)
{
$code = $this->getCachedCode();
$fields_hash = Array (
'PwResetConfirm' => $code,
'PwRequestTime' => adodb_mktime(),
);
$user_id = $this->Application->RecallVar('tmp_user_id');
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'PortalUser', 'PortalUserId = '.$user_id);
$params['user_key'] = $code;
if (!$this->SelectParam($params, 'template,t')) {
$params['template'] = $this->Application->GetVar('reset_confirm_template');
}
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
/**
* Generates & caches code for password confirmation link
*
* @return string
*/
function getCachedCode()
{
static $code = null;
if (!isset($code)) {
$code = md5($this->GenerateCode());
}
return $code;
}
function GenerateCode()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = preg_replace('/^0/', '', $id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function ForgottenPassword($params)
{
return $this->Application->GetVar('ForgottenPassword');
}
function TestCodeIsValid($params)
{
$passed_key = trim($this->Application->GetVar('user_key'));
// used for error reporting only -> rewrite code + theme (by Alex)
$user_current_object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too
/* @var $user_current_object UsersItem */
$code_type = isset($params['code_type']) ? $params['code_type'] : 'forgot_password';
$error_messages = Array (
'forgot_password' => Array (
'code_is_not_valid' => 'lu_code_is_not_valid',
'code_expired' => 'lu_code_expired',
),
'activation' => Array (
'code_is_not_valid' => 'lu_error_ActivationCodeNotValid',
'code_expired' => 'lu_error_ActivationCodeExpired',
),
);
if ($code_type == 'custom') {
// custom error messages are given directly in tag
$error_messages[$code_type] = Array (
'code_is_not_valid' => $params['error_invalid'],
'code_expired' => $params['error_expired'],
);
}
$expiration_timeouts = Array (
'forgot_password' => 'config:Users_AllowReset',
'activation' => 'config:UserEmailActivationTimeout',
'custom' => '',
);
if (!$passed_key) {
$user_current_object->SetError('PwResetConfirm', 'code_is_not_valid', $error_messages[$code_type]['code_is_not_valid']);
return false;
}
$user_object =& $this->Application->recallObject('u.forgot', null, Array('skip_autoload' => true));
/* @var $user_object UsersItems */
$user_object->Load($passed_key, 'PwResetConfirm');
if ( !$user_object->isLoaded() ) {
$user_current_object->SetError('PwResetConfirm', 'code_is_not_valid', $error_messages[$code_type]['code_is_not_valid']);
return false;
}
else {
$expiration_timeout = isset($params['expiration_timeout']) ? $params['expiration_timeout'] : $expiration_timeouts[$code_type];
if ( preg_match('/^config:(.*)$/', $expiration_timeout, $regs) ) {
$expiration_timeout = $this->Application->ConfigValue( $regs[1] );
}
if ( $expiration_timeout ) {
if ( $user_object->GetDBField('PwRequestTime') < strtotime('-' . $expiration_timeout . ' minutes') ) {
$user_current_object->SetError('PwResetConfirm', 'code_expired', $error_messages[$code_type]['code_expired']);
return false;
}
}
}
return true;
}
/**
* Returns sitem administrator email
*
* @param Array $params
* @return string
*/
function SiteAdminEmail($params)
{
return $this->Application->ConfigValue('Smtp_AdminMailFrom');
}
function AffiliatePaymentTypeChecked($params)
{
static $checked = false;
if( $this->Application->GetVar('PaymentTypeId') )
{
$apt_object =& $this->Application->recallObject('apt.active');
if( $this->Application->GetVar('PaymentTypeId') == $apt_object->GetDBField('PaymentTypeId') )
{
return 1;
}
else
{
return 0;
}
}
if(!$checked)
{
$checked = true;
return 1;
}
else
{
return 0;
}
}
function HasError($params)
{
$res = parent::HasError($params);
if($this->SelectParam($params,'field,fields') == 'any')
{
$res = $res || $this->Application->GetVar('MustAgreeToTerms'); // need to do it not put module fields into kernel ! (noticed by Alex)
$res = $res || $this->Application->GetVar('SSNRequiredError');
}
return $res;
}
/**
* Returns login name of user
*
* @param Array $params
*/
function LoginName($params)
{
$object =& $this->getObject($params);
return $object->GetID() != USER_ROOT ? $object->GetDBField('Login') : 'root';
}
function CookieUsername($params)
{
$submit_value = $this->Application->GetVar($params['submit_field']);
if ($submit_value !== false) {
return $submit_value;
}
$username = $this->Application->GetVar('save_username'); // from cookie
if ($username == 'super-root') {
$username = 'root';
}
return $username === false ? '' : $username;
}
/**
* Checks if user have one of required permissions
*
* @param Array $params
* @return bool
*/
function HasPermission($params)
{
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
return $perm_helper->TagPermissionCheck($params);
}
/**
* Returns link to user public profile
*
* @param Array $params
* @return string
*/
function ProfileLink($params)
{
$object =& $this->getObject($params);
$params['user_id'] = $object->GetID();
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
function ImageSrc($params)
{
list ($ret, $tag_processed) = $this->processAggregatedTag('ImageSrc', $params, $this->getPrefixSpecial());
return $tag_processed ? $ret : false;
}
function LoggedIn($params)
{
static $loggedin_status = Array ();
$object =& $this->getObject($params);
/* @var $object kDBList */
if (!isset($loggedin_status[$this->Special])) {
$user_ids = $object->GetCol($object->IDField);
$sql = 'SELECT LastAccessed, '.$object->IDField.'
FROM '.TABLE_PREFIX.'UserSession
WHERE (PortalUserId IN ('.implode(',', $user_ids).'))';
$loggedin_status[$this->Special] = $this->Conn->GetCol($sql, $object->IDField);
}
return isset($loggedin_status[$this->Special][$object->GetID()]);
}
/**
* Prints user activation link
*
* @param Array $params
* @return string
*/
function ActivationLink($params)
{
$code = $this->getCachedCode();
$fields_hash = Array (
'PwResetConfirm' => $code,
'PwRequestTime' => adodb_mktime(),
);
$object =& $this->getObject($params);
/* @var $object kDBItem */
$this->Conn->doUpdate($fields_hash, $object->TableName, $object->IDField . ' = ' . $object->GetID());
$params['user_key'] = $code;
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
/**
* Activates user using given code
*
* @param Array $params
*/
function ActivateUser($params)
{
$passed_key = trim($this->Application->GetVar('user_key'));
$user_helper =& $this->Application->recallObject('UserHelper');
/* @var $user_helper UserHelper */
$user =& $user_helper->getUserObject();
$user->Load($passed_key, 'PwResetConfirm');
if ( !$user->isLoaded() ) {
return ;
}
$user->SetDBField('Status', STATUS_ACTIVE);
$user->SetDBField('PwResetConfirm', '');
$user->SetDBField('PwRequestTime', 0);
$user->Update();
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
\ No newline at end of file
Index: branches/5.1.x/core/units/helpers/user_helper.php
===================================================================
--- branches/5.1.x/core/units/helpers/user_helper.php (revision 14477)
+++ branches/5.1.x/core/units/helpers/user_helper.php (revision 14478)
@@ -1,446 +1,447 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class UserHelper extends kHelper {
/**
* Event to be used during login processings
*
* @var kEvent
*/
var $event = null;
/**
* Performs user login and returns the result
*
* @param string $username
* @param string $password
* @param bool $dry_run
* @param bool $remember_login
* @param string $remember_login_cookie
* @return int
*/
function loginUser($username, $password, $dry_run = false, $remember_login = false, $remember_login_cookie = '')
{
if (!isset($this->event)) {
$this->event = new kEvent('u:OnLogin');
}
if (!$password && !$remember_login_cookie) {
return LOGIN_RESULT_INVALID_PASSWORD;
}
$object =& $this->getUserObject();
// process "Save Username" checkbox
if ($this->Application->isAdmin) {
$save_username = $this->Application->GetVar('cb_save_username') ? $username : '';
$this->Application->Session->SetCookie('save_username', $save_username, strtotime('+1 year'));
// cookie will be set on next refresh, but refresh won't occur if
// login error present, so duplicate cookie in kHTTPQuery
$this->Application->SetVar('save_username', $save_username);
}
// logging in "root" (admin only)
$super_admin = ($username == 'super-root') && $this->verifySuperAdmin();
if ($this->Application->isAdmin && ($username == 'root') || ($super_admin && $username == 'super-root')) {
$root_password = $this->Application->ConfigValue('RootPass');
$password_formatter =& $this->Application->recallObject('kPasswordFormatter');
if ($root_password != $password_formatter->EncryptPassword($password, 'b38')) {
return LOGIN_RESULT_INVALID_PASSWORD;
}
$user_id = USER_ROOT;
$object->Clear($user_id);
$object->SetDBField('Login', 'root');
if (!$dry_run) {
$this->loginUserById($user_id, $remember_login_cookie);
if ($super_admin) {
$this->Application->StoreVar('super_admin', 1);
}
// reset counters
$this->Application->resetCounters('UserSession');
$this->_processLoginRedirect('root', $password);
$this->_processInterfaceLanguage();
}
return LOGIN_RESULT_OK;
}
$user_id = $this->getUserId($username, $password, $remember_login_cookie);
if ($user_id) {
$object->Load($user_id);
if (!$this->checkBanRules($object)) {
return LOGIN_RESULT_BANNED;
}
if ($object->GetDBField('Status') == STATUS_ACTIVE) {
if ( !$this->checkLoginPermission() ) {
return LOGIN_RESULT_NO_PERMISSION;
}
if (!$dry_run) {
$this->loginUserById($user_id, $remember_login_cookie);
if ($remember_login) {
// remember username & password when "Remember Login" checkbox us checked (when user is using login form on Front-End)
$remember_login_cookie = $username . '|' . md5($password);
$this->Application->Session->SetCookie('remember_login', $remember_login_cookie, strtotime('+1 month'));
}
if (!$remember_login_cookie) {
// reset counters
$this->Application->resetCounters('UserSession');
$this->_processLoginRedirect($username, $password);
$this->_processInterfaceLanguage();
}
}
return LOGIN_RESULT_OK;
}
else {
$pending_template = $this->Application->GetVar('pending_disabled_template');
if ($pending_template !== false && !$dry_run) {
// when user found, but it's not yet approved redirect hit to notification template
$this->event->redirect = $pending_template;
return LOGIN_RESULT_OK;
}
else {
// when no notification template given return an error
return LOGIN_RESULT_INVALID_PASSWORD;
}
}
}
if (!$dry_run) {
$this->event->SetRedirectParam('pass', 'all');
// $this->event->SetRedirectParam('pass_category', 1); // to test
}
return LOGIN_RESULT_INVALID_PASSWORD;
}
/**
* Login username by it's PortalUserId
*
* @param int $user_id
* @param bool $remember_login_cookie
*/
function loginUserById($user_id, $remember_login_cookie = false)
{
$object =& $this->getUserObject();
$this->Application->StoreVar('user_id', $user_id);
$this->Application->SetVar('u.current_id', $user_id);
$this->Application->Session->SetField('PortalUserId', $user_id);
if ($user_id != USER_ROOT) {
$groups = $this->Application->RecallVar('UserGroups');
$this->Application->Session->SetField('GroupId', reset( explode(',', $groups) ));
$this->Application->Session->SetField('GroupList', $groups);
}
$this->Application->LoadPersistentVars();
if (!$remember_login_cookie) {
// don't change last login time when auto-login is used
$this_login = (int)$this->Application->RecallPersistentVar('ThisLogin');
$this->Application->StorePersistentVar('LastLogin', $this_login);
$this->Application->StorePersistentVar('ThisLogin', adodb_mktime());
}
$this->Application->HandleEvent($dummy, 'u:OnAfterLogin');
}
/**
* Checks login permission
*
* @return bool
*/
function checkLoginPermission()
{
$object =& $this->getUserObject();
$groups = $object->getMembershipGroups(true);
if (!$groups) {
$groups = Array();
}
// store groups, because kApplication::CheckPermission will use them!
array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') );
$this->Application->StoreVar( 'UserGroups', implode(',', $groups), true ); // true for optional
return $this->Application->CheckPermission($this->Application->isAdmin ? 'ADMIN' : 'LOGIN', 1);
}
/**
* Performs user logout
*
*/
function logoutUser()
{
if (!isset($this->event)) {
$this->event = new kEvent('u:OnLogout');
}
$sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize');
$sync_manager->performAction('LogoutUser');
$this->Application->HandleEvent($dummy, 'u:OnBeforeLogout');
$user_id = USER_GUEST;
$this->Application->SetVar('u.current_id', $user_id);
$object =& $this->Application->recallObject('u.current', null, Array('skip_autoload' => true));
$object->Load($user_id);
$this->Application->DestroySession();
$this->Application->StoreVar('user_id', $user_id, true);
$this->Application->Session->SetField('PortalUserId', $user_id);
$group_list = $this->Application->ConfigValue('User_GuestGroup') . ',' . $this->Application->ConfigValue('User_LoggedInGroup');
$this->Application->StoreVar('UserGroups', $group_list, true);
$this->Application->Session->SetField('GroupList', $group_list);
if ($this->Application->ConfigValue('UseJSRedirect')) {
$this->event->SetRedirectParam('js_redirect', 1);
}
$this->Application->resetCounters('UserSession');
$this->Application->Session->SetCookie('remember_login', '', strtotime('-1 hour'));
- $this->event->SetRedirectParam('pass', 'all');
+ // don't pass user prefix on logout, since resulting url will have broken "env"
+ $this->event->SetRedirectParam('pass', MOD_REWRITE ? 'm' : 'all');
}
/**
* Returns user id based on given criteria
*
* @param string $username
* @param string $password
* @param string $remember_login_cookie
* @return int
*/
function getUserId($username, $password, $remember_login_cookie)
{
$password = md5($password);
if ($remember_login_cookie) {
list ($username, $password) = explode('|', $remember_login_cookie); // 0 - username, 1 - md5(password)
}
$sql = 'SELECT PortalUserId
FROM ' . TABLE_PREFIX . 'PortalUser
WHERE (Email = %1$s OR Login = %1$s) AND (Password = %2$s)';
return $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($username), $this->Conn->qstr($password) ) );
}
/**
* Process all required data and redirect logged-in user
*
* @param string $username
* @param string $password
*/
function _processLoginRedirect($username, $password)
{
// set next template
$next_template = $this->Application->GetVar('next_template');
if ($next_template) {
$this->event->redirect = $next_template;
}
// process IIS redirect
if ($this->Application->ConfigValue('UseJSRedirect')) {
$this->event->SetRedirectParam('js_redirect', 1);
}
// syncronize login
$sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize');
$sync_manager->performAction('LoginUser', $username, $password);
}
/**
* Sets correct interface language after sucessful login, based on user settings
*
* @param kEvent $event
*/
function _processInterfaceLanguage()
{
if (!$this->Application->isAdmin) {
return ;
}
$is_root = $this->Application->RecallVar('user_id') == USER_ROOT;
$object =& $this->getUserObject();
$user_language_id = $is_root ? $this->Application->RecallPersistentVar('AdminLanguage') : $object->GetDBField('AdminLanguage');
$sql = 'SELECT LanguageId, IF(LanguageId = ' . (int)$user_language_id . ', 2, AdminInterfaceLang) AS SortKey
FROM ' . TABLE_PREFIX . 'Language
WHERE Enabled = 1
HAVING SortKey <> 0
ORDER BY SortKey DESC';
$language_info = $this->Conn->GetRow($sql);
$language_id = $language_info && $language_info['LanguageId'] ? $language_info['LanguageId'] : $user_language_id;
if ($user_language_id != $language_id) {
// first admin login OR language was delelted or disabled
if ($is_root) {
$this->Application->StorePersistentVar('AdminLanguage', $language_id);
}
else {
$object->SetDBField('AdminLanguage', $language_id);
$object->Update();
}
}
$this->event->SetRedirectParam('m_lang', $language_id); // data
$this->Application->Session->SetField('Language', $language_id); // interface
}
/**
* Checks that user is allowed to use super admin mode
*
* @return bool
*/
function verifySuperAdmin()
{
$sa_mode = ipMatch(defined('SA_IP') ? SA_IP : '');
return $sa_mode || $this->Application->isDebugMode();
}
/**
* Returns user object, used during login processings
*
* @return UsersItem
*/
function &getUserObject()
{
$prefix_special = $this->Application->isAdmin ? 'u.current' : 'u'; // "u" used on front not to change theme
$object =& $this->Application->recallObject($prefix_special, null, Array('skip_autoload' => true));
return $object;
}
/**
* Checks, if given user fields matches at least one of defined ban rules
*
* @param kDBItem $object
* @return bool
*/
function checkBanRules(&$object)
{
$table = $this->Application->getUnitOption('ban-rule', 'TableName');
if (!$this->Conn->TableFound($table)) {
// when ban table not found -> assume user is ok by default
return true;
}
$sql = 'SELECT *
FROM ' . $table . '
WHERE ItemType = 6 AND Status = ' . STATUS_ACTIVE . '
ORDER BY Priority DESC';
$rules = $this->Conn->Query($sql);
$found = false;
foreach ($rules as $rule) {
$field = $rule['ItemField'];
$this_value = mb_strtolower( $object->GetDBField($field) );
$test_value = mb_strtolower( $rule['ItemValue'] );
switch ( $rule['ItemVerb'] ) {
case 1: // is
if ($this_value == $test_value) {
$found = true;
}
break;
case 2: // is not
if ($this_value != $test_value) {
$found = true;
}
break;
case 3: // contains
if ( strstr($this_value, $test_value) ) {
$found = true;
}
break;
case 4: // not contains
if ( !strstr($this_value, $test_value) ) {
$found = true;
}
break;
case 7: // exists
if ( strlen($this_value) > 0 ) {
$found = true;
}
break;
case 8: // unique
if ( $this->_checkValueExist($field, $this_value) ) {
$found = true;
}
break;
}
if ( $found ) {
// check ban rules, until one of them matches
if ( $rule['RuleType'] ) {
// invert rule type
$found = false;
}
break;
}
}
return !$found;
}
/**
* Checks if value is unique in Users table against the specified field
*
* @param string $field
* @param string $value
* @return string
*/
function _checkValueExist($field, $value)
{
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('u', 'TableName') . '
WHERE '. $field .' = ' . $this->Conn->qstr($value);
return $this->Conn->GetOne($sql);
}
}

Event Timeline