0byt3m1n1-V2
Path:
/
home
/
a
/
c
/
a
/
academiac
/
www
/
[
Home
]
File: user.php.tar
home/academiac/www/administrator/components/com_virtuemart/models/user.php 0000604 00000141265 15137216075 0023302 0 ustar 00 <?php /** * * Data module for shop users * * @package VirtueMart * @subpackage User * @author Oscar van Eijk * @author Max Milbers * @author RickG * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to 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. * @version $Id: user.php 6543 2012-10-16 06:41:27Z Milbo $ */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); // Hardcoded groupID of the Super Admin define ('__SUPER_ADMIN_GID', 25); // Load the model framework jimport('joomla.version'); if(!class_exists('VmModel'))require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmmodel.php'); /** * Model class for shop users * * @package VirtueMart * @subpackage User * @author RickG * @author Max Milbers */ class VirtueMartModelUser extends VmModel { /** * Constructor for the user model. * * The user ID is read and determined if it is an array of ids or just one single id. */ function __construct(){ parent::__construct('virtuemart_user_id'); $this->setMainTable('vmusers'); $this->setToggleName('user_is_vendor'); $this->addvalidOrderingFieldName(array('ju.username','ju.name','sg.virtuemart_shoppergroup_id','shopper_group_name','shopper_group_desc') ); array_unshift($this->_validOrderingFieldName,'ju.id'); // $user = JFactory::getUser(); // $this->_id = $user->id; } /** * public function Resets the user id and data * * * @author Max Milbers */ public function setId($cid){ $user = JFactory::getUser(); //anonymous sets to 0 for a new entry if(empty($user->id)){ $userId = 0; //echo($this->_id,'Recognized anonymous case'); } else { //not anonymous, but no cid means already registered user edit own data if(empty($cid)){ $userId = $user->id; // vmdebug('setId setCurrent $user',$user->get('id')); } else { if($cid != $user->id){ if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check("admin")) { $userId = $cid; // vmdebug('Admin watches user, setId '.$cid); } else { JError::raiseWarning(1,'Hacking attempt'); $userId = $user->id; } }else { $userId = $user->id; } } } $this->setUserId($userId); return $userId; } /** * Internal function * * @param unknown_type $id */ private function setUserId($id){ $app = JFactory::getApplication(); // if($app->isAdmin()){ if($this->_id!=$id){ $this->_id = (int)$id; $this->_data = null; $this->customer_number = 0; } // } } public function getCurrentUser(){ $user = JFactory::getUser(); $this->setUserId($user->id); return $this->getUser(); } private $_defaultShopperGroup = 0; /** * Sets the internal user id with given vendor Id * * @author Max Milbers * @param int $vendorId */ function getVendor($vendorId=1,$return=TRUE){ $vendorModel = VmModel::getModel('vendor'); $userId = VirtueMartModelVendor::getUserIdByVendorId($vendorId); if($userId){ $this->setUserId($userId); if($return){ return $this->getUser(); } } else { return false; } } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * @author Max Milbers */ function getUser(){ if(!empty($this->_data)) return $this->_data; if(empty($this->_db)) $this->_db = JFactory::getDBO(); $this->_data = $this->getTable('vmusers'); $this->_data->load((int)$this->_id); // vmdebug('$this->_data->vmusers',$this->_data); $this->_data->JUser = JUser::getInstance($this->_id); // vmdebug('$this->_data->JUser',$this->_data->JUser); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); $this->_data->perms = Permissions::getInstance()->getPermissions((int)$this->_id); // Add the virtuemart_shoppergroup_ids $xrefTable = $this->getTable('vmuser_shoppergroups'); $this->_data->shopper_groups = $xrefTable->load($this->_id); $shoppergroupmodel = VmModel::getModel('ShopperGroup'); $site = JFactory::getApplication ()->isSite (); if($site){ if(empty($this->_data->shopper_groups)) $this->_data->shopper_groups = array(); $shoppergroupmodel->appendShopperGroups($this->_data->shopper_groups,$this->_data->JUser,$site); } if(!empty($this->_id)) { $q = 'SELECT `virtuemart_userinfo_id` FROM `#__virtuemart_userinfos` WHERE `virtuemart_user_id` = "' . (int)$this->_id.'"'; $this->_db->setQuery($q); $userInfo_ids = $this->_db->loadResultArray(0); } else { $userInfo_ids = array(); } // vmdebug('my query',$this->_db->getQuery()); //vmdebug('my $_ui',$userInfo_ids,$this->_id); $this->_data->userInfo = array (); $BTuid = 0; foreach($userInfo_ids as $uid){ $this->_data->userInfo[$uid] = $this->getTable('userinfos'); $this->_data->userInfo[$uid]->load($uid); if ($this->_data->userInfo[$uid]->address_type == 'BT') { $BTuid = $uid; $this->_data->userInfo[$BTuid]->name = $this->_data->JUser->name; $this->_data->userInfo[$BTuid]->email = $this->_data->JUser->email; $this->_data->userInfo[$BTuid]->username = $this->_data->JUser->username; $this->_data->userInfo[$BTuid]->address_type = 'BT'; // vmdebug('$this->_data->vmusers',$this->_data); } } // vmdebug('user_is_vendor ?',$this->_data->user_is_vendor); if($this->_data->user_is_vendor){ $vendorModel = VmModel::getModel('vendor'); if(Vmconfig::get('multix','none')=='none'){ $this->_data->virtuemart_vendor_id = 1; //vmdebug('user model, single vendor',$this->_data->virtuemart_vendor_id); } $vendorModel->setId($this->_data->virtuemart_vendor_id); $this->_data->vendor = $vendorModel->getVendor(); } return $this->_data; } /** * Retrieve contact info for a user if any * * @return array of null */ function getContactDetails() { if ($this->_id) { $this->_db->setQuery('SELECT * FROM #__contact_details WHERE user_id = ' . $this->_id); $_contacts = $this->_db->loadObjectList(); if (count($_contacts) > 0) { return $_contacts[0]; } } return null; } /** * Functions belonging to get_groups_below_me Taken with correspondence from CommunityBuilder * adjusted to the our needs * @version $Id: user.php 6543 2012-10-16 06:41:27Z Milbo $ * @package Community Builder * @subpackage cb.acl.php * @author Beat and mambojoe * @author Max Milbers * @copyright (C) Beat, www.joomlapolis.com * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2 */ function get_object_id( $var_1 = null, $var_2 = null, $var_3 = null ) { if ( JVM_VERSION === 2) { $return = $var_2; } else { $return = $this->_acl->get_object_id( $var_1, $var_2, $var_3 ); } return $return; } /** * Taken with correspondence from CommunityBuilder * adjusted to the our needs * @version $Id: user.php 6543 2012-10-16 06:41:27Z Milbo $ * @package Community Builder * @subpackage cb.acl.php * @author Beat and mambojoe * @author Max Milbers * @copyright (C) Beat, www.joomlapolis.com * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2 */ function get_object_groups( $var_1 = null, $var_2 = null, $var_3 = null ) { if ( version_compare(JVERSION,'1.6.0','ge') ) { $user_id = ( is_integer( $var_1 ) ? $var_1 : $var_2 ); $recurse = ( $var_3 == 'RECURSE' ? true : false ); $return = $this->_acl->getGroupsByUser( $user_id, $recurse ); } else { if ( ! $var_2 ) { $var_2 = 'ARO'; } if ( ! $var_3 ) { $var_3 = 'NO_RECURSE'; } $return = $this->_acl->get_object_groups( $var_1, $var_2, $var_3 ); } return $return; } /** * Remap literal groups (such as in default values) to the hardcoded CMS values * * @param string|array $name of int|string * @return int|array of int */ function mapGroupNamesToValues( $name ) { static $ps = null; $selected = (array) $name; foreach ( $selected as $k => $v ) { if ( ! is_numeric( $v ) ) { if ( ! $ps ) { if ( JVM_VERSION === 2 ) { $ps = array( 'Root' => 0 , 'Users' => 0 , 'Public' => 1, 'Registered' => 2, 'Author' => 3, 'Editor' => 4, 'Publisher' => 5, 'Backend' => 0 , 'Manager' => 6, 'Administrator' => 7, 'Superadministrator' => 8 ); } else { $ps = array( 'Root' => 17, 'Users' => 28, 'Public' => 29, 'Registered' => 18, 'Author' => 19, 'Editor' => 20, 'Publisher' => 21, 'Backend' => 30, 'Manager' => 23, 'Administrator' => 24, 'Superadministrator' => 25 ); } } if ( array_key_exists( $v, $ps ) ) { if ( $ps[$v] != 0 ) { $selected[$k] = $ps[$v]; } else { unset( $selected[$k] ); } } else { $selected[$k] = (int) $v; } } } if ( ! is_array( $name ) ) { $selected = $selected[0]; } return $selected; } function get_group_children_tree( $var_1 = null, $var_2 = null, $var_3 = null, $var_4 = null ) { $_CB_database = &$this->getDbo(); if ( ! $var_4 ) { $var_4 = true; } if ( JVM_VERSION === 2 ) { $query = 'SELECT a.' . $_CB_database->NameQuote( 'id' ) . ' AS value' . ', a.' . $_CB_database->NameQuote( 'title' ) . ' AS text' . ', COUNT( DISTINCT b.' . $_CB_database->NameQuote( 'id' ) . ' ) AS level' . "\n FROM " . $_CB_database->NameQuote( '#__usergroups' ) . " AS a" . "\n LEFT JOIN " . $_CB_database->NameQuote( '#__usergroups' ) . " AS b" . ' ON a.' . $_CB_database->NameQuote( 'lft' ) . ' > b.' . $_CB_database->NameQuote( 'lft' ) . ' AND a.' . $_CB_database->NameQuote( 'rgt' ) . ' < b.' . $_CB_database->NameQuote( 'rgt' ) . "\n GROUP BY a." . $_CB_database->NameQuote( 'id' ) . "\n ORDER BY a." . $_CB_database->NameQuote( 'lft' ) . " ASC"; $_CB_database->setQuery( $query ); $groups = $_CB_database->loadObjectList(); $user_groups = array(); for ( $i = 0, $n = count( $groups ); $i < $n; $i++ ) { $groups[$i]->text = str_repeat( '- ', $groups[$i]->level ) . JText::_( $groups[$i]->text ); if ( $var_4 ) { $user_groups[$i] = JHtml::_( 'select.option', $groups[$i]->value, $groups[$i]->text ); } else { $user_groups[$i] = array( 'value' => $groups[$i]->value, 'text' => $groups[$i]->text ); } } $return = $user_groups; } else { if ( ! $var_3 ) { $var_3 = true; } $return = $this->_acl->get_group_children_tree( $var_1, $var_2, $var_3, $var_4 ); } return $return; } /** * Return a list with groups that can be set by the current user * * @return mixed Array with groups that can be set, or the groupname (string) if it cannot be changed. */ function getGroupList() { if(JVM_VERSION === 2) { //hm CB thing also not help // $_grpList = $this->get_groups_below_me(); // return $_grpList; /* if(!class_exists('UsersModelUser')) require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_users'.DS.'models'.DS.'user.php'); $jUserModel = new UsersModelUser(); $list = $jUserModel->getGroups(); $user = JFactory::getUser(); if ($user->authorise('core.edit', 'com_users') && $user->authorise('core.manage', 'com_users')) { $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true)); return $model->getItems(); } else { return null; }*/ $user = JFactory::getUser(); $authGroups = JAccess::getGroupsByUser($user->id); // $authGroups = $user->getAuthorisedGroups(); // vmdebug('getGroupList j17',$authGroups); $db = $this->getDbo(); $where = implode($authGroups,'" OR `id` = "').'"'; $q = 'SELECT `id` as value,`title` as text FROM #__usergroups WHERE `id` = "'.$where; $db->setQuery($q); $list = $db->loadAssocList(); // foreach($list as $item){ // vmdebug('getGroupList $item ',$item); // } // vmdebug('getGroupList $q '.$list); return $list; } else { $_aclObject = JFactory::getACL(); if(empty($this->_data)) $this->getUser(); if (JVM_VERSION>1){ //TODO fix this latter. It's just an workarround to make it working on 1.6 $gids = $this->_data->JUser->get('groups'); return array_flip($gids); } $_usr = $_aclObject->get_object_id ('users', $this->_data->JUser->get('id'), 'ARO'); $_grp = $_aclObject->get_object_groups ($_usr, 'ARO'); $_grpName = strtolower ($_aclObject->get_group_name($_grp[0], 'ARO')); $_currentUser = JFactory::getUser(); $_my_usr = $_aclObject->get_object_id ('users', $_currentUser->get('id'), 'ARO'); $_my_grp = $_aclObject->get_object_groups ($_my_usr, 'ARO'); $_my_grpName = strtolower ($_aclObject->get_group_name($_my_grp[0], 'ARO')); // administrators can't change each other and frontend-only users can only see groupnames if (( $_grpName == $_my_grpName && $_my_grpName == 'administrator' ) || !$_aclObject->is_group_child_of($_my_grpName, 'Public Backend')) { return $_grpName; } else { $_grpList = $_aclObject->get_group_children_tree(null, 'USERS', false); $_remGroups = $_aclObject->get_group_children( $_my_grp[0], 'ARO', 'RECURSE' ); if (!$_remGroups) { $_remGroups = array(); } // Make sure privs higher than my own can't be granted if (in_array($_grp[0], $_remGroups)) { // nor can privs of users with higher privs be decreased. return $_grpName; } $_i = 0; $_j = count($_grpList); while ($_i < $_j) { if (in_array($_grpList[$_i]->value, $_remGroups)) { array_splice( $_grpList, $_i, 1 ); $_j = count($_grpList); } else { $_i++; } } return $_grpList; } } } /** * Bind the post data to the JUser object and the VM tables, then saves it * It is used to register new users * This function can also change already registered users, this is important when a registered user changes his email within the checkout. * * @author Max Milbers * @author Oscar van Eijk * @return boolean True is the save was successful, false otherwise. */ public function store(&$data,$checkToken = TRUE){ $message = ''; $user = ''; $newId = 0; if($checkToken){ JRequest::checkToken() or jexit( 'Invalid Token, while trying to save user' ); $mainframe = JFactory::getApplication() ; } if(empty($data)){ vmError('Developer notice, no data to store for user'); return false; } //To find out, if we have to register a new user, we take a look on the id of the usermodel object. //The constructor sets automatically the right id. $new = ($this->_id < 1); if(empty($this->_id)){ $user = new JUser(); //thealmega http://forum.virtuemart.net/index.php?topic=99755.msg393758#msg393758 } else { $user = JFactory::getUser($this->_id); } $gid = $user->get('gid'); // Save original gid // Preformat and control user datas by plugin JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $valid = true ; $dispatcher->trigger('plgVmOnBeforeUserfieldDataSave',array(&$valid,$this->_id,&$data,$user )); // $valid must be false if plugin detect an error if( $valid == false ) { return false; } // Before I used this "if($cart && !$new)" // This construction is necessary, because this function is used to register a new JUser, so we need all the JUser data in $data. // On the other hand this function is also used just for updating JUser data, like the email for the BT address. In this case the // name, username, password and so on is already stored in the JUser and dont need to be entered again. if(empty ($data['email'])){ $email = $user->get('email'); if(!empty($email)){ $data['email'] = $email; } } else { $data['email'] = JRequest::getString('email', '', 'post', 'email'); } $data['email'] = str_replace(array('\'','"',',','%','*','/','\\','?','^','`','{','}','|','~'),array(''),$data['email']); //This is important, when a user changes his email address from the cart, //that means using view user layout edit_address (which is called from the cart) $user->set('email',$data['email']); if(empty ($data['name'])){ $name = $user->get('name'); if(!empty($name)){ $data['name'] = $name; } } else { $data['name'] = JRequest::getString('name', '', 'post', 'name'); } $data['name'] = str_replace(array('\'','"',',','%','*','/','\\','?','^','`','{','}','|','~'),array(''),$data['name']); if(empty ($data['username'])){ $username = $user->get('username'); if(!empty($username)){ $data['username'] = $username; } else { $data['username'] = JRequest::getVar('username', '', 'post', 'username'); } } if(empty ($data['password'])){ $data['password'] = JRequest::getVar('password', '', 'post', 'string' ,JREQUEST_ALLOWRAW); } if(empty ($data['password2'])){ $data['password2'] = JRequest::getVar('password2', '', 'post', 'string' ,JREQUEST_ALLOWRAW); } if(!$new && !empty($data['password']) && empty($data['password2'])){ unset($data['password']); unset($data['password2']); } // Bind Joomla userdata if (!$user->bind($data)) { foreach($user->getErrors() as $error) { // vmError('user bind '.$error); vmError('user bind '.$error,JText::sprintf('COM_VIRTUEMART_USER_STORE_ERROR',$error)); } $message = 'Couldnt bind data to joomla user'; array('user'=>$user,'password'=>$data['password'],'message'=>$message,'newId'=>$newId,'success'=>false); } if($new){ // If user registration is not allowed, show 403 not authorized. // But it is possible for admins and storeadmins to save $usersConfig = JComponentHelper::getParams( 'com_users' ); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if (!Permissions::getInstance()->check("admin,storeadmin") && $usersConfig->get('allowUserRegistration') == '0') { VmConfig::loadJLang('com_virtuemart'); JError::raiseError( 403, JText::_('COM_VIRTUEMART_ACCESS_FORBIDDEN')); return; } $authorize = JFactory::getACL(); // Initialize new usertype setting $newUsertype = $usersConfig->get( 'new_usertype' ); if (!$newUsertype) { if ( JVM_VERSION===1){ $newUsertype = 'Registered'; } else { $newUsertype = 2; } } // Set some initial user values $user->set('usertype', $newUsertype); if ( JVM_VERSION===1){ $user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' )); } else { $user->groups[] = $newUsertype; } $date = JFactory::getDate(); $user->set('registerDate', $date->toMySQL()); // If user activation is turned on, we need to set the activation information $useractivation = $usersConfig->get( 'useractivation' ); $doUserActivation=false; if ( JVM_VERSION===1){ if ($useractivation == '1' ) { $doUserActivation=true; } } else { if ($useractivation == '1' or $useractivation == '2') { $doUserActivation=true; } } vmdebug('user',$useractivation , $doUserActivation); if ($doUserActivation ) { jimport('joomla.user.helper'); $user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) ); $user->set('block', '1'); //$user->set('lastvisitDate', '0000-00-00 00:00:00'); } } $option = JRequest::getCmd( 'option'); // If an exising superadmin gets a new group, make sure enough admins are left... if (!$new && $user->get('gid') != $gid && $gid == __SUPER_ADMIN_GID) { if ($this->getSuperAdminCount() <= 1) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_ONLYSUPERADMIN')); return false; } } if(isset($data['language'])){ $user->setParam('language',$data['language']); } // Save the JUser object if (!$user->save()) { vmError(JText::_( $user->getError()) , JText::_( $user->getError())); return false; } //vmdebug('my user, why logged in? ',$user); $newId = $user->get('id'); $data['virtuemart_user_id'] = $newId; //We need this in that case, because data is bound to table later $this->setUserId($newId); //Save the VM user stuff if(!$this->saveUserData($data) || !self::storeAddress($data)){ vmError('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USER_DATA'); // vmError(Jtext::_('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USERINFO_DATA')); } else { if ($new) { $this->sendRegistrationEmail($user,$user->password_clear, $doUserActivation); if ($doUserActivation ) { vmInfo('COM_VIRTUEMART_REG_COMPLETE_ACTIVATE'); } else { vmInfo('COM_VIRTUEMART_REG_COMPLETE'); $user->set('activation', '' ); $user->set('block', '0'); $user->set('guest', '0'); } } else { vmInfo('COM_VIRTUEMART_USER_DATA_STORED'); } } //The extra check for isset vendor_name prevents storing of the vendor if there is no form (edit address cart) if((int)$data['user_is_vendor']==1 and isset($data['vendor_name'])){ vmdebug('vendor recognised '.$data['virtuemart_vendor_id']); if($this ->storeVendorData($data)){ if ($new) { if ($doUserActivation ) { vmInfo('COM_VIRTUEMART_REG_VENDOR_COMPLETE_ACTIVATE'); } else { vmInfo('COM_VIRTUEMART_REG_VENDOR_COMPLETE'); } } else { vmInfo('COM_VIRTUEMART_VENDOR_DATA_STORED'); } } } return array('user'=>$user,'password'=>$data['password'],'message'=>$message,'newId'=>$newId,'success'=>true); } /** * This function is NOT for anonymous. Anonymous just get the information directly sent by email. * This function saves the vm Userdata for registered JUsers. * TODO, setting of shoppergroup isnt done * * TODO No reason not to use this function for new users, but it requires a Joomla <user> plugin * that gets fired by the onAfterStoreUser. I'll built that (OvE) * * Notice: * As long we do not have the silent registration, an anonymous does not get registered. It is enough to send the virtuemart_order_id * with the email. The order is saved with all information in an extra table, so there is * no need for a silent registration. We may think about if we actually need/want the feature silent registration * The information of anonymous is stored in the order table and has nothing todo with the usermodel! * * @author Max Milbers * @author Oscar van Eijk * return boolean */ public function saveUserData(&$data,$trigger=true){ if(empty($this->_id)){ echo 'This is a notice for developers, you used this function for an anonymous user, but it is only designed for already registered ones'; vmError( 'This is a notice for developers, you used this function for an anonymous user, but it is only designed for already registered ones'); return false; } $noError = true; $usertable = $this->getTable('vmusers'); $alreadyStoredUserData = $usertable->load($this->_id); $app = JFactory::getApplication(); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin")){ unset($data['virtuemart_vendor_id']); unset($data['user_is_vendor']); $data['user_is_vendor'] = $alreadyStoredUserData->user_is_vendor; $data['virtuemart_vendor_id'] = $alreadyStoredUserData->virtuemart_vendor_id; } else { if(!isset($data['user_is_vendor']) and !empty($alreadyStoredUserData->user_is_vendor)){ $data['user_is_vendor'] = $alreadyStoredUserData->user_is_vendor; } if(!isset($data['virtuemart_vendor_id']) and !empty($alreadyStoredUserData->virtuemart_vendor_id)){ $data['virtuemart_vendor_id'] = $alreadyStoredUserData->virtuemart_vendor_id; } } unset($data['customer_number']); if(empty($alreadyStoredUserData->customer_number)){ //if(!class_exists('vmUserPlugin')) require(JPATH_VM_SITE.DS.'helpers'.DS.'vmuserplugin.php'); ///if(!$returnValues){ $data['customer_number'] = strtoupper(substr($data['username'],0,2)).substr(md5($data['username']),0,9); //We set this data so that vmshopper plugin know if they should set the customer nummer $data['customer_number_bycore'] = 1; //} } else { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin,storeadmin")) { $data['customer_number'] = $alreadyStoredUserData->customer_number; } } if($app->isSite()){ unset($data['perms']); if(!empty($alreadyStoredUserData->perms)){ $data['perms'] = $alreadyStoredUserData->perms; } else { $data['perms'] = 'shopper'; } } else { } if($trigger){ JPluginHelper::importPlugin('vmshopper'); $dispatcher = JDispatcher::getInstance(); $plg_datas = $dispatcher->trigger('plgVmOnUserStore',array(&$data)); foreach($plg_datas as $plg_data){ // $data = array_merge($plg_data,$data); } } $usertable -> bindChecknStore($data); $errors = $usertable->getErrors(); foreach($errors as $error){ $this->setError($error); vmError('storing user adress data'.$error); $noError = false; } if(Permissions::getInstance()->check("admin,storeadmin")) { $shoppergroupmodel = VmModel::getModel('ShopperGroup'); if(empty($this->_defaultShopperGroup)){ $this->_defaultShopperGroup = $shoppergroupmodel->getDefault(0); } if(empty($data['virtuemart_shoppergroup_id']) or $data['virtuemart_shoppergroup_id']==$this->_defaultShopperGroup->virtuemart_shoppergroup_id){ $data['virtuemart_shoppergroup_id'] = array(); } // Bind the form fields to the table if(!empty($data['virtuemart_shoppergroup_id'])){ $shoppergroupData = array('virtuemart_user_id'=>$this->_id,'virtuemart_shoppergroup_id'=>$data['virtuemart_shoppergroup_id']); $user_shoppergroups_table = $this->getTable('vmuser_shoppergroups'); $shoppergroupData = $user_shoppergroups_table -> bindChecknStore($shoppergroupData); $errors = $user_shoppergroups_table->getErrors(); foreach($errors as $error){ $this->setError($error); vmError('Set shoppergroup '.$error); $noError = false; } } } if($trigger){ $plg_datas = $dispatcher->trigger('plgVmAfterUserStore',array($data)); foreach($plg_datas as $plg_data){ $data = array_merge($plg_data); } } return $noError; } public function storeVendorData($data){ if($data['user_is_vendor']){ $vendorModel = VmModel::getModel('vendor'); //TODO Attention this is set now to virtuemart_vendor_id=1, because using a vendor with different id then 1 is not completly supported and can lead to bugs //So we disable the possibility to store vendors not with virtuemart_vendor_id = 1 if(Vmconfig::get('multix','none')=='none' ){ $data['virtuemart_vendor_id'] = 1; vmdebug('no multivendor, set virtuemart_vendor_id = 1'); } $vendorModel->setId($data['virtuemart_vendor_id']); if(empty($data['vendor_store_name']) and !empty($data['company'])) $data['vendor_store_name'] = $data['company']; if (!$vendorModel->store($data)) { vmError('storeVendorData '.$vendorModel->getError()); vmdebug('Error storing vendor',$vendorModel); return false; } } return true; } /** * Take a data array and save any address info found in the array. * * @author unknown, oscar, max milbers * @param array $data (Posted) user data * @param sting $_table Table name to write to, null (default) not to write to the database * @param boolean $_cart Attention, this was deleted, the address to cart is now done in the controller (True to write to the session (cart)) * @return boolean True if the save was successful, false otherwise. */ function storeAddress(&$data){ // if(empty($data['address_type'])){ // vmError('storeAddress no address_type given'); // return false; // } $user =JFactory::getUser(); $userinfo = $this->getTable('userinfos'); if($data['address_type'] == 'BT'){ if(isset($data['virtuemart_userinfo_id']) and $data['virtuemart_userinfo_id']!=0){ $data['virtuemart_userinfo_id'] = (int)$data['virtuemart_userinfo_id']; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); if(!Permissions::getInstance()->check('admin')){ $userinfo->load($data['virtuemart_userinfo_id']); if($userinfo->virtuemart_user_id!=$user->id){ vmError('Hacking attempt as admin?','Hacking attempt storeAddress'); return false; } } } else { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); //Todo multi-x, also vendors should be allowed to change the user address. if(!Permissions::getInstance()->check('admin')){ $userId = $user->id; } else { $userId = (int)$data['virtuemart_user_id']; } $q = 'SELECT `virtuemart_userinfo_id` FROM #__virtuemart_userinfos WHERE `virtuemart_user_id` = '.$userId.' AND `address_type` = "BT"'; $this->_db->setQuery($q); $total = $this->_db->loadResultArray(); if (count($total) > 0) { $data['virtuemart_userinfo_id'] = (int)$total[0]; } else { $data['virtuemart_userinfo_id'] = 0;//md5(uniqid($this->virtuemart_user_id)); } $userinfo->load($data['virtuemart_userinfo_id']); //unset($data['virtuemart_userinfo_id']); } if(!$this->validateUserData((array)$data,'BT')){ return false; } $userInfoData = self::_prepareUserFields($data, 'BT',$userinfo); //vmdebug('model user storeAddress',$data); if (!$userinfo->bindChecknStore($userInfoData)) { vmError('storeAddress '.$userinfo->getError()); } } // Check for fields with the the 'shipto_' prefix; that means a (new) shipto address. if($data['address_type'] == 'ST' or isset($data['shipto_address_type_name'])){ $dataST = array(); $_pattern = '/^shipto_/'; foreach ($data as $_k => $_v) { if (preg_match($_pattern, $_k)) { $_new = preg_replace($_pattern, '', $_k); $dataST[$_new] = $_v; } } $userinfo = $this->getTable('userinfos'); if(isset($dataST['virtuemart_userinfo_id']) and $dataST['virtuemart_userinfo_id']!=0){ $dataST['virtuemart_userinfo_id'] = (int)$dataST['virtuemart_userinfo_id']; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); if(!Permissions::getInstance()->check('admin')){ $userinfo->load($dataST['virtuemart_userinfo_id']); $user = JFactory::getUser(); if($userinfo->virtuemart_user_id!=$user->id){ vmError('Hacking attempt as admin?','Hacking attempt store address'); return false; } } } if(empty($userinfo->virtuemart_user_id)){ if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); if(!Permissions::getInstance()->check('admin')){ $dataST['virtuemart_user_id'] = $user->id; } else { if(isset($data['virtuemart_user_id'])){ $dataST['virtuemart_user_id'] = (int)$data['virtuemart_user_id']; } else { //Disadvantage is that admins should not change the ST address in the FE (what should never happen anyway.) $dataST['virtuemart_user_id'] = $user->id; } } } if(!$this->validateUserData((array)$dataST,'ST')){ return false; } $dataST['address_type'] = 'ST'; $userfielddata = self::_prepareUserFields($dataST, 'ST',$userinfo); if (!$userinfo->bindChecknStore($userfielddata)) { vmError($userinfo->getError()); } } return $userinfo->virtuemart_userinfo_id; } /** * Test userdata if valid * * @author Max Milbers * @param String if BT or ST * @param Object If given, an object with data address data that must be formatted to an array * @return redirectMsg, if there is a redirectMsg, the redirect should be executed after */ public function validateUserData($data,$type='BT') { if (!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'userfields.php'); $userFieldsModel = VmModel::getModel('userfields'); if ($type == 'BT') { $fieldtype = 'account'; }else { $fieldtype = 'shipment'; } $neededFields = $userFieldsModel->getUserFields( $fieldtype , array('required' => true, 'delimiters' => true, 'captcha' => true, 'system' => false) , array('delimiter_userinfo', 'name','username', 'password', 'password2', 'address_type_name', 'address_type', 'user_is_vendor', 'agreed')); $i = 0; $j = 0; $return = true; $required = 0; //$objSize = count($data); $missingFields = array(); foreach ($neededFields as $field) { //This is a special test for the virtuemart_state_id. There is the speciality that the virtuemart_state_id could be 0 but is valid. if ($field->name == 'virtuemart_state_id') { if (!class_exists('VirtueMartModelState')) require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'state.php'); if(!empty($data['virtuemart_country_id'])){ if(!isset($data['virtuemart_state_id'])) $data['virtuemart_state_id'] = 0; if (!$msg = VirtueMartModelState::testStateCountry($data['virtuemart_country_id'], $data['virtuemart_state_id'])) { //The state is invalid, so we set the state 0 here. $data['virtuemart_state_id'] = 0; vmdebug('State was not fitting to country, set to 0'); } else if(empty($data['virtuemart_state_id'])){ vmdebug('virtuemart_state_id is empty, but valid (country has not states, set to unrequired'); $field->required = false; } else { vmdebug('validateUserData my country '.$data['virtuemart_country_id'].' my state '.$data['virtuemart_state_id']); } } } if($field->required ){ $required++; if(empty($data[$field->name])){ $missingFields[] = JText::_($field->title); $i++; $return = false; } else if($data[$field->name] == $field->default){ $i++; } else { } } } if($i==$required) $return = -1; //vmdebug('my i '.$i.' my data size '.$required,$return,$data); if(!$return){ VmConfig::loadJLang('com_virtuemart_shoppers', true); foreach($missingFields as $fieldname){ vmInfo(JText::sprintf('COM_VIRTUEMART_MISSING_VALUE_FOR_FIELD',$fieldname) ); vmdebug(''); } } return $return; } function _prepareUserFields(&$data, $type,$userinfo = 0) { if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php' ); $userFieldsModel = VmModel::getModel('userfields'); if ($type == 'ST') { $prepareUserFields = $userFieldsModel->getUserFields( 'shipment' , array() // Default toggles ); } else { // BT // The user is not logged in (anonymous), so we need tome extra fields $prepareUserFields = $userFieldsModel->getUserFields( 'account' , array() // Default toggles , array('delimiter_userinfo', 'name', 'username', 'password', 'password2', 'user_is_vendor') // Skips ); } $admin = false; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check('admin','storeadmin')){ $admin = true; } // Format the data foreach ($prepareUserFields as $fld) { if(empty($data[$fld->name])) $data[$fld->name] = ''; if(!$admin and $fld->readonly){ $fldName = $fld->name; unset($data[$fldName]); if($userinfo!==0){ if(property_exists($userinfo,$fldName)){ //vmdebug('property_exists userinfo->$fldName '.$fldName,$userinfo); $data[$fldName] = $userinfo->$fldName; } else { vmError('Your tables seem to be broken, you have fields in your form which have no corresponding field in the db'); } } } else { $data[$fld->name] = $userFieldsModel->prepareFieldDataSave($fld, $data); } } return $data; } function getBTuserinfo_id($id = 0){ if(empty($this->_db)) $this->_db = JFactory::getDBO(); if($id == 0){ $id = $this->_id; //vmdebug('getBTuserinfo_id is '.$this->_id); } $q = 'SELECT `virtuemart_userinfo_id` FROM `#__virtuemart_userinfos` WHERE `virtuemart_user_id` = "' .(int)$id .'" AND `address_type`="BT" '; $this->_db->setQuery($q); return $this->_db->loadResult(); } /** * * @author Max Milbers */ function getUserInfoInUserFields($layoutName, $type,$uid,$cart=true,$isVendor=false ){ // if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php' ); // $userFieldsModel = new VirtuemartModelUserfields(); $userFieldsModel = VmModel::getModel('userfields'); $prepareUserFields = $userFieldsModel->getUserFieldsFor( $layoutName, $type, $uid ); if($type=='ST'){ $preFix = 'shipto_'; } else { $preFix = ''; } /* * JUser or $this->_id is the logged user */ if(!empty($this->_data->JUser)){ $JUser = $this->_data->JUser; } else { $JUser = JUser::getInstance($this->_id); } $userFields = array(); if(!empty($uid)){ $data = $this->getTable('userinfos'); $data->load($uid); //vmdebug('$data',$data); if($data->virtuemart_user_id!==0 and !$isVendor){ if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin")) { if($data->virtuemart_user_id!=$this->_id){ vmError('Hacking attempt loading userinfo, you got logged'); echo 'Hacking attempt loading userinfo, you got logged'; return false; } } } if ($data->address_type != 'ST' ) { $BTuid = $uid; $data->name = $JUser->name; $data->email = $JUser->email; $data->username = $JUser->username; $data->address_type = 'BT'; } // vmdebug('getUserInfoInUserFields ',$data); } else { //New Address is filled here with the data of the cart (we are in the userview) if($cart){ if (!class_exists('VirtueMartCart')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); $cart = VirtueMartCart::getCart(); $adType = $type.'address'; if(empty($cart->$adType)){ $data = $cart->$type; if(empty($data)) $data = array(); if($JUser){ if(empty($data['name'])){ $data['name'] = $JUser->name; } if(empty($data['email'])){ $data['email'] = $JUser->email; } if(empty($data['username'])){ $data['username'] = $JUser->username; } if(empty($data['virtuemart_user_id'])){ $data['virtuemart_user_id'] = $JUser->id; } } } $data = (object)$data; } else { if($JUser){ if(empty($data['name'])){ $data['name'] = $JUser->name; } if(empty($data['email'])){ $data['email'] = $JUser->email; } if(empty($data['username'])){ $data['username'] = $JUser->username; } if(empty($data['virtuemart_user_id'])){ $data['virtuemart_user_id'] = $JUser->id; } $data = (object)$data; } else { $data = null; } } } $userFields[$uid] = $userFieldsModel->getUserFieldsFilled( $prepareUserFields ,$data ,$preFix ); return $userFields; } /** * This should store the userdata given in userfields * * @author Max Milbers */ function storeUserDataByFields($data,$type, $toggles, $skips){ if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php' ); $userFieldsModel = VmModel::getModel('userfields'); $prepareUserFields = $userFieldsModel->getUserFields( $type, $toggles, $skips ); // Format the data foreach ($prepareUserFields as $_fld) { if(empty($data[$_fld->name])) $data[$_fld->name] = ''; $data[$_fld->name] = $userFieldsModel->prepareFieldDataSave($_fld,$data); } $this->store($data); return true; } /** * This uses the shopFunctionsF::renderAndSendVmMail function, which uses a controller and task to render the content * and sents it then. * * * @author Oscar van Eijk * @author Max Milbers * @author Christopher Roussel * @author Valérie Isaksen */ private function sendRegistrationEmail($user, $password, $doUserActivation){ if(!class_exists('shopFunctionsF')) require(JPATH_VM_SITE.DS.'helpers'.DS.'shopfunctionsf.php'); $vars = array('user' => $user); // Send registration confirmation mail $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email $vars['password'] = $password; if ($doUserActivation) { jimport('joomla.user.helper'); if(JVM_VERSION === 2) { $com_users = 'com_users'; $activationLink = 'index.php?option='.$com_users.'&task=registration.activate&token='.$user->get('activation'); } else { $com_users = 'com_user'; $activationLink = 'index.php?option='.$com_users.'&task=activate&activation='.$user->get('activation'); } $vars['activationLink'] = $activationLink; } $vars['doVendor']=true; // public function renderMail ($viewName, $recipient, $vars=array(),$controllerName = null) shopFunctionsF::renderMail('user', $user->get('email'), $vars); } /** * Delete all record ids selected * * @return boolean True is the remove was successful, false otherwise. */ function remove($userIds) { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check('admin','storeadmin')) { $userInfo = $this->getTable('userinfos'); $vm_shoppergroup_xref = $this->getTable('vmuser_shoppergroups'); $vmusers = $this->getTable('vmusers'); $_status = true; foreach($userIds as $userId) { $_JUser = JUser::getInstance($userId); if ($this->getSuperAdminCount() <= 1) { // Prevent deletion of the only Super Admin //$_u = JUser::getInstance($userId); if ($_JUser->get('gid') == __SUPER_ADMIN_GID) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_LASTSUPERADMIN')); $_status = false; continue; } } if(Permissions::getInstance()->check('storeadmin')) { if ($_JUser->get('gid') == __SUPER_ADMIN_GID) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_LASTSUPERADMIN')); $_status = false; continue; } } if (!$userInfo->delete($userId)) { vmError($userInfo->getError()); return false; } if (!$vm_shoppergroup_xref->delete($userId)) { vmError($vm_shoppergroup_xref->getError()); // Signal but continue $_status = false; continue; } if (!$vmusers->delete($userId)) { vmError($vmusers->getError()); // Signal but continue $_status = false; continue; } if (!$_JUser->delete()) { vmError($_JUser->getError()); $_status = false; continue; } } } return $_status; } function removeAddress($virtuemart_userinfo_id){ $db = JFactory::getDBO(); if ( isset($virtuemart_userinfo_id) and $this->_id != 0 ) { //$userModel -> deleteAddressST(); $q = 'DELETE FROM #__virtuemart_userinfos WHERE virtuemart_user_id="'. $this->_id .'" AND virtuemart_userinfo_id="'. (int)$virtuemart_userinfo_id .'"'; $db->setQuery($q); if($db->query()){ vmInfo('Address has been successfully deleted.'); return true; } } return false; } /** * Retrieve a list of users from the database. * * @author Max Milbers * @return object List of user objects */ function getUserList() { //$select = ' * '; //$joinedTables = ' FROM #__users AS ju LEFT JOIN #__virtuemart_vmusers AS vmu ON ju.id = vmu.virtuemart_user_id'; $search = JRequest::getString('search', false); $tableToUse = JRequest::getString('searchTable','juser'); $where = ''; if ($search) { $where = ' WHERE '; $searchArray = array('ju.name','username','email','perms','usertype','shopper_group_name'); if($tableToUse!='juser'){ if(!class_exists('TableUserinfos'))require(JPATH_VM_ADMINISTRATOR.DS.'tables'.DS.'userinfos.php'); $db = JFactory::getDbo(); $userfieldTable = new TableUserinfos($db); $userfieldFields = get_object_vars($userfieldTable); $userFieldSearchArray = array('company','first_name','last_name'); //We must validate if the userfields actually exists, they could be removed $userFieldsValid = array(); foreach($userFieldSearchArray as $ufield){ if(array_key_exists($ufield,$userfieldFields)){ $userFieldsValid[] = $ufield; } } $searchArray = array_merge($userFieldsValid,$searchArray); } $search = str_replace(' ','%',$this->_db->getEscaped( $search, true )); foreach($searchArray as $field){ $where.= ' '.$field.' LIKE "%'.$search.'%" OR '; } $where = substr($where,0,-3); } $select = ' ju.id AS id , ju.name AS name , ju.username AS username , ju.email AS email , IFNULL(vmu.user_is_vendor,"0") AS is_vendor , IFNULL(sg.shopper_group_name, "") AS shopper_group_name '; if ($search) { if($tableToUse!='juser'){ $select .= ' , ui.name as uiname '; } foreach($searchArray as $ufield){ $select .= ' , '.$ufield; } } $joinedTables = ' FROM #__users AS ju LEFT JOIN #__virtuemart_vmusers AS vmu ON ju.id = vmu.virtuemart_user_id LEFT JOIN #__virtuemart_vmuser_shoppergroups AS vx ON ju.id = vx.virtuemart_user_id LEFT JOIN #__virtuemart_shoppergroups AS sg ON vx.virtuemart_shoppergroup_id = sg.virtuemart_shoppergroup_id '; if ($search and $tableToUse!='juser') { $joinedTables .= ' LEFT JOIN #__virtuemart_userinfos AS ui ON ui.virtuemart_user_id = vmu.virtuemart_user_id'; } return $this->_data = $this->exeSortSearchListQuery(0,$select,$joinedTables,$where,' GROUP BY ju.id',$this->_getOrdering()); } /** * If a filter was set, get the SQL WHERE clase * * @return string text to add to the SQL statement */ function _getFilter() { if ($search = JRequest::getString('search', false)) { $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; //$search = $this->_db->Quote($search, false); $searchArray = array('name','username','email','perms','usertype','shopper_group_name'); $where = ' WHERE '; foreach($searchArray as $field){ $where.= ' `'.$field.'` LIKE '.$search.' OR '; } $where = substr($where,0,-3); //$where = ' WHERE `name` LIKE '.$search.' OR `username` LIKE ' .$search.' OR `email` LIKE ' .$search.' OR `perms` LIKE ' .$search.' OR `usertype` LIKE ' .$search.' OR `shopper_group_name` LIKE ' .$search; return ($where); } return (''); } /** * Retrieve a single address for a user * * @param $_uid int User ID * @param $_virtuemart_userinfo_id string Optional User Info ID * @param $_type string, addess- type, ST (ShipTo, default) or BT (BillTo). Empty string to ignore */ function getUserAddressList($_uid = 0, $_type = 'ST',$_virtuemart_userinfo_id = -1){ //Todo, add perms, allow admin to see 0 entries. if($_uid==0 and $this->_id==0){ return array(); } $_q = 'SELECT * FROM #__virtuemart_userinfos WHERE virtuemart_user_id="' . (($_uid==0)?$this->_id:(int)$_uid) .'"'; if ($_virtuemart_userinfo_id !== -1) { $_q .= ' AND virtuemart_userinfo_id="'.(int)$_virtuemart_userinfo_id.'"'; } else { if ($_type !== '') { $_q .= ' AND address_type="'.$_type.'"'; } } // vmdebug('getUserAddressList query '.$_q); return ($this->_getList($_q)); } /** * Retrieves the Customer Number of the user specified by ID * * @param int $_id User ID * @return string Customer Number */ private $customer_number = 0; public function getCustomerNumberById() { if($this->customer_number===0){ $_q = "SELECT `customer_number` FROM `#__virtuemart_vmusers` " ."WHERE `virtuemart_user_id`='" . $this->_id . "' "; $_r = $this->_getList($_q); if(!empty($_r[0])){ $this->customer_number = $_r[0]->customer_number; }else { $this->customer_number = false; } } return $this->customer_number; } /** * Get the number of active Super Admins * * @return integer */ function getSuperAdminCount() { $this->_db->setQuery('SELECT COUNT(id) FROM #__users' . ' WHERE usertype = ' . __SUPER_ADMIN_GID . ' AND block = 0'); return ($this->_db->loadResult()); } /** * Return a list of Joomla ACL groups. * * The returned object list includes a group anme and a group name with spaces * prepended to the name for displaying an indented tree. * * @author RickG * @return ObjectList List of acl group objects. */ function getAclGroupIndentedTree() { //TODO check this out if (JVM_VERSION===1) { $name = 'name'; $as = '` AS `title`'; $table = '#__core_acl_aro_groups'; $and = 'AND `parent`.`lft` > 2 '; } else { $name = 'title'; $as = '`'; $table = '#__usergroups'; $and = ''; } //Ugly thing, produces Select_full_join $query = 'SELECT `node`.`' . $name . $as . ', CONCAT(REPEAT(" ", (COUNT(`parent`.`' . $name . '`) - 1)), `node`.`' . $name . '`) AS `text` '; $query .= 'FROM `' . $table . '` AS node, `' . $table . '` AS parent '; $query .= 'WHERE `node`.`lft` BETWEEN `parent`.`lft` AND `parent`.`rgt` '; $query .= $and; $query .= 'GROUP BY `node`.`' . $name . '` '; $query .= ' ORDER BY `node`.`lft`'; $this->_db->setQuery($query); //$app = JFactory::getApplication(); //$app -> enqueueMessage($this->_db->getQuery()); $objlist = $this->_db->loadObjectList(); // vmdebug('getAclGroupIndentedTree',$objlist); return $objlist; } } //No Closing tag home/academiac/www/administrator/components/com_virtuemart/controllers/user.php 0000604 00000011126 15137243267 0024360 0 ustar 00 <?php /** * * User controller * * @package VirtueMart * @subpackage User * @author Oscar van Eijk * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to 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. * @version $Id: user.php 6071 2012-06-06 15:33:04Z Milbo $ */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); // Load the controller framework jimport('joomla.application.component.controller'); if(!class_exists('VmController'))require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmcontroller.php'); /** * Controller class for the user * * @package VirtueMart * @subpackage User * @author Oscar van Eijk * @author Max Milbers */ class VirtuemartControllerUser extends VmController { /** * Method to display the view * * @access public * @author */ function __construct(){ VmConfig::loadJLang('com_virtuemart_shoppers',TRUE); parent::__construct('virtuemart_user_id'); } /** * Handle the edit task */ function edit($view=0){ //We set here the virtuemart_user_id, when no virtuemart_user_id is set to 0, for adding a new user //In every other case the virtuemart_user_id is sent. $cid = JRequest::getVar('virtuemart_user_id'); if(!isset($cid)) JRequest::setVar('virtuemart_user_id', (int)0); parent::edit('edit'); } function addST(){ $this->edit(); } function editshop(){ $user = JFactory::getUser(); //the virtuemart_user_id var gets overriden in the edit function, when not set. So we must set it here JRequest::setVar('virtuemart_user_id', (int)$user->id); $this->edit(); } function cancel(){ $lastTask = JRequest::getWord('last_task'); if ($lastTask == 'edit_shop') $this->setRedirect('index.php?option=com_virtuemart'); else $this->setRedirect('index.php?option=com_virtuemart&view=user'); } /** * Handle the save task * Checks already in the controller the rights todo so and sets the data by filtering the post * * @author Max Milbers */ function save($data = 0){ $document = JFactory::getDocument(); $viewType = $document->getType(); $view = $this->getView('user', $viewType); $_currentUser = JFactory::getUser(); // TODO sortout which check is correctt..... // if (!$_currentUser->authorize('administration', 'manage', 'components', 'com_users')) { if (!$_currentUser->authorize('core.edit', 'com_users')) { $msg = JText::_(_NOT_AUTH); } else { $model = VmModel::getModel('user'); $data = JRequest::get('post'); // Store multiple selectlist entries as a ; separated string if (array_key_exists('vendor_accepted_currencies', $data) && is_array($data['vendor_accepted_currencies'])) { $data['vendor_accepted_currencies'] = implode(',', $data['vendor_accepted_currencies']); } // TODO disallow vendor_store_name as HTML ? $data['vendor_store_name'] = JRequest::getVar('vendor_store_name','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_store_desc'] = JRequest::getVar('vendor_store_desc','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_terms_of_service'] = JRequest::getVar('vendor_terms_of_service','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_legal_info'] = JRequest::getVar('vendor_legal_info','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_letter_css'] = JRequest::getVar('vendor_letter_css','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_letter_header_html'] = JRequest::getVar('vendor_letter_header_html','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_letter_footer_html'] = JRequest::getVar('vendor_letter_footer_html','','post','STRING',JREQUEST_ALLOWHTML); $ret=$model->store($data); if(!$ret){ $msg = ''; } else { $msg = $ret['message']; } } $cmd = JRequest::getCmd('task'); $lastTask = JRequest::getWord('last_task'); if($cmd == 'apply'){ if ($lastTask == 'editshop') $redirection = 'index.php?option=com_virtuemart&view=user&task=editshop'; else $redirection = 'index.php?option=com_virtuemart&view=user&task=edit&virtuemart_user_id[]='.$ret['newId']; } else { if ($lastTask == 'editshop') $redirection = 'index.php?option=com_virtuemart'; else $redirection = 'index.php?option=com_virtuemart&view=user'; } // $this->setRedirect($redirection, $ret['message']); $this->setRedirect($redirection); } } //No Closing tag home/academiac/www/libraries/joomla/user/user.php 0000644 00000050246 15137257157 0016135 0 ustar 00 <?php /** * @package Joomla.Platform * @subpackage User * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * User class. Handles all application interaction with a user * * @package Joomla.Platform * @subpackage User * @since 11.1 */ class JUser extends JObject { /** * A cached switch for if this user has root access rights. * * @var boolean * @since 11.1 */ protected $isRoot = null; /** * Unique id * * @var integer * @since 11.1 */ public $id = null; /** * The users real name (or nickname) * @var string * @since 11.1 */ public $name = null; /** * The login name * * @var string * @since 11.1 */ public $username = null; /** * The email * * @var string * @since 11.1 */ public $email = null; /** * MD5 encrypted password * * @var string * @since 11.1 */ public $password = null; /** * Clear password, only available when a new password is set for a user * * @var string * @since 11.1 */ public $password_clear = ''; /** * User type * Used in Joomla 1.0 and 1.5 for access control. * * @var string * @deprecated 12.1 * @see $_authGroups * @see JAccess * @since 11.1 */ public $usertype = null; /** * Block status * * @var integer * @since 11.1 */ public $block = null; /** * Should this user receive system email * * @var integer * @since 11.1 */ public $sendEmail = null; /** * Date the user was registered * * @var datetime * @since 11.1 */ public $registerDate = null; /** * Date of last visit * * @var datetime * @since 11.1 */ public $lastvisitDate = null; /** * Activation hash * * @var string * @since 11.1 */ public $activation = null; /** * User parameters * * @var string * @since 11.1 */ public $params = null; /** * Array of ids of groups that user belongs to * * @var array * @since 11.1 */ public $groups = array(); /** * Guest status * * @var boolean * @since 11.1 */ public $guest = null; /** * Last Reset Time * * @var string * @since Joomla 2.5.6 */ public $lastResetTime = null; /** * Count since last Reset Time * * @var int * @since Joomla 2.5.6 */ public $resetCount = null; /** * User parameters * @var object * @since 11.1 */ protected $_params = null; /** * Authorised access groups * * @var array * @since 11.1 */ protected $_authGroups = null; /** * Authorised access levels * * @var array * @since 11.1 */ protected $_authLevels = null; /** * Authorised access actions * * @var array * @since 11.1 */ protected $_authActions = null; /** * Error message * * @var string * @since 11.1 */ protected $_errorMsg = null; /** * @var array JUser instances container. * @since 11.3 */ protected static $instances = array(); /** * Constructor activating the default information of the language * * @param integer $identifier The primary key of the user to load (optional). * * @since 11.1 */ public function __construct($identifier = 0) { // Create the user parameters object $this->_params = new JRegistry; // Load the user if it exists if (!empty($identifier)) { $this->load($identifier); } else { //initialise $this->id = 0; $this->sendEmail = 0; $this->aid = 0; $this->guest = 1; } } /** * Returns the global User object, only creating it if it * doesn't already exist. * * @param integer $identifier The user to load - Can be an integer or string - If string, it is converted to ID automatically. * * @return JUser The User object. * * @since 11.1 */ public static function getInstance($identifier = 0) { // Find the user id if (!is_numeric($identifier)) { if (!$id = JUserHelper::getUserId($identifier)) { JError::raiseWarning('SOME_ERROR_CODE', JText::sprintf('JLIB_USER_ERROR_ID_NOT_EXISTS', $identifier)); $retval = false; return $retval; } } else { $id = $identifier; } // If the $id is zero, just return an empty JUser. // Note: don't cache this user because it'll have a new ID on save! if ($id === 0) { return new JUser; } if (empty(self::$instances[$id])) { $user = new JUser($id); self::$instances[$id] = $user; } return self::$instances[$id]; } /** * Method to get a parameter value * * @param string $key Parameter key * @param mixed $default Parameter default value * * @return mixed The value or the default if it did not exist * * @since 11.1 */ public function getParam($key, $default = null) { return $this->_params->get($key, $default); } /** * Method to set a parameter * * @param string $key Parameter key * @param mixed $value Parameter value * * @return mixed Set parameter value * * @since 11.1 */ public function setParam($key, $value) { return $this->_params->set($key, $value); } /** * Method to set a default parameter if it does not exist * * @param string $key Parameter key * @param mixed $value Parameter value * * @return mixed Set parameter value * * @since 11.1 */ public function defParam($key, $value) { return $this->_params->def($key, $value); } /** * Proxy to authorise * * @param string $action The name of the action to check for permission. * @param string $assetname The name of the asset on which to perform the action. * * @return boolean True if authorised * * @deprecated 12.1 * @note Use the authorise method instead. * @since 11.1 */ public function authorize($action, $assetname = null) { // Deprecation warning. JLog::add('JUser::authorize() is deprecated.', JLog::WARNING, 'deprecated'); return $this->authorise($action, $assetname); } /** * Method to check JUser object authorisation against an access control * object and optionally an access extension object * * @param string $action The name of the action to check for permission. * @param string $assetname The name of the asset on which to perform the action. * * @return boolean True if authorised * * @since 11.1 */ public function authorise($action, $assetname = null) { // Make sure we only check for core.admin once during the run. if ($this->isRoot === null) { $this->isRoot = false; // Check for the configuration file failsafe. $config = JFactory::getConfig(); $rootUser = $config->get('root_user'); // The root_user variable can be a numeric user ID or a username. if (is_numeric($rootUser) && $this->id > 0 && $this->id == $rootUser) { $this->isRoot = true; } elseif ($this->username && $this->username == $rootUser) { $this->isRoot = true; } else { // Get all groups against which the user is mapped. $identities = $this->getAuthorisedGroups(); array_unshift($identities, $this->id * -1); if (JAccess::getAssetRules(1)->allow('core.admin', $identities)) { $this->isRoot = true; return true; } } } return $this->isRoot ? true : JAccess::check($this->id, $action, $assetname); } /** * Gets an array of the authorised access levels for the user * * @return array * * @deprecated 12.1 * @note Use the getAuthorisedViewLevels method instead. * @since 11.1 */ public function authorisedLevels() { // Deprecation warning. JLog::add('JUser::authorisedLevels() is deprecated.', JLog::WARNING, 'deprecated'); return $this->getAuthorisedViewLevels(); } /** * Method to return a list of all categories that a user has permission for a given action * * @param string $component The component from which to retrieve the categories * @param string $action The name of the section within the component from which to retrieve the actions. * * @return array List of categories that this group can do this action to (empty array if none). Categories must be published. * * @since 11.1 */ public function getAuthorisedCategories($component, $action) { // Brute force method: get all published category rows for the component and check each one // TODO: Modify the way permissions are stored in the db to allow for faster implementation and better scaling $db = JFactory::getDbo(); $query = $db->getQuery(true)->select('c.id AS id, a.name AS asset_name')->from('#__categories AS c') ->innerJoin('#__assets AS a ON c.asset_id = a.id')->where('c.extension = ' . $db->quote($component))->where('c.published = 1'); $db->setQuery($query); $allCategories = $db->loadObjectList('id'); $allowedCategories = array(); foreach ($allCategories as $category) { if ($this->authorise($action, $category->asset_name)) { $allowedCategories[] = (int) $category->id; } } return $allowedCategories; } /** * Gets an array of the authorised access levels for the user * * @return array * * @since 11.1 */ public function getAuthorisedViewLevels() { if ($this->_authLevels === null) { $this->_authLevels = array(); } if (empty($this->_authLevels)) { $this->_authLevels = JAccess::getAuthorisedViewLevels($this->id); } return $this->_authLevels; } /** * Gets an array of the authorised user groups * * @return array * * @since 11.1 */ public function getAuthorisedGroups() { if ($this->_authGroups === null) { $this->_authGroups = array(); } if (empty($this->_authGroups)) { $this->_authGroups = JAccess::getGroupsByUser($this->id); } return $this->_authGroups; } /** * Pass through method to the table for setting the last visit date * * @param integer $timestamp The timestamp, defaults to 'now'. * * @return boolean True on success. * * @since 11.1 */ public function setLastVisit($timestamp = null) { // Create the user table object $table = $this->getTable(); $table->load($this->id); return $table->setLastVisit($timestamp); } /** * Method to get the user parameters * * This function tries to load an XML file based on the user's usertype. The filename of the xml * file is the same as the usertype. The functionals has a static variable to store the parameters * setup file base path. You can call this function statically to set the base path if needed. * * @param boolean $loadsetupfile If true, loads the parameters setup file. Default is false. * @param path $path Set the parameters setup file base path to be used to load the user parameters. * * @return object The user parameters object. * * @since 11.1 */ public function getParameters($loadsetupfile = false, $path = null) { static $parampath; // Set a custom parampath if defined if (isset($path)) { $parampath = $path; } // Set the default parampath if not set already if (!isset($parampath)) { $parampath = JPATH_ADMINISTRATOR . 'components/com_users/models'; } if ($loadsetupfile) { $type = str_replace(' ', '_', strtolower($this->usertype)); $file = $parampath . '/' . $type . '.xml'; if (!file_exists($file)) { $file = $parampath . '/' . 'user.xml'; } $this->_params->loadSetupFile($file); } return $this->_params; } /** * Method to get the user parameters * * @param object $params The user parameters object * * @return void * * @since 11.1 */ public function setParameters($params) { $this->_params = $params; } /** * Method to get the user table object * * This function uses a static variable to store the table name of the user table to * instantiate. You can call this function statically to set the table name if * needed. * * @param string $type The user table name to be used * @param string $prefix The user table prefix to be used * * @return object The user table object * * @since 11.1 */ public static function getTable($type = null, $prefix = 'JTable') { static $tabletype; // Set the default tabletype; if (!isset($tabletype)) { $tabletype['name'] = 'user'; $tabletype['prefix'] = 'JTable'; } // Set a custom table type is defined if (isset($type)) { $tabletype['name'] = $type; $tabletype['prefix'] = $prefix; } // Create the user table object return JTable::getInstance($tabletype['name'], $tabletype['prefix']); } /** * Method to bind an associative array of data to a user object * * @param array &$array The associative array to bind to the object * * @return boolean True on success * * @since 11.1 */ public function bind(&$array) { // Let's check to see if the user is new or not if (empty($this->id)) { // Check the password and create the crypted password if (empty($array['password'])) { $array['password'] = JUserHelper::genRandomPassword(); $array['password2'] = $array['password']; } // TODO: Backend controller checks the password, frontend doesn't but should. // Hence this code is required: if (isset($array['password2']) && $array['password'] != $array['password2']) { $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH')); return false; } $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string'); $array['password'] = JUserHelper::hashPassword($array['password']); // Set the registration timestamp $this->set('registerDate', JFactory::getDate()->toSql()); // Check that username is not greater than 150 characters $username = $this->get('username'); if (strlen($username) > 150) { $username = substr($username, 0, 150); $this->set('username', $username); } // Check that password is not greater than 100 characters $password = $this->get('password'); if (strlen($password) > 100) { $password = substr($password, 0, 100); $this->set('password', $password); } } else { // Updating an existing user if (!empty($array['password'])) { if ($array['password'] != $array['password2']) { $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH')); return false; } $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string'); $array['password'] = JUserHelper::hashPassword($array['password']); } else { $array['password'] = $this->password; } } // TODO: this will be deprecated as of the ACL implementation // $db = JFactory::getDbo(); if (array_key_exists('params', $array)) { $params = ''; $this->_params->loadArray($array['params']); if (is_array($array['params'])) { $params = (string) $this->_params; } else { $params = $array['params']; } $this->params = $params; } // Bind the array if (!$this->setProperties($array)) { $this->setError(JText::_('JLIB_USER_ERROR_BIND_ARRAY')); return false; } // Make sure its an integer $this->id = (int) $this->id; return true; } /** * Method to save the JUser object to the database * * @param boolean $updateOnly Save the object only if not a new user * Currently only used in the user reset password method. * * @return boolean True on success * * @since 11.1 * @throws exception */ public function save($updateOnly = false) { // Create the user table object $table = $this->getTable(); $this->params = (string) $this->_params; $table->bind($this->getProperties()); // Allow an exception to be thrown. try { // Check and store the object. if (!$table->check()) { $this->setError($table->getError()); return false; } // If user is made a Super Admin group and user is NOT a Super Admin // // @todo ACL - this needs to be acl checked // $my = JFactory::getUser(); //are we creating a new user $isNew = empty($this->id); // If we aren't allowed to create new users return if ($isNew && $updateOnly) { return true; } // Get the old user $oldUser = new JUser($this->id); // // Access Checks // // The only mandatory check is that only Super Admins can operate on other Super Admin accounts. // To add additional business rules, use a user plugin and throw an Exception with onUserBeforeSave. // Check if I am a Super Admin $iAmSuperAdmin = $my->authorise('core.admin'); $iAmRehashingSuperadmin = false; if (($my->id == 0 && !$isNew) && $this->id == $oldUser->id && $oldUser->authorise('core.admin') && $oldUser->password != $this->password) { $iAmRehashingSuperadmin = true; } // We are only worried about edits to this account if I am not a Super Admin. if ($iAmSuperAdmin != true && $iAmRehashingSuperadmin != true) { if ($isNew) { // Check if the new user is being put into a Super Admin group. foreach ($this->groups as $groupId) { if (JAccess::checkGroup($groupId, 'core.admin')) { throw new Exception(JText::_('JLIB_USER_ERROR_NOT_SUPERADMIN')); } } } else { // I am not a Super Admin, and this one is, so fail. if (JAccess::check($this->id, 'core.admin')) { throw new Exception(JText::_('JLIB_USER_ERROR_NOT_SUPERADMIN')); } if ($this->groups != null) { // I am not a Super Admin and I'm trying to make one. foreach ($this->groups as $groupId) { if (JAccess::checkGroup($groupId, 'core.admin')) { throw new Exception(JText::_('JLIB_USER_ERROR_NOT_SUPERADMIN')); } } } } } // Fire the onUserBeforeSave event. JPluginHelper::importPlugin('user'); $dispatcher = JDispatcher::getInstance(); $result = $dispatcher->trigger('onUserBeforeSave', array($oldUser->getProperties(), $isNew, $this->getProperties())); if (in_array(false, $result, true)) { // Plugin will have to raise its own error or throw an exception. return false; } // Store the user data in the database if (!($result = $table->store())) { throw new Exception($table->getError()); } // Set the id for the JUser object in case we created a new user. if (empty($this->id)) { $this->id = $table->get('id'); } if ($my->id == $table->id) { $registry = new JRegistry; $registry->loadString($table->params); $my->setParameters($registry); } // Fire the onUserAfterSave event $dispatcher->trigger('onUserAfterSave', array($this->getProperties(), $isNew, $result, $this->getError())); } catch (Exception $e) { $this->setError($e->getMessage()); return false; } return $result; } /** * Method to delete the JUser object from the database * * @return boolean True on success * * @since 11.1 */ public function delete() { JPluginHelper::importPlugin('user'); // Trigger the onUserBeforeDelete event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onUserBeforeDelete', array($this->getProperties())); // Create the user table object $table = $this->getTable(); $result = false; if (!$result = $table->delete($this->id)) { $this->setError($table->getError()); } // Trigger the onUserAfterDelete event $dispatcher->trigger('onUserAfterDelete', array($this->getProperties(), $result, $this->getError())); return $result; } /** * Method to load a JUser object by user id number * * @param mixed $id The user id of the user to load * * @return boolean True on success * * @since 11.1 */ public function load($id) { // Create the user table object $table = $this->getTable(); // Load the JUserModel object based on the user id or throw a warning. if (!$table->load($id)) { JError::raiseWarning('SOME_ERROR_CODE', JText::sprintf('JLIB_USER_ERROR_UNABLE_TO_LOAD_USER', $id)); return false; } // Set the user parameters using the default XML file. We might want to // extend this in the future to allow for the ability to have custom // user parameters, but for right now we'll leave it how it is. $this->_params->loadString($table->params); // Assuming all is well at this point lets bind the data $this->setProperties($table->getProperties()); return true; } } home/academiac/www/libraries/joomla/html/html/user.php 0000644 00000004607 15137262040 0017052 0 ustar 00 <?php /** * @package Joomla.Platform * @subpackage HTML * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Utility class working with users * * @package Joomla.Platform * @subpackage HTML * @since 11.4 */ abstract class JHtmlUser { /** * Displays a list of user groups. * * @param boolean true to include super admin groups, false to exclude them * * @return array An array containing a list of user groups. * * @since 11.4 */ public static function groups($includeSuperAdmin = false) { $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text, COUNT(DISTINCT b.id) AS level'); $query->from($db->quoteName('#__usergroups') . ' AS a'); $query->join('LEFT', $db->quoteName('#__usergroups') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); $query->group('a.id, a.title, a.lft, a.rgt'); $query->order('a.lft ASC'); $db->setQuery($query); $options = $db->loadObjectList(); // Check for a database error. if ($db->getErrorNum()) { JError::raiseNotice(500, $db->getErrorMsg()); return null; } for ($i = 0, $n = count($options); $i < $n; $i++) { $options[$i]->text = str_repeat('- ', $options[$i]->level) . $options[$i]->text; $groups[] = JHtml::_('select.option', $options[$i]->value, $options[$i]->text); } // Exclude super admin groups if requested if (!$includeSuperAdmin) { $filteredGroups = array(); foreach ($groups as $group) { if (!JAccess::checkGroup($group->value, 'core.admin')) { $filteredGroups[] = $group; } } $groups = $filteredGroups; } return $groups; } /** * Get a list of users. * * @return string * * @since 11.4 */ public static function userlist() { // Get the database object and a new query object. $db = JFactory::getDBO(); $query = $db->getQuery(true); // Build the query. $query->select('a.id AS value, a.name AS text'); $query->from('#__users AS a'); $query->where('a.block = 0'); $query->order('a.name'); // Set the query and load the options. $db->setQuery($query); $items = $db->loadObjectList(); // Detect errors if ($db->getErrorNum()) { JError::raiseWarning(500, $db->getErrorMsg()); } return $items; } } home/academiac/www/libraries/joomla/database/table/user.php 0000644 00000031111 15137272073 0017772 0 ustar 00 <?php /** * @package Joomla.Platform * @subpackage Database * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; jimport('joomla.database.table'); /** * Users table * * @package Joomla.Platform * @subpackage Table * @since 11.1 */ class JTableUser extends JTable { /** * Associative array of user names => group ids * * @var array * @since 11.1 */ public $groups; /** * Constructor * * @param JDatabase &$db A database connector object. * * @since 11.1 */ public function __construct(&$db) { parent::__construct('#__users', 'id', $db); // Initialise. $this->id = 0; $this->sendEmail = 0; } /** * Method to load a user, user groups, and any other necessary data * from the database so that it can be bound to the user object. * * @param integer $userId An optional user id. * @param boolean $reset False if row not found or on error * (internal error state set in that case). * * @return boolean True on success, false on failure. * * @since 11.1 */ public function load($userId = null, $reset = true) { // Get the id to load. if ($userId !== null) { $this->id = $userId; } else { $userId = $this->id; } // Check for a valid id to load. if ($userId === null) { return false; } // Reset the table. $this->reset(); // Load the user data. $query = $this->_db->getQuery(true); $query->select('*'); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('id') . ' = ' . (int) $userId); $this->_db->setQuery($query); $data = (array) $this->_db->loadAssoc(); // Check for an error message. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } if (!count($data)) { return false; } // Bind the data to the table. $return = $this->bind($data); if ($return !== false) { // Load the user groups. $query->clear(); $query->select($this->_db->quoteName('g') . '.' . $this->_db->quoteName('id')); $query->select($this->_db->quoteName('g') . '.' . $this->_db->quoteName('title')); $query->from($this->_db->quoteName('#__usergroups') . ' AS g'); $query->join('INNER', $this->_db->quoteName('#__user_usergroup_map') . ' AS m ON m.group_id = g.id'); $query->where($this->_db->quoteName('m.user_id') . ' = ' . (int) $userId); $this->_db->setQuery($query); // Add the groups to the user data. $this->groups = $this->_db->loadAssocList('id', 'id'); // Check for an error message. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } } return $return; } /** * Method to bind the user, user groups, and any other necessary data. * * @param array $array The data to bind. * @param mixed $ignore An array or space separated list of fields to ignore. * * @return boolean True on success, false on failure. * * @since 11.1 */ public function bind($array, $ignore = '') { if (key_exists('params', $array) && is_array($array['params'])) { $registry = new JRegistry; $registry->loadArray($array['params']); $array['params'] = (string) $registry; } // Attempt to bind the data. $return = parent::bind($array, $ignore); // Load the real group data based on the bound ids. if ($return && !empty($this->groups)) { // Set the group ids. JArrayHelper::toInteger($this->groups); // Get the titles for the user groups. $query = $this->_db->getQuery(true); $query->select($this->_db->quoteName('id')); $query->select($this->_db->quoteName('title')); $query->from($this->_db->quoteName('#__usergroups')); $query->where($this->_db->quoteName('id') . ' = ' . implode(' OR ' . $this->_db->quoteName('id') . ' = ', $this->groups)); $this->_db->setQuery($query); // Set the titles for the user groups. $this->groups = $this->_db->loadAssocList('id', 'id'); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } } return $return; } /** * Validation and filtering * * @return boolean True if satisfactory * * @since 11.1 */ public function check() { // Validate user information if (trim($this->name) == '') { $this->setError(JText::_('JLIB_DATABASE_ERROR_PLEASE_ENTER_YOUR_NAME')); return false; } if (trim($this->username) == '') { $this->setError(JText::_('JLIB_DATABASE_ERROR_PLEASE_ENTER_A_USER_NAME')); return false; } if (preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $this->username) || strlen(utf8_decode($this->username)) < 2 || trim($this->username) != $this->username) { $this->setError(JText::sprintf('JLIB_DATABASE_ERROR_VALID_AZ09', 2)); return false; } if ((trim($this->email) == "") || !JMailHelper::isEmailAddress($this->email)) { $this->setError(JText::_('JLIB_DATABASE_ERROR_VALID_MAIL')); return false; } // Set the registration timestamp if ($this->registerDate == null || $this->registerDate == $this->_db->getNullDate()) { $this->registerDate = JFactory::getDate()->toSql(); } // check for existing username $query = $this->_db->getQuery(true); $query->select($this->_db->quoteName('id')); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('username') . ' = ' . $this->_db->quote($this->username)); $query->where($this->_db->quoteName('id') . ' != ' . (int) $this->id); $this->_db->setQuery($query); $xid = intval($this->_db->loadResult()); if ($xid && $xid != intval($this->id)) { $this->setError(JText::_('JLIB_DATABASE_ERROR_USERNAME_INUSE')); return false; } // check for existing email $query->clear(); $query->select($this->_db->quoteName('id')); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('email') . ' = ' . $this->_db->quote($this->email)); $query->where($this->_db->quoteName('id') . ' != ' . (int) $this->id); $this->_db->setQuery($query); $xid = intval($this->_db->loadResult()); if ($xid && $xid != intval($this->id)) { $this->setError(JText::_('JLIB_DATABASE_ERROR_EMAIL_INUSE')); return false; } // check for root_user != username $config = JFactory::getConfig(); $rootUser = $config->get('root_user'); if (!is_numeric($rootUser)) { $query->clear(); $query->select($this->_db->quoteName('id')); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('username') . ' = ' . $this->_db->quote($rootUser)); $this->_db->setQuery($query); $xid = intval($this->_db->loadResult()); if ($rootUser == $this->username && (!$xid || $xid && $xid != intval($this->id)) || $xid && $xid == intval($this->id) && $rootUser != $this->username) { $this->setError(JText::_('JLIB_DATABASE_ERROR_USERNAME_CANNOT_CHANGE')); return false; } } return true; } /** * Method to store a row in the database from the JTable instance properties. * If a primary key value is set the row with that primary key value will be * updated with the instance property values. If no primary key value is set * a new row will be inserted into the database with the properties from the * JTable instance. * * @param boolean $updateNulls True to update fields even if they are null. * * @return boolean True on success. * * @link http://docs.joomla.org/JTable/store * @since 11.1 */ public function store($updateNulls = false) { // Get the table key and key value. $k = $this->_tbl_key; $key = $this->$k; // TODO: This is a dumb way to handle the groups. // Store groups locally so as to not update directly. $groups = $this->groups; unset($this->groups); // Insert or update the object based on presence of a key value. if ($key) { // Already have a table key, update the row. $return = $this->_db->updateObject($this->_tbl, $this, $this->_tbl_key, $updateNulls); } else { // Don't have a table key, insert the row. $return = $this->_db->insertObject($this->_tbl, $this, $this->_tbl_key); } // Handle error if it exists. if (!$return) { $this->setError(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED', strtolower(get_class($this)), $this->_db->getErrorMsg())); return false; } // Reset groups to the local object. $this->groups = $groups; unset($groups); // Store the group data if the user data was saved. if ($return && is_array($this->groups) && count($this->groups)) { // Delete the old user group maps. $query = $this->_db->getQuery(true); $query->delete(); $query->from($this->_db->quoteName('#__user_usergroup_map')); $query->where($this->_db->quoteName('user_id') . ' = ' . (int) $this->id); $this->_db->setQuery($query); $this->_db->execute(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } // Set the new user group maps. $query->clear(); $query->insert($this->_db->quoteName('#__user_usergroup_map')); $query->columns(array($this->_db->quoteName('user_id'), $this->_db->quoteName('group_id'))); $query->values($this->id . ', ' . implode('), (' . $this->id . ', ', $this->groups)); $this->_db->setQuery($query); $this->_db->execute(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } } return true; } /** * Method to delete a user, user groups, and any other necessary data from the database. * * @param integer $userId An optional user id. * * @return boolean True on success, false on failure. * * @since 11.1 */ public function delete($userId = null) { // Set the primary key to delete. $k = $this->_tbl_key; if ($userId) { $this->$k = intval($userId); } // Delete the user. $query = $this->_db->getQuery(true); $query->delete(); $query->from($this->_db->quoteName($this->_tbl)); $query->where($this->_db->quoteName($this->_tbl_key) . ' = ' . (int) $this->$k); $this->_db->setQuery($query); $this->_db->execute(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } // Delete the user group maps. $query->clear(); $query->delete(); $query->from($this->_db->quoteName('#__user_usergroup_map')); $query->where($this->_db->quoteName('user_id') . ' = ' . (int) $this->$k); $this->_db->setQuery($query); $this->_db->execute(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } /* * Clean Up Related Data. */ $query->clear(); $query->delete(); $query->from($this->_db->quoteName('#__messages_cfg')); $query->where($this->_db->quoteName('user_id') . ' = ' . (int) $this->$k); $this->_db->setQuery($query); $this->_db->execute(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } $query->clear(); $query->delete(); $query->from($this->_db->quoteName('#__messages')); $query->where($this->_db->quoteName('user_id_to') . ' = ' . (int) $this->$k); $this->_db->setQuery($query); $this->_db->execute(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } return true; } /** * Updates last visit time of user * * @param integer $timeStamp The timestamp, defaults to 'now'. * @param integer $userId The user id (optional). * * @return boolean False if an error occurs * * @since 11.1 */ public function setLastVisit($timeStamp = null, $userId = null) { // Check for User ID if (is_null($userId)) { if (isset($this)) { $userId = $this->id; } else { // do not translate jexit(JText::_('JLIB_DATABASE_ERROR_SETLASTVISIT')); } } // If no timestamp value is passed to function, than current time is used. $date = JFactory::getDate($timeStamp); // Update the database row for the user. $db = $this->_db; $query = $db->getQuery(true); $query->update($db->quoteName($this->_tbl)); $query->set($db->quoteName('lastvisitDate') . '=' . $db->quote($date->toSql())); $query->where($db->quoteName('id') . '=' . (int) $userId); $db->setQuery($query); $db->execute(); // Check for a database error. if ($db->getErrorNum()) { $this->setError($db->getErrorMsg()); return false; } return true; } } home/academiac/www/libraries/cms/form/field/user.php 0000644 00000007333 15137437110 0016472 0 ustar 00 <?php /** * @package Joomla.Libraries * @subpackage Form * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Field to select a user id from a modal list. * * @package Joomla.Libraries * @subpackage Form * @since 1.6.0 */ class JFormFieldUser extends JFormField { /** * The form field type. * * @var string * @since 1.6.0 */ public $type = 'User'; /** * Method to get the user field input markup. * * @return string The field input markup. * * @since 1.6.0 */ protected function getInput() { // Initialize variables. $html = array(); $groups = $this->getGroups(); $excluded = $this->getExcluded(); $link = 'index.php?option=com_users&view=users&layout=modal&tmpl=component&field=' . $this->id . (isset($groups) ? ('&groups=' . base64_encode(json_encode($groups))) : '') . (isset($excluded) ? ('&excluded=' . base64_encode(json_encode($excluded))) : ''); // Initialize some field attributes. $attr = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; // Initialize JavaScript field attributes. $onchange = (string) $this->element['onchange']; // Load the modal behavior script. JHtml::_('behavior.modal', 'a.modal_' . $this->id); // Build the script. $script = array(); $script[] = ' function jSelectUser_' . $this->id . '(id, title) {'; $script[] = ' var old_id = document.getElementById("' . $this->id . '_id").value;'; $script[] = ' if (old_id != id) {'; $script[] = ' document.getElementById("' . $this->id . '_id").value = id;'; $script[] = ' document.getElementById("' . $this->id . '_name").value = title;'; $script[] = ' ' . $onchange; $script[] = ' }'; $script[] = ' SqueezeBox.close();'; $script[] = ' }'; // Add the script to the document head. JFactory::getDocument()->addScriptDeclaration(implode("\n", $script)); // Load the current username if available. $table = JTable::getInstance('user'); if ($this->value) { $table->load($this->value); } else { $table->name = JText::_('JLIB_FORM_SELECT_USER'); } // Create a dummy text field with the user name. $html[] = '<div class="fltlft">'; $html[] = ' <input type="text" id="' . $this->id . '_name"' . ' value="' . htmlspecialchars($table->name, ENT_COMPAT, 'UTF-8') . '"' . ' disabled="disabled"' . $attr . ' />'; $html[] = '</div>'; // Create the user select button. $html[] = '<div class="button2-left">'; $html[] = ' <div class="blank">'; if ($this->element['readonly'] != 'true') { $html[] = ' <a class="modal_' . $this->id . '" title="' . JText::_('JLIB_FORM_CHANGE_USER') . '"' . ' href="' . $link . '"' . ' rel="{handler: \'iframe\', size: {x: 800, y: 500}}">'; $html[] = ' ' . JText::_('JLIB_FORM_CHANGE_USER') . '</a>'; } $html[] = ' </div>'; $html[] = '</div>'; // Create the real field, hidden, that stored the user id. $html[] = '<input type="hidden" id="' . $this->id . '_id" name="' . $this->name . '" value="' . (int) $this->value . '" />'; return implode("\n", $html); } /** * Method to get the filtering groups (null means no filtering) * * @return mixed array of filtering groups or null. * * @since 1.6.0 */ protected function getGroups() { return null; } /** * Method to get the users to exclude from the list of users * * @return mixed Array of users to exclude or null to to not exclude them * * @since 1.6.0 */ protected function getExcluded() { return null; } } home/academiac/www/components/com_virtuemart/controllers/user.php 0000604 00000025610 15137453466 0021507 0 ustar 00 <?php /** * * Controller for the front end User maintenance * * @package VirtueMart * @subpackage User * @author Oscar van Eijk * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to 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. * @version $Id: user.php 6355 2012-08-20 09:23:27Z Milbo $ */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); // Load the controller framework jimport('joomla.application.component.controller'); /** * VirtueMart Component Controller * * @package VirtueMart */ class VirtueMartControllerUser extends JController { public function __construct() { parent::__construct(); $this->useSSL = VmConfig::get('useSSL',0); $this->useXHTML = false; VmConfig::loadJLang('com_virtuemart_shoppers',TRUE); } /** * Override of display to prevent caching * * @return JController A JController object to support chaining. */ public function display(){ $document = JFactory::getDocument(); $viewType = $document->getType(); $viewName = JRequest::getCmd('view', $this->default_view); $viewLayout = JRequest::getCmd('layout', 'default'); $view = $this->getView($viewName, $viewType, '', array('base_path' => $this->basePath, 'layout' => $viewLayout)); $view->assignRef('document', $document); $view->display(); return $this; } function edit(){ } /** * deprecated */ function editAddressST(){ $view = $this->getView('user', 'html'); $view->setLayout('edit_address'); $ftask ='saveAddressST'; $view->assignRef('fTask', $ftask); // Display it all $view->display(); } /** * This is for use in the cart, it calls a standard template for editing user adresses. It sets the task following into the form * of the template to saveCartUser, the task saveCartUser just sets the right redirect in the js save(). This is done just to have the * controll flow in the controller and not in the layout. The layout is everytime calling a standard joomla task. * * @author Max Milbers */ function editAddressCart(){ $view = $this->getView('user', 'html'); $view->setLayout('edit_address'); $ftask ='savecartuser'; $view->assignRef('fTask', $ftask); // Display it all $view->display(); } /** * This is for use in the checkout process, it is the same like editAddressCart, but it sets the save task * to saveCheckoutUser, the task saveCheckoutUser just sets the right redirect. This is done just to have the * controll flow in the controller and not in the layout. The layout is everytime calling a standard joomla task. * * @author Max Milbers */ function editAddressCheckout(){ $view = $this->getView('user', 'html'); $view->setLayout('edit_address'); $ftask ='savecheckoutuser'; $view->assignRef('fTask', $ftask); // Display it all $view->display(); } /** * This function is called from the layout edit_adress and just sets the right redirect back to the cart * We use here the saveData(true) function, because within the cart shouldnt be done any registration. * * @author Max Milbers */ function saveCheckoutUser(){ $msg = $this->saveData(true,VmConfig::get('reg_silent',0)); //We may add here the option for silent registration. $this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=cart&task=checkout',$this->useXHTML,$this->useSSL), $msg ); } function registerCheckoutUser(){ if($this->checkCaptcha('index.php?option=com_virtuemart&view=user&task=editaddresscheckout&addrtype=BT') != FALSE) { $msg = $this->saveData(true,true); $this->setRedirect(JRoute::_( 'index.php?option=com_virtuemart&view=cart&task=checkout',$this->useXHTML,$this->useSSL ),$msg); } } /** * This function is called from the layout edit_adress and just sets the right redirect back to the cart. * We use here the saveData(true) function, because within the cart shouldnt be done any registration. * * @author Max Milbers */ function saveCartUser(){ $addressType = vRequest::getString('address_type'); if($addressType=='BT'){ $msg = $this->saveData(true,VmConfig::get('reg_silent',0)); } else { $msg = $this->saveData(false,false,true); } $this->setRedirect(JRoute::_( 'index.php?option=com_virtuemart&view=cart', FALSE ),$msg); } function registerCartuser(){ if($this->checkCaptcha('index.php?option=com_virtuemart&view=user&task=editaddresscart&addrtype=BT') != FALSE) { $msg = $this->saveData(true, true); $this->setRedirect(JRoute::_('index.php?option=com_virtuemart&view=cart', FALSE) , $msg); } } /** * This is the save function for the normal user edit.php layout. * We use here directly the userModel store function, because this view is for registering also * it redirects to the standard user view. * * @author Max Milbers */ function saveUser(){ $layout = JRequest::getWord('layout','edit'); if($this->checkCaptcha('index.php?option=com_virtuemart&view=user&layout='.$layout) != FALSE) { $msg = $this->saveData(true, true); $this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, FALSE), $msg ); } } function saveAddressST(){ $msg = $this->saveData(false,false,true); $layout = 'edit';// JRequest::getWord('layout','edit'); $this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, FALSE), $msg ); } /** * Save the user info. The saveData function don't use the userModel store function for anonymous shoppers, because it would register them. * We make this function private, so we can do the tests in the tasks. * * @author Max Milbers * @author Valérie Isaksen * * @param boolean Defaults to false, the param is for the userModel->store function, which needs it to determine how to handle the data. * @return String it gives back the messages. */ private function saveData($cart=false,$register=false, $onlyAddress=false) { $mainframe = JFactory::getApplication(); $currentUser = JFactory::getUser(); $msg = ''; $data = JRequest::get('post'); if(empty($data['address_type'])){ $data['address_type'] = vRequest::getCmd('addrtype','BT'); } if($currentUser->guest!=1 || $register){ $userModel = VmModel::getModel('user'); if(!$cart){ // Store multiple selectlist entries as a ; separated string if (array_key_exists('vendor_accepted_currencies', $data) && is_array($data['vendor_accepted_currencies'])) { $data['vendor_accepted_currencies'] = implode(',', $data['vendor_accepted_currencies']); } $data['vendor_store_name'] = JRequest::getVar('vendor_store_name','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_store_desc'] = JRequest::getVar('vendor_store_desc','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_terms_of_service'] = JRequest::getVar('vendor_terms_of_service','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_letter_css'] = JRequest::getVar('vendor_letter_css','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_letter_header_html'] = JRequest::getVar('vendor_letter_header_html','','post','STRING',JREQUEST_ALLOWHTML); $data['vendor_letter_footer_html'] = JRequest::getVar('vendor_letter_footer_html','','post','STRING',JREQUEST_ALLOWHTML); } //It should always be stored if($onlyAddress){ $ret = $userModel->storeAddress($data); } else { $ret = $userModel->store($data); } if(!$onlyAddress and $currentUser->guest==1){ $msg = (is_array($ret)) ? $ret['message'] : $ret; $usersConfig = JComponentHelper::getParams( 'com_users' ); $useractivation = $usersConfig->get( 'useractivation' ); if (is_array($ret) and $ret['success'] and !$useractivation) { // Username and password must be passed in an array $credentials = array('username' => $ret['user']->username, 'password' => $ret['user']->password_clear ); $return = $mainframe->login($credentials); } else if(VmConfig::get('oncheckout_only_registered',0)){ $layout = JRequest::getWord('layout','edit'); $this->redirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, FALSE), $msg ); } } } if(!class_exists('VirtueMartCart')) require(JPATH_VM_SITE.DS.'helpers'.DS.'cart.php'); $cart = VirtueMartCart::getCart(); $cart->saveAddressInCart($data, $data['address_type']); return $msg; } /** * Editing a user address was cancelled when called from the cart; return to the cart * * @author Oscar van Eijk */ function cancelCartUser(){ $this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=cart', FALSE) ); } /** * Editing a user address was cancelled during chaeckout; return to the cart * * @author Oscar van Eijk */ function cancelCheckoutUser(){ $this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=cart&task=checkout',$this->useXHTML,$this->useSSL) ); } /** * Action cancelled; return to the previous view * * @author Oscar van Eijk */ function cancel() { $return = JURI::base(); $this->setRedirect( $return ); } function removeAddressST(){ $virtuemart_userinfo_id = JRequest::getVar('virtuemart_userinfo_id'); //Lets do it dirty for now $userModel = VmModel::getModel('user'); $userModel->removeAddress($virtuemart_userinfo_id); $layout = JRequest::getWord('layout','edit'); $this->setRedirect( JRoute::_('index.php?option=com_virtuemart&view=user&layout='.$layout, $this->useXHTML,$this->useSSL) ); } /** * Check the Joomla ReCaptcha Plg * * @author Maik Künnemann */ function checkCaptcha($retUrl){ if(JFactory::getUser()->guest==1 and VmConfig::get ('reg_captcha')){ $recaptcha = vRequest::getVar ('recaptcha_response_field'); JPluginHelper::importPlugin('captcha'); $dispatcher = JDispatcher::getInstance(); $res = $dispatcher->trigger('onCheckAnswer',$recaptcha); if(!$res[0]){ $data = vRequest::getPost(); $data['address_type'] = vRequest::getVar('addrtype','BT'); if(!class_exists('VirtueMartCart')) require(JPATH_VM_SITE.DS.'helpers'.DS.'cart.php'); $cart = VirtueMartCart::getCart(); $cart->saveAddressInCart($data, $data['address_type']); $errmsg = vmText::_('PLG_RECAPTCHA_ERROR_INCORRECT_CAPTCHA_SOL'); $this->setRedirect (JRoute::_ ($retUrl . '&captcha=1', FALSE), $errmsg); return FALSE; } else { return TRUE; } } else { return TRUE; } } } // No closing tag home/academiac/www/components/com_users/controllers/user.php 0000644 00000014563 15137707333 0020452 0 ustar 00 <?php /** * @package Joomla.Site * @subpackage com_users * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; require_once JPATH_COMPONENT.'/controller.php'; /** * Registration controller class for Users. * * @package Joomla.Site * @subpackage com_users * @since 1.6 */ class UsersControllerUser extends UsersController { /** * Method to log in a user. * * @since 1.6 */ public function login() { JSession::checkToken('post') or jexit(JText::_('JInvalid_Token')); $app = JFactory::getApplication(); // Populate the data array: $data = array(); $data['return'] = base64_decode(JRequest::getVar('return', '', 'POST', 'BASE64')); $data['username'] = JRequest::getVar('username', '', 'method', 'username'); $data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW); // Set the return URL if empty. if (empty($data['return'])) { $data['return'] = 'index.php?option=com_users&view=profile'; } // Set the return URL in the user state to allow modification by plugins $app->setUserState('users.login.form.return', $data['return']); // Get the log in options. $options = array(); $options['remember'] = JRequest::getBool('remember', false); $options['return'] = $data['return']; // Get the log in credentials. $credentials = array(); $credentials['username'] = $data['username']; $credentials['password'] = $data['password']; // Perform the log in. if (true === $app->login($credentials, $options)) { // Success $app->setUserState('users.login.form.data', array()); $app->redirect(JRoute::_($app->getUserState('users.login.form.return'), false)); } else { // Login failed ! $data['remember'] = (int)$options['remember']; $app->setUserState('users.login.form.data', $data); $app->redirect(JRoute::_('index.php?option=com_users&view=login', false)); } } /** * Method to log out a user. * * @since 1.6 */ public function logout() { JSession::checkToken('request') or jexit(JText::_('JInvalid_Token')); $app = JFactory::getApplication(); // Perform the log in. $error = $app->logout(); // Check if the log out succeeded. if (!($error instanceof Exception)) { // Get the return url from the request and validate that it is internal. $return = JRequest::getVar('return', '', 'method', 'base64'); $return = base64_decode($return); if (!JURI::isInternal($return)) { $return = ''; } // Redirect the user. $app->redirect(JRoute::_($return, false)); } else { $app->redirect(JRoute::_('index.php?option=com_users&view=login', false)); } } /** * Method to register a user. * * @since 1.6 */ public function register() { JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN')); // Get the form data. $data = JRequest::getVar('user', array(), 'post', 'array'); // Get the model and validate the data. $model = $this->getModel('Registration', 'UsersModel'); $return = $model->validate($data); // Check for errors. if ($return === false) { // Get the validation messages. $app = &JFactory::getApplication(); $errors = $model->getErrors(); // Push up to three validation messages out to the user. for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) { if ($errors[$i] instanceof Exception) { $app->enqueueMessage($errors[$i]->getMessage(), 'notice'); } else { $app->enqueueMessage($errors[$i], 'notice'); } } // Save the data in the session. $app->setUserState('users.registration.form.data', $data); // Redirect back to the registration form. $this->setRedirect('index.php?option=com_users&view=registration'); return false; } // Finish the registration. $return = $model->register($data); // Check for errors. if ($return === false) { // Save the data in the session. $app->setUserState('users.registration.form.data', $data); // Redirect back to the registration form. $message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError()); $this->setRedirect('index.php?option=com_users&view=registration', $message, 'error'); return false; } // Flush the data from the session. $app->setUserState('users.registration.form.data', null); exit; } /** * Method to login a user. * * @since 1.6 */ public function remind() { // Check the request token. JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN')); $app = JFactory::getApplication(); $model = $this->getModel('User', 'UsersModel'); $data = JRequest::getVar('jform', array(), 'post', 'array'); // Submit the username remind request. $return = $model->processRemindRequest($data); // Check for a hard error. if ($return instanceof Exception) { // Get the error message to display. if ($app->getCfg('error_reporting')) { $message = $return->getMessage(); } else { $message = JText::_('COM_USERS_REMIND_REQUEST_ERROR'); } // Get the route to the next page. $itemid = UsersHelperRoute::getRemindRoute(); $itemid = $itemid !== null ? '&Itemid='.$itemid : ''; $route = 'index.php?option=com_users&view=remind'.$itemid; // Go back to the complete form. $this->setRedirect(JRoute::_($route, false), $message, 'error'); return false; } elseif ($return === false) { // Complete failed. // Get the route to the next page. $itemid = UsersHelperRoute::getRemindRoute(); $itemid = $itemid !== null ? '&Itemid='.$itemid : ''; $route = 'index.php?option=com_users&view=remind'.$itemid; // Go back to the complete form. $message = JText::sprintf('COM_USERS_REMIND_REQUEST_FAILED', $model->getError()); $this->setRedirect(JRoute::_($route, false), $message, 'notice'); return false; } else { // Complete succeeded. // Get the route to the next page. $itemid = UsersHelperRoute::getLoginRoute(); $itemid = $itemid !== null ? '&Itemid='.$itemid : ''; $route = 'index.php?option=com_users&view=login'.$itemid; // Proceed to the login form. $message = JText::_('COM_USERS_REMIND_REQUEST_SUCCESS'); $this->setRedirect(JRoute::_($route, false), $message); return true; } } /** * Method to login a user. * * @since 1.6 */ public function resend() { // Check for request forgeries JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN')); } } home/academiac/www/administrator/components/com_users/models/user.php 0000644 00000041042 15140173626 0022233 0 ustar 00 <?php /** * @package Joomla.Administrator * @subpackage com_users * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access. defined('_JEXEC') or die; jimport('joomla.application.component.modeladmin'); jimport('joomla.access.access'); /** * User model. * * @package Joomla.Administrator * @subpackage com_users * @since 1.6 */ class UsersModelUser extends JModelAdmin { /** * Returns a reference to the a Table object, always creating it. * * @param string $type The table type to instantiate * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * * @return JTable A database object * * @since 1.6 */ public function getTable($type = 'User', $prefix = 'JTable', $config = array()) { $table = JTable::getInstance($type, $prefix, $config); return $table; } /** * Method to get a single record. * * @param integer $pk The id of the primary key. * * @return mixed Object on success, false on failure. * * @since 1.6 */ public function getItem($pk = null) { $result = parent::getItem($pk); // Get the dispatcher and load the users plugins. $dispatcher = JDispatcher::getInstance(); JPluginHelper::importPlugin('user'); // Trigger the data preparation event. $results = $dispatcher->trigger('onContentPrepareData', array('com_users.user', $result)); return $result; } /** * Method to get the record form. * * @param array $data An optional array of data for the form to interogate. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return mixed A JForm object on success, false on failure * * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Initialise variables. $app = JFactory::getApplication(); // Get the form. $form = $this->loadForm('com_users.user', 'user', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_users.edit.user.data', array()); if (empty($data)) { $data = $this->getItem(); } // TODO: Maybe this can go into the parent model somehow? // Get the dispatcher and load the users plugins. $dispatcher = JDispatcher::getInstance(); JPluginHelper::importPlugin('user'); // Trigger the data preparation event. $results = $dispatcher->trigger('onContentPrepareData', array('com_users.profile', $data)); // Check for errors encountered while preparing the data. if (count($results) && in_array(false, $results, true)) { $this->setError($dispatcher->getError()); } return $data; } /** * Override JModelAdmin::preprocessForm to ensure the correct plugin group is loaded. * * @param JForm $form A JForm object. * @param mixed $data The data expected for the form. * @param string $group The name of the plugin group to import (defaults to "content"). * * @return void * * @since 1.6 * @throws Exception if there is an error in the form event. */ protected function preprocessForm(JForm $form, $data, $group = 'user') { parent::preprocessForm($form, $data, $group); } /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. * * @since 1.6 */ public function save($data) { // Initialise variables; $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('user.id'); $user = JUser::getInstance($pk); $my = JFactory::getUser(); if ($data['block'] && $pk == $my->id && !$my->block) { $this->setError(JText::_('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF')); return false; } // Make sure that we are not removing ourself from Super Admin group $iAmSuperAdmin = $my->authorise('core.admin'); if ($iAmSuperAdmin && $my->get('id') == $pk) { // Check that at least one of our new groups is Super Admin $stillSuperAdmin = false; $myNewGroups = $data['groups']; foreach ($myNewGroups as $group) { $stillSuperAdmin = ($stillSuperAdmin) ? ($stillSuperAdmin) : JAccess::checkGroup($group, 'core.admin'); } if (!$stillSuperAdmin) { $this->setError(JText::_('COM_USERS_USERS_ERROR_CANNOT_DEMOTE_SELF')); return false; } } // Bind the data. if (!$user->bind($data)) { $this->setError($user->getError()); return false; } // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } $this->setState('user.id', $user->id); return true; } /** * Method to delete rows. * * @param array &$pks An array of item ids. * * @return boolean Returns true on success, false on failure. * * @since 1.6 */ public function delete(&$pks) { // Initialise variables. $user = JFactory::getUser(); $table = $this->getTable(); $pks = (array) $pks; // Check if I am a Super Admin $iAmSuperAdmin = $user->authorise('core.admin'); // Trigger the onUserBeforeSave event. JPluginHelper::importPlugin('user'); $dispatcher = JDispatcher::getInstance(); if (in_array($user->id, $pks)) { $this->setError(JText::_('COM_USERS_USERS_ERROR_CANNOT_DELETE_SELF')); return false; } // Iterate the items to delete each one. foreach ($pks as $i => $pk) { if ($table->load($pk)) { // Access checks. $allow = $user->authorise('core.delete', 'com_users'); // Don't allow non-super-admin to delete a super admin $allow = (!$iAmSuperAdmin && JAccess::check($pk, 'core.admin')) ? false : $allow; if ($allow) { // Get users data for the users to delete. $user_to_delete = JFactory::getUser($pk); // Fire the onUserBeforeDelete event. $dispatcher->trigger('onUserBeforeDelete', array($table->getProperties())); if (!$table->delete($pk)) { $this->setError($table->getError()); return false; } else { // Trigger the onUserAfterDelete event. $dispatcher->trigger('onUserAfterDelete', array($user_to_delete->getProperties(), true, $this->getError())); } } else { // Prune items that you can't change. unset($pks[$i]); JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED')); } } else { $this->setError($table->getError()); return false; } } return true; } /** * Method to block user records. * * @param array &$pks The ids of the items to publish. * @param integer $value The value of the published state * * @return boolean True on success. * * @since 1.6 */ function block(&$pks, $value = 1) { // Initialise variables. $app = JFactory::getApplication(); $dispatcher = JDispatcher::getInstance(); $user = JFactory::getUser(); // Check if I am a Super Admin $iAmSuperAdmin = $user->authorise('core.admin'); $table = $this->getTable(); $pks = (array) $pks; JPluginHelper::importPlugin('user'); // Access checks. foreach ($pks as $i => $pk) { if ($value == 1 && $pk == $user->get('id')) { // Cannot block yourself. unset($pks[$i]); JError::raiseWarning(403, JText::_('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF')); } elseif ($table->load($pk)) { $old = $table->getProperties(); $allow = $user->authorise('core.edit.state', 'com_users'); // Don't allow non-super-admin to delete a super admin $allow = (!$iAmSuperAdmin && JAccess::check($pk, 'core.admin')) ? false : $allow; // Prepare the logout options. $options = array( 'clientid' => array(0, 1) ); if ($allow) { // Skip changing of same state if ($table->block == $value) { unset($pks[$i]); continue; } $table->block = (int) $value; // If unblocking, also change password reset count to zero to unblock reset if ($table->block === 0) { $table->resetCount = 0; } // Allow an exception to be thrown. try { if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the onUserBeforeSave event. $result = $dispatcher->trigger('onUserBeforeSave', array($old, false, $table->getProperties())); if (in_array(false, $result, true)) { // Plugin will have to raise it's own error or throw an exception. return false; } // Store the table. if (!$table->store()) { $this->setError($table->getError()); return false; } // Trigger the onAftereStoreUser event $dispatcher->trigger('onUserAfterSave', array($table->getProperties(), false, true, null)); } catch (Exception $e) { $this->setError($e->getMessage()); return false; } // Log the user out. if ($value) { $app->logout($table->id, $options); } } else { // Prune items that you can't change. unset($pks[$i]); JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } } } return true; } /** * Method to activate user records. * * @param array &$pks The ids of the items to activate. * * @return boolean True on success. * * @since 1.6 */ function activate(&$pks) { // Initialise variables. $dispatcher = JDispatcher::getInstance(); $user = JFactory::getUser(); // Check if I am a Super Admin $iAmSuperAdmin = $user->authorise('core.admin'); $table = $this->getTable(); $pks = (array) $pks; JPluginHelper::importPlugin('user'); // Access checks. foreach ($pks as $i => $pk) { if ($table->load($pk)) { $old = $table->getProperties(); $allow = $user->authorise('core.edit.state', 'com_users'); // Don't allow non-super-admin to delete a super admin $allow = (!$iAmSuperAdmin && JAccess::check($pk, 'core.admin')) ? false : $allow; if (empty($table->activation)) { // Ignore activated accounts. unset($pks[$i]); } elseif ($allow) { $table->block = 0; $table->activation = ''; // Allow an exception to be thrown. try { if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the onUserBeforeSave event. $result = $dispatcher->trigger('onUserBeforeSave', array($old, false, $table->getProperties())); if (in_array(false, $result, true)) { // Plugin will have to raise it's own error or throw an exception. return false; } // Store the table. if (!$table->store()) { $this->setError($table->getError()); return false; } // Fire the onAftereStoreUser event $dispatcher->trigger('onUserAfterSave', array($table->getProperties(), false, true, null)); } catch (Exception $e) { $this->setError($e->getMessage()); return false; } } else { // Prune items that you can't change. unset($pks[$i]); JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } } } return true; } /** * Method to perform batch operations on an item or a set of items. * * @param array $commands An array of commands to perform. * @param array $pks An array of item ids. * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. * * @since 2.5 */ public function batch($commands, $pks, $contexts) { // Sanitize user ids. $pks = array_unique($pks); JArrayHelper::toInteger($pks); // Remove any values of zero. if (array_search(0, $pks, true)) { unset($pks[array_search(0, $pks, true)]); } if (empty($pks)) { $this->setError(JText::_('COM_USERS_USERS_NO_ITEM_SELECTED')); return false; } $done = false; if (!empty($commands['group_id'])) { $cmd = JArrayHelper::getValue($commands, 'group_action', 'add'); if (!$this->batchUser((int) $commands['group_id'], $pks, $cmd)) { return false; } $done = true; } if (!$done) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } // Clear the cache $this->cleanCache(); return true; } /** * Perform batch operations * * @param integer $group_id The group ID which assignments are being edited * @param array $user_ids An array of user IDs on which to operate * @param string $action The action to perform * * @return boolean True on success, false on failure * * @since 1.6 */ public function batchUser($group_id, $user_ids, $action) { // Get the DB object $db = $this->getDbo(); JArrayHelper::toInteger($user_ids); // Non-super admin cannot work with super-admin group if ((!JFactory::getUser()->get('isRoot') && JAccess::checkGroup($group_id, 'core.admin')) || $group_id < 1) { $this->setError(JText::_('COM_USERS_ERROR_INVALID_GROUP')); return false; } switch ($action) { // Sets users to a selected group case 'set': $doDelete = 'all'; $doAssign = true; break; // Remove users from a selected group case 'del': $doDelete = 'group'; break; // Add users to a selected group case 'add': default: $doAssign = true; break; } // Remove the users from the group if requested. if (isset($doDelete)) { $query = $db->getQuery(true); // Remove users from the group $query->delete($db->quoteName('#__user_usergroup_map')); $query->where($db->quoteName('user_id') . ' IN (' . implode(',', $user_ids) . ')'); // Only remove users from selected group if ($doDelete == 'group') { $query->where($db->quoteName('group_id') . ' = ' . (int) $group_id); } $db->setQuery($query); // Check for database errors. if (!$db->query()) { $this->setError($db->getErrorMsg()); return false; } } // Assign the users to the group if requested. if (isset($doAssign)) { $query = $db->getQuery(true); // First, we need to check if the user is already assigned to a group $query->select($db->quoteName('user_id')); $query->from($db->quoteName('#__user_usergroup_map')); $query->where($db->quoteName('group_id') . ' = ' . (int) $group_id); $db->setQuery($query); $users = $db->loadColumn(); // Build the values clause for the assignment query. $query->clear(); $groups = false; foreach ($user_ids as $id) { if (!in_array($id, $users)) { $query->values($id . ',' . $group_id); $groups = true; } } // If we have no users to process, throw an error to notify the user if (!$groups) { $this->setError(JText::_('COM_USERS_ERROR_NO_ADDITIONS')); return false; } $query->insert($db->quoteName('#__user_usergroup_map')); $query->columns(array($db->quoteName('user_id'), $db->quoteName('group_id'))); $db->setQuery($query); // Check for database errors. if (!$db->query()) { $this->setError($db->getErrorMsg()); return false; } } return true; } /** * Gets the available groups. * * @return array An array of groups * * @since 1.6 */ public function getGroups() { $user = JFactory::getUser(); if ($user->authorise('core.edit', 'com_users') && $user->authorise('core.manage', 'com_users')) { $model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true)); return $model->getItems(); } else { return null; } } /** * Gets the groups this object is assigned to * * @param integer $userId The user ID to retrieve the groups for * * @return array An array of assigned groups * * @since 1.6 */ public function getAssignedGroups($userId = null) { // Initialise variables. $userId = (!empty($userId)) ? $userId : (int) $this->getState('user.id'); if (empty($userId)) { $result = array(); $groupsIDs = $this->getForm()->getValue('groups'); if (!empty($groupsIDs)) { $result = $groupsIDs; } else { $config = JComponentHelper::getParams('com_users'); if ($groupId = $config->get('new_usertype')) { $result[] = $groupId; } } } else { $result = JUserHelper::getUserGroups($userId); } return $result; } }
©
2018.