/**
  * Handles authentication via Twitter and reports back to the subject
  *
  * @param   array   $credentials  Array holding the user credentials
  * @param   array   $options      Array of extra options
  * @param   object  &$response    Authentication response object
  *
  * @return  boolean
  */
 public function onUserAuthenticate($credentials, $options, &$response)
 {
     $response->type = $this->_name;
     if (JArrayHelper::getValue($options, 'action') == 'core.login.site') {
         $username = JArrayHelper::getValue($credentials, 'username');
         $name = JArrayHelper::getValue($credentials, 'name');
         $email = JArrayHelper::getValue($credentials, 'email');
         if (!$username) {
             $response->status = JAuthentication::STATUS_FAILURE;
             $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
             return false;
         }
         if ($user = new JUser(JUserHelper::getUserId($username))) {
             if ($user->get('block') || $user->get('activation')) {
                 $response->status = JAuthentication::STATUS_FAILURE;
                 $response->error_message = JText::_('JGLOBAL_AUTH_ACCESS_DENIED');
                 return;
             }
         }
         $response->email = $email;
         $response->fullname = $name;
         $response->username = $username;
         $response->status = JAuthentication::STATUS_SUCCESS;
         $response->error_message = '';
     }
 }
Ejemplo n.º 2
0
 /**
  * Run when a membership activated
  * @param PlanOsMembership $row
  */
 function onMembershipActive($row)
 {
     if (!$row->user_id && $row->username && $row->user_password) {
         //Need to create the account here
         $data['name'] = trim($row->first_name . ' ' . $row->last_name);
         //Decrypt the password
         $data['username'] = $row->username;
         //Password
         $privateKey = md5(JFactory::getConfig()->get('secret'));
         $key = new JCryptKey('simple', $privateKey, $privateKey);
         $crypt = new JCrypt(new JCryptCipherSimple(), $key);
         $data['password'] = $data['password2'] = $data['password'] = $crypt->decrypt($row->user_password);
         $data['email1'] = $data['email2'] = $data['email'] = $row->email;
         $params = JComponentHelper::getParams('com_users');
         $data['groups'] = array();
         $data['groups'][] = $params->get('new_usertype', 2);
         $user = new JUser();
         if (!$user->bind($data)) {
             return false;
         }
         // Store the data.
         if (!$user->save()) {
             return false;
         }
         $row->user_id = $user->get('id');
         $row->store();
     }
 }
Ejemplo n.º 3
0
 function edit()
 {
     $mainframe = JFactory::getApplication();
     $jshopConfig = JSFactory::getConfig();
     $db = JFactory::getDBO();
     $me = JFactory::getUser();
     $user_id = JRequest::getInt("user_id");
     $user = JTable::getInstance('userShop', 'jshop');
     $user->load($user_id);
     $user_site = new JUser($user_id);
     $_countries = $this->getModel("countries");
     $countries = $_countries->getAllCountries(0);
     $lists['country'] = JHTML::_('select.genericlist', $countries, 'country', 'class = "inputbox" size = "1"', 'country_id', 'name', $user->country);
     $lists['d_country'] = JHTML::_('select.genericlist', $countries, 'd_country', 'class = "inputbox endes" size = "1"', 'country_id', 'name', $user->d_country);
     $user->birthday = getDisplayDate($user->birthday, $jshopConfig->field_birthday_format);
     $user->d_birthday = getDisplayDate($user->d_birthday, $jshopConfig->field_birthday_format);
     $option_title = array();
     foreach ($jshopConfig->user_field_title as $key => $value) {
         $option_title[] = JHTML::_('select.option', $key, $value, 'title_id', 'title_name');
     }
     $lists['select_titles'] = JHTML::_('select.genericlist', $option_title, 'title', 'class = "inputbox"', 'title_id', 'title_name', $user->title);
     $lists['select_d_titles'] = JHTML::_('select.genericlist', $option_title, 'd_title', 'class = "inputbox endes"', 'title_id', 'title_name', $user->d_title);
     $client_types = array();
     foreach ($jshopConfig->user_field_client_type as $key => $value) {
         $client_types[] = JHTML::_('select.option', $key, $value, 'id', 'name');
     }
     $lists['select_client_types'] = JHTML::_('select.genericlist', $client_types, 'client_type', 'class = "inputbox" ', 'id', 'name', $user->client_type);
     $_usergroups = $this->getModel("userGroups");
     $usergroups = $_usergroups->getAllUsergroups();
     $lists['usergroups'] = JHTML::_('select.genericlist', $usergroups, 'usergroup_id', 'class = "inputbox" size = "1"', 'usergroup_id', 'usergroup_name', $user->usergroup_id);
     $lists['block'] = JHTML::_('select.booleanlist', 'block', 'class="inputbox" size="1"', $user_site->get('block'));
     filterHTMLSafe($user, ENT_QUOTES);
     $tmp_fields = $jshopConfig->getListFieldsRegister();
     $config_fields = $tmp_fields['editaccount'];
     $count_filed_delivery = $jshopConfig->getEnableDeliveryFiledRegistration('editaccount');
     JHTML::_('behavior.calendar');
     $view = $this->getView("users", 'html');
     $view->setLayout("edit");
     $view->assign('config', $jshopConfig);
     $view->assign('user', $user);
     $view->assign('me', $me);
     $view->assign('user_site', $user_site);
     $view->assign('lists', $lists);
     $view->assign('etemplatevar', '');
     $view->assign('config_fields', $config_fields);
     $view->assign('count_filed_delivery', $count_filed_delivery);
     JPluginHelper::importPlugin('jshoppingadmin');
     $dispatcher = JDispatcher::getInstance();
     $dispatcher->trigger('onBeforeEditUsers', array(&$view));
     $view->displayEdit();
 }
Ejemplo n.º 4
0
 /**
  * Checks if the content is liked.
  *
  * @return  boolean  True if user liked the content, false otherwise.
  *
  * @since   12.1
  * @throws  LogicException
  * @throws  RuntimeException
  */
 public function isLiked()
 {
     // Assert the object is loaded.
     $this->assertIsLoaded();
     // Build a database query to check the liked state.
     $query = $this->db->getQuery(true);
     $query->select('*');
     $query->from($this->db->qn('#__content_likes'));
     $query->where('content_id = ' . (int) $this->content_id);
     $query->where('user_id = ' . (int) $this->user->get('id'));
     // Check the liked state.
     $this->db->setQuery($query);
     $result = $this->db->loadObject();
     return empty($result) ? false : true;
 }
Ejemplo n.º 5
0
 function edit()
 {
     $mainframe = JFactory::getApplication();
     $jshopConfig = JSFactory::getConfig();
     $db = JFactory::getDBO();
     $me = JFactory::getUser();
     $user_id = JRequest::getInt("user_id");
     $user = JSFactory::getTable('userShop', 'jshop');
     $user->load($user_id);
     $user->loadDataFromEdit();
     $user_site = new JUser($user_id);
     $lists['country'] = JshopHelpersSelects::getCountry($user->country);
     $lists['d_country'] = JshopHelpersSelects::getCountry($user->d_country, 'class = "inputbox endes"', 'd_country');
     $lists['select_titles'] = JshopHelpersSelects::getTitle($user->title);
     $lists['select_d_titles'] = JshopHelpersSelects::getTitle($user->d_title, 'class = "inputbox endes"', 'd_title');
     $lists['select_client_types'] = JshopHelpersSelects::getClientType($user->client_type);
     $usergroups = JSFactory::getModel("userGroups")->getAllUsergroups();
     $lists['usergroups'] = JHTML::_('select.genericlist', $usergroups, 'usergroup_id', 'class = "inputbox" size = "1"', 'usergroup_id', 'usergroup_name', $user->usergroup_id);
     $lists['block'] = JHTML::_('select.booleanlist', 'block', 'class="inputbox" size="1"', $user_site->get('block'));
     filterHTMLSafe($user, ENT_QUOTES);
     $tmp_fields = $jshopConfig->getListFieldsRegister();
     $config_fields = $tmp_fields['editaccount'];
     $count_filed_delivery = $jshopConfig->getEnableDeliveryFiledRegistration('editaccount');
     JHTML::_('behavior.calendar');
     $view = $this->getView("users", 'html');
     $view->setLayout("edit");
     $view->assign('config', $jshopConfig);
     $view->assign('user', $user);
     $view->assign('me', $me);
     $view->assign('user_site', $user_site);
     $view->assign('lists', $lists);
     $view->assign('etemplatevar', '');
     $view->assign('config_fields', $config_fields);
     $view->assign('count_filed_delivery', $count_filed_delivery);
     JDispatcher::getInstance()->trigger('onBeforeEditUsers', array(&$view));
     $view->displayEdit();
 }
Ejemplo n.º 6
0
 function onLoginUser($user, $options)
 {
     $app = JFactory::getApplication();
     if ($app->isAdmin()) {
         return true;
     }
     $user_id = 0;
     if (empty($user['id'])) {
         if (!empty($user['username'])) {
             jimport('joomla.user.helper');
             $instance = new JUser();
             if ($id = intval(JUserHelper::getUserId($user['username']))) {
                 $instance->load($id);
             }
             if ($instance->get('block') == 0) {
                 $user_id = $instance->id;
             }
         }
     } else {
         $user_id = $user['id'];
     }
     $this->restoreSession($user_id);
     if (empty($user_id)) {
         return true;
     }
     if (!defined('DS')) {
         define('DS', DIRECTORY_SEPARATOR);
     }
     if (!(include_once rtrim(JPATH_ADMINISTRATOR, DS) . DS . 'components' . DS . 'com_hikashop' . DS . 'helpers' . DS . 'helper.php')) {
         return true;
     }
     $userClass = hikashop_get('class.user');
     $hika_user_id = $userClass->getID($user_id, 'cms');
     if (empty($hika_user_id)) {
         return true;
     }
     $addressClass = hikashop_get('class.address');
     $addresses = $addressClass->getByUser($hika_user_id);
     if (empty($addresses) || !count($addresses)) {
         return true;
     }
     $address = reset($addresses);
     $field = 'address_country';
     if (!empty($address->address_state)) {
         $field = 'address_state';
     }
     $app->setUserState(HIKASHOP_COMPONENT . '.shipping_address', $address->address_id);
     $app->setUserState(HIKASHOP_COMPONENT . '.billing_address', $address->address_id);
     $zoneClass = hikashop_get('class.zone');
     $zone = $zoneClass->get($address->{$field});
     if (!empty($zone)) {
         $zone_id = $zone->zone_id;
         $app->setUserState(HIKASHOP_COMPONENT . '.zone_id', $zone->zone_id);
     }
 }
Ejemplo n.º 7
0
function saveJanrainEngageUser($auth_info) 
{
	global $mainframe;
	jimport('joomla.user.helper');
	$db		=& JFactory::getDBO();
	$my 	=& JFactory::getUser();
	$uri 	=& JFactory::getURI();
	$host 	= $uri->getHost();

	// process the auth_info response
	$profileValues 	= $auth_info['profile'];
	$identifier 	= $profileValues['identifier'];	
	
	if( !isset($auth_info['profile']['email'] )) 
	{
		$nameDisp = str_replace(' ','_',$auth_info['profile']['displayName']);
		$auth_info['profile']['email'] = $nameDisp.'@'.$host;
	}
	
	$query = "SELECT `id` FROM #__users WHERE `email`='".$auth_info['profile']['email']."'";
	$db->setQuery($query);
	$userid = $db->loadResult();
	
	$newuser = true;
	if( isset($userid) ) 
	{
		$user =& JFactory::getUser($userid);
		if ($user->id == $userid) 
		{
            $newuser = false;
        }
	}
	if($newuser == true) 
	{
		//save the user
		$user 			= new JUser();
		$authorize 		=& JFactory::getACL();
		$date 			=& JFactory::getDate();
		$uriInfo 		= JFactory::getURI();
		$host 			= $uriInfo->getHost();
		$usersConfig	=& JComponentHelper::getParams( 'com_users' );
		$newUsertype	= $usersConfig->get( 'new_usertype' );
		
		$user->set('id', 0);
		$user->set('usertype', $newUsertype);
		$user->set('gid', $authorize->get_group_id('',$newUsertype, 'ARO'));
		$user->set('registerDate', $date->toMySQL());
		
		if(isset($auth_info['profile']['displayName'])) 
		{
			$displayName = $auth_info['profile']['displayName'];
		} 
		elseif(isset($auth_info['profile']['name']['displayName'])) 
		{
			$displayName = $auth_info['profile']['name']['displayName'];
		}
		
		if(isset($auth_info['profile']['preferredUsername'])) 
		{
			$preferredUsername = $auth_info['profile']['preferredUsername'];
		} 
		elseif(isset($auth_info['profile']['name']['preferredUsername'])) 
		{
			$preferredUsername = $auth_info['profile']['name']['preferredUsername'];
		}

		$user->set('name', $displayName);
		// if username already exists, just add an index to it
		$nameexists = true;
		$index 		= 0;
		$userName 	= $preferredUsername;
		while ($nameexists == true) 
		{
			if(JUserHelper::getUserId($userName) != 0) 
			{
				$index++;
				$userName = $preferredUsername.$index;
			} 
			else 
			{
				$nameexists = false;
			}
		}
		$user->set('username', $userName);
	  
		$sEmail = '';
		if(isset($auth_info['profile']['email'])) 
		{
			$sEmail = $auth_info['profile']['email'];
			$user->set('email', $auth_info['profile']['email']);
		} 
		elseif (isset($auth_info['profile']['name']['email'])) 
		{
		  	$sEmail = $auth_info['profile']['email'];
		  	$user->set('email', $auth_info['profile']['email']);
		} 
		
		$pwd = JUserHelper::genRandomPassword();
		$user->set('password', $pwd);
		
		if (!$user->save()) 
		{
			echo "ERROR: ";
			echo $user->getError();
		}
		
		// admin users gid
		$gid 		= 25;
		$query 		= "SELECT `email`, `name` FROM `#__users` WHERE `gid` = '".$gid."'";
		$db->setQuery( $query );		
		$adminRows 	= $db->loadObjectList();
	
		// send email notification to admins
		if( !empty($adminRows) ) 
		{
			foreach($adminRows as $adminRow) 
			{
				$sitename 	= $mainframe->getCfg( 'sitename' );
				$siteRoot   = JURI::base();
			
				$userName	= $user->get('username');
				$userID		= $user->get('id');
				$userTupe	= $user->get('usertype');
				$userEmail	= $user->get('email');
				$adminName 	= $adminRow->name;
				$adminEmail = $adminRow->email;
				
				$subject	= JText::_('New user registered via JAINARAIN ENGANGE at')." ".$sitename;
				$subject 	= html_entity_decode($subject, ENT_QUOTES);	
		
				$message 	= JText::_('Hello')." ".$adminName."\n";
				$message 	.= JText::_('New user registered via JAINARAIN ENGANGE at')." ".$siteRoot."\n\n";
				$message 	.= JText::_('User Detail:')."\n";
				$message 	.= JText::_('User ID :')." ".$userID."\n";
				$message 	.= JText::_('Usertype :')." ".$userTupe."\n";
				$message 	.= JText::_('Name :')." ".$displayName."\n";
				$message 	.= JText::_('Username :'******'Email :')." ".$sEmail."\n";
				$message 	= html_entity_decode($message, ENT_QUOTES);
	
				JUtility::sendMail( $userName, $userEmail, $adminEmail,  $subject, $message );
			}
		}
			
		// check if the community builder tables are there
		$query 			= "SHOW TABLES LIKE '%__comprofiler'";
		$db->setQuery($query);
		$tableexists	= $db->loadResult();

		if( isset($tableexists) ) 
		{
			 $cbquery = "INSERT IGNORE INTO #__comprofiler(id,user_id,firstname,lastname) VALUES ('".$user->get('id')."','".$user->get('id')."','".$auth_info['profile']['name']['givenName']."','".$auth_info['profile']['name']['familyName']."')";
			$db->setQuery($cbquery);
			if (!$db->query()) 
			{
				JERROR::raiseError(500, $db->stderror());
			}
			else 
			{
				if($auth_info['profile']['photo']) 
				{
					global $_CB_database, $_CB_framework,   $ueConfig, $_PLUGINS ;
					if ( defined( 'JPATH_ADMINISTRATOR' ) ) 
					{
						include_once JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php';
						require_once $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/comprofiler.html.php';						
					} 
					else 
					{						
						include_once $mainframe->getCfg( 'absolute_path' ). '/administrator/components/com_comprofiler/plugin.foundation.php';						
						require_once $mainframe->getPath( 'front_html' );						
					}
					$filename		=	urldecode(uniqid($user->get('id')."_"));
					
					// replace every space-character with a single "_"
					$filename		=	preg_replace( "/ /", "_",	 $filename );				
					// Get rid of extra underscores						
					$filename		=	preg_replace( "/_+/", "_",	 $filename );						
					$filename		=	preg_replace( "/(^_|_$)/", "", $filename );						
					$tag			=	preg_replace( "/^.*\\.([^\\.]*)$/", "\\1", $auth_info['profile']['photo'] );	
					$tag			=	strtolower( $tag );						
					$newFileName		=	$filename . ".jpg";					 
					$file		=	$_CB_framework->getCfg('absolute_path') . '/images/comprofiler/' . $newFileName;						
					copy( $auth_info['profile']['photo'], $file );						
					
					$db->setQuery("UPDATE #__comprofiler SET avatar='" .$newFileName . "', avatarapproved=1, lastupdatedate='".date('Y-m-d\TH:i:s')."' WHERE id=" . (int) $user->get('id'));						
					$db->query();
				}
			}
		}
					
		// check if the Jomsocial tables are there, then set avatar
		$query = "SHOW TABLES LIKE '%__community_users'";
		$db->setQuery($query);
		$Jomtableexists = $db->loadResult();

		if (isset($Jomtableexists) && $auth_info['profile']['photo']) 
		{
			jimport('joomla.filesystem.file');
			jimport('joomla.utilities.utility');
			require_once(JPATH_ROOT.DS.'components'.DS.'com_community'.DS.'helpers'.DS.'image.php');
				
			$fileName	= JUtility::getHash( $auth_info['profile']['photo'] . time() );
			$fileName	= JString::substr( $fileName , 0 , 24 );
								   
			$avatarimage		= 'images/avatar/' . $fileName.'.jpg' ;
			$thumbavatar		= 'images/avatar/' . 'thumb_' . $fileName.'.jpg' ;
							

			$st = JPATH_ROOT;
			$jPath = split('\administrator',$st);
			 
			$storage	 = $jPath[0] . DS . 'images' . DS . 'avatar'. DS .   $fileName.'.jpg';
			$storageThumbnail	= $jPath[0] . DS .'images'.DS . 'avatar'. DS . 'thumb_' . $fileName.'.jpg' ;
			$destType = 'image/jpg';
			$imageMaxWidth	= 140; 
			   
			// Only resize when the width exceeds the max.
			if( !cImageResizePropotional( $auth_info['profile']['photo'] , $storage , $destType , $imageMaxWidth ) ) 
			{
				global $option,$mainframe;
				$msg = JText::sprintf( 'Image Upload Error '); 	
			}
	
			// Generate thumbnail
			if(!cImageCreateThumb( $auth_info['profile']['photo'] , $storageThumbnail , $destType  )) 
			{
				global $option,$mainframe;
				$msg = JText::sprintf( 'Image Upload Error '); 	
			}			
														 
			$query = "SELECT `userid` FROM `#__community_users` WHERE `userid`='" . $user->get('id') . "'";
			$db->setQuery( $query );
			if($db->loadResult()) 
			{				
				$query = "UPDATE `#__community_users` SET `avatar` = '" . $avatarimage . "', `thumb` = '" .$thumbavatar . "' WHERE `userid`='" . $user->get('id') . "'";
			}
			else 
			{
				$query = "INSERT INTO `#__community_users` SET `userid`='" . $user->get('id') . "', `avatar` = '" . $avatarimage . "', `thumb` = '" .$thumbavatar . "'";
			}
			$db->setQuery( $query );
			$db->query();		 
		}
	}

	// Get an ACL object
	$acl =& JFactory::getACL();

	// Get the user group from the ACL
	if ($user->get('tmp_user') == 1) 
	{
		$grp = new JObject;
		// This should be configurable at some point
		$grp->set('name', 'Registered');
	} 
	else 
	{
		$grp = $acl->getAroGroup($user->get('id'));
	}

	//Mark the user as logged in
	$user->set( 'guest', 0 );
	$user->set( 'aid', 1 );

	// Fudge Authors, Editors, Publishers and Super Administrators into the special access group
	if($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) 
	{
		 $user->set('aid', 2);
	}

	//Set the usertype based on the ACL group name
	$user->set('usertype', $grp->name);

	// Register the needed session variables
	$session =& JFactory::getSession();
	$session->set('user', $user);

	// Get the session object
	$table =& JTable::getInstance('session');
	$table->load( $session->getId() );
	$table->guest           = $user->get('guest');
	$table->username        = $user->get('username');
	$table->userid          = intval($user->get('id'));
	$table->usertype        = $user->get('usertype');
	$table->gid             = intval($user->get('gid'));

	$table->update();

	// Hit the user last visit field
	$user->setLastVisit();
	 
	// redirect
	global $redirectUrl;
	$returnURL = $redirectUrl;
	$mainframe->redirect($returnURL); 

}
Ejemplo n.º 8
0
 /**
  * Saves the record
  */
 function save()
 {
     global $mainframe;
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $option = JRequest::getCmd('option');
     // Initialize some variables
     $db =& JFactory::getDBO();
     $me =& JFactory::getUser();
     $acl =& JFactory::getACL();
     $MailFrom = $mainframe->getCfg('mailfrom');
     $FromName = $mainframe->getCfg('fromname');
     $SiteName = $mainframe->getCfg('sitename');
     // Create a new JUser object
     $user = new JUser(JRequest::getVar('id', 0, 'post', 'int'));
     $original_gid = $user->get('gid');
     $post = JRequest::get('post');
     $post['username'] = JRequest::getVar('username', '', 'post', 'username');
     $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
     if (!$user->bind($post)) {
         $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $mainframe->enqueueMessage($user->getError(), 'error');
         //$mainframe->redirect( 'index.php?option=com_users', $user->getError() );
         //return false;
         return $this->execute('edit');
     }
     $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO');
     $groups = $acl->get_object_groups($objectID, 'ARO');
     $this_group = strtolower($acl->get_group_name($groups[0], 'ARO'));
     if ($user->get('id') == $me->get('id') && $user->get('block') == 1) {
         $msg = JText::_('You cannot block Yourself!');
         $mainframe->enqueueMessage($msg, 'message');
         return $this->execute('edit');
     } else {
         if ($this_group == 'super administrator' && $user->get('block') == 1) {
             $msg = JText::_('You cannot block a Super Administrator');
             $mainframe->enqueueMessage($msg, 'message');
             return $this->execute('edit');
         } else {
             if ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) {
                 $msg = JText::_('WARNBLOCK');
                 $mainframe->enqueueMessage($msg, 'message');
                 return $this->execute('edit');
             } else {
                 if ($this_group == 'super administrator' && $me->get('gid') != 25) {
                     $msg = JText::_('You cannot edit a super administrator account');
                     $mainframe->enqueueMessage($msg, 'message');
                     return $this->execute('edit');
                 }
             }
         }
     }
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if (!$isNew) {
         // if group has been changed and where original group was a Super Admin
         if ($user->get('gid') != $original_gid && $original_gid == 25) {
             // count number of active super admins
             $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count <= 1) {
                 // disallow change if only one Super Admin exists
                 $this->setRedirect('index.php?option=com_users', JText::_('WARN_ONLY_SUPER'));
                 return false;
             }
         }
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $mainframe->enqueueMessage($user->getError(), 'error');
         return $this->execute('edit');
     }
     /*
      * Time for the email magic so get ready to sprinkle the magic dust...
      */
     if ($isNew) {
         $adminEmail = $me->get('email');
         $adminName = $me->get('name');
         $subject = JText::_('NEW_USER_MESSAGE_SUBJECT');
         $message = sprintf(JText::_('NEW_USER_MESSAGE'), $user->get('name'), $SiteName, JURI::root(), $user->get('username'), $user->password_clear);
         if ($MailFrom != '' && $FromName != '') {
             $adminName = $FromName;
             $adminEmail = $MailFrom;
         }
         JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message);
     }
     // If updating self, load the new user object into the session
     if ($user->get('id') == $me->get('id')) {
         // Get an ACL object
         $acl =& JFactory::getACL();
         // Get the user group from the ACL
         $grp = $acl->getAroGroup($user->get('id'));
         // Mark the user as logged in
         $user->set('guest', 0);
         $user->set('aid', 1);
         // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
         if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
             $user->set('aid', 2);
         }
         // Set the usertype based on the ACL group name
         $user->set('usertype', $grp->name);
         $session =& JFactory::getSession();
         $session->set('user', $user);
     }
     switch ($this->getTask()) {
         case 'apply':
             $msg = JText::sprintf('Successfully Saved changes to User', $user->get('name'));
             $this->setRedirect('index.php?option=com_users&view=user&task=edit&cid[]=' . $user->get('id'), $msg);
             break;
         case 'save':
         default:
             $msg = JText::sprintf('Successfully Saved User', $user->get('name'));
             $this->setRedirect('index.php?option=com_users', $msg);
             break;
     }
 }
Ejemplo n.º 9
0
 /**
  * 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 static function storeVM25(&$data, $checkToken = TRUE, &$userModel, $opc_no_activation = false, &$opc)
 {
     $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.
     $user = JFactory::getUser();
     $user_id = $user->id;
     $new = $user->id < 1;
     if (empty($user_id)) {
         $user = new JUser();
         //thealmega http://forum.virtuemart.net/index.php?topic=99755.msg393758#msg393758
     } else {
         $user = JFactory::getUser($user_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, $user_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;
         }
     }
     $data['email'] = str_replace(array('\'', '"', ',', '%', '*', '/', '\\', '?', '^', '`', '{', '}', '|', '~'), array(''), $data['email']);
     unset($data['isRoot']);
     unset($data['groups']);
     unset($data['_authGroups']);
     //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;
         }
     }
     if (empty($data['name'])) {
         $data['name'] = '';
         if (!empty($data['first_name'])) {
             $data['name'] = $data['first_name'];
         }
         if ($data['name'] == '_') {
             $data['name'] = '';
         }
         if (!empty($data['last_name'])) {
             $data['name'] = $data['last_name'];
         }
         if ($data['name'] == '_') {
             $data['name'] = '';
         }
         if (empty($data['name'])) {
             $data['name'] = $data['username'];
         }
         if ($data['name'] == '_') {
             $data['name'] = '';
         }
         if (empty($data['name'])) {
             $data['name'] = $data['email'];
         }
     }
     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['username'])) {
                 $data['username'] = $data['email'];
             }
         }
     }
     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']);
     }
     $usersConfig = JComponentHelper::getParams('com_users');
     $usernamechange = $usersConfig->get('change_login_name', true);
     if (!$new) {
         if (empty($usernamechange)) {
             $data['username'] = $user->get('username');
         }
     }
     if (!$user->authorise('core.admin', 'com_virtuemart')) {
         $whiteDataToBind = array();
         $whiteDataToBind['name'] = $data['name'];
         $whiteDataToBind['username'] = $data['username'];
         $whiteDataToBind['email'] = $data['email'];
         if (isset($data['password'])) {
             $whiteDataToBind['password'] = $data['password'];
         }
         if (isset($data['password2'])) {
             $whiteDataToBind['password2'] = $data['password2'];
         }
     } else {
         $whiteDataToBind = $data;
     }
     // Bind Joomla userdata
     if (!$user->bind($whiteDataToBind)) {
         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';
     }
     if ($new) {
         // If user registration is not allowed, show 403 not authorized.
         // But it is possible for admins and storeadmins to save
         /*
         JPluginHelper::importPlugin('user');
         JPluginHelper::importPlugin('system');
         $dispatcher = JDispatcher::getInstance();
         
         $valid = true ;
         $dispatcher->trigger('onAfterStoreUser',array($user,true,true,'' ));
         */
         if (!defined('VM_VERSION') || VM_VERSION < 3) {
             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'));
                 $data['virtuemart_user_id'] = 0;
                 unset($data['username']);
                 unset($data['password']);
                 unset($data['password2']);
                 $user = new JUser();
                 $userModel->_id = 0;
                 //$userModel->saveUserData($data);
                 $opc->userStoreAddress($userModel, $data);
                 return false;
             }
             $authorize = JFactory::getACL();
         } else {
             $authorize = JFactory::getUser();
             if (!($authorize->authorise('core.admin', 'com_virtuemart') or $authorize->authorise('core.manage', 'com_virtuemart')) and $usersConfig->get('allowUserRegistration') == '0') {
                 VmConfig::loadJLang('com_virtuemart');
                 vmError(vmText::_('COM_VIRTUEMART_ACCESS_FORBIDDEN'));
                 $data['virtuemart_user_id'] = 0;
                 unset($data['username']);
                 unset($data['password']);
                 unset($data['password2']);
                 $user = new JUser();
                 $userModel->_id = 0;
                 //$userModel->saveUserData($data);
                 $opc->userStoreAddress($userModel, $data);
                 return false;
             }
         }
         // 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();
         if (method_exists($date, 'toMySQL')) {
             $user->set('registerDate', $date->toMySQL());
         } else {
             $user->set('registerDate', $date->toSQL());
         }
         // If user activation is turned on, we need to set the activation information
         $useractivation = $usersConfig->get('useractivation');
         if (!empty($opc_no_activation)) {
             $useractivation = false;
         }
         $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');
             if (method_exists('JApplication', 'getHash')) {
                 $user->set('activation', JApplication::getHash(JUserHelper::genRandomPassword()));
             } else {
                 $user->set('activation', JUtility::getHash(JUserHelper::genRandomPassword()));
             }
             //$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 (method_exists($userModel, 'getSuperAdminCount')) {
             if ($userModel->getSuperAdminCount() <= 1) {
                 vmError(JText::_('COM_VIRTUEMART_USER_ERR_ONLYSUPERADMIN'));
                 return false;
             }
         }
     }
     if (isset($data['language'])) {
         $user->setParam('language', $data['language']);
     } else {
         if (isset($data['order_language'])) {
             $user->setParam('language', $data['order_language']);
         }
     }
     // Save the JUser object
     $regfail = false;
     if (!$user->save()) {
         vmError(JText::_($user->getError()), JText::_($user->getError()));
         $regfail = true;
     }
     //vmdebug('my user, why logged in? ',$user);
     if (!$regfail) {
         $newId = $user->get('id');
     } else {
         $newId = 0;
     }
     $data['virtuemart_user_id'] = $newId;
     //We need this in that case, because data is bound to table later
     $regid = $user->get('id');
     if (!empty($regid)) {
         $GLOBALS['opc_new_user'] = $user->get('id');
     } else {
         $GLOBALS['opc_new_user'] = $newId;
     }
     //$this->setUserId($newId);
     $userModel->_id = $newId;
     $userModel->_data = null;
     //Save the VM user stuff
     if (!empty($data['quite'])) {
         $msgqx1 = JFactory::getApplication()->get('messageQueue', array());
         $msgqx2 = JFactory::getApplication()->get('_messageQueue', array());
     }
     if (!empty($newId)) {
         include JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'config' . DS . 'onepage.cfg.php';
         if ($new || $allow_sg_update) {
             $userdata = $userModel->saveUserData($data);
             $groups = array();
             if (method_exists($userModel, 'getCurrentUser')) {
                 $user2 = $userModel->getCurrentUser();
                 $groups = $user2->shopper_groups;
             }
             $shoppergroupmodel = VmModel::getModel('ShopperGroup');
             $default = $shoppergroupmodel->getDefault(0);
             if (!empty($default)) {
                 $default_id = $default->virtuemart_shoppergroup_id;
             } else {
                 $default_id = 1;
             }
             $default1 = $shoppergroupmodel->getDefault(1);
             if (!empty($default1)) {
                 $default1 = $default1->virtuemart_shoppergroup_id;
             } else {
                 $default1 = 2;
             }
             require_once JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'helpers' . DS . 'shoppergroups.php';
             OPCShopperGroups::getSetShopperGroup(false);
             $session = JFactory::getSession();
             $ids = $session->get('vm_shoppergroups_add', array(), 'vm');
             if (!empty($groups)) {
                 $ids = array_merge($ids, $groups);
             }
             $remove = $session->get('vm_shoppergroups_remove', array(), 'vm');
             if (!empty($remove)) {
                 foreach ($remove as $sr) {
                     foreach ($ids as $key => $sg) {
                         if ($sg == $sr) {
                             unset($ids[$key]);
                         }
                     }
                 }
             }
             if (!empty($ids)) {
                 foreach ($ids as $key => $sg) {
                     if ($sg == $default) {
                         unset($ids[$key]);
                     }
                     if (empty($sg)) {
                         unset($ids[$key]);
                     }
                     if ($sg == $default1) {
                         unset($ids[$key]);
                     }
                 }
             }
             if (empty($data['virtuemart_shoppergroup_id']) or $data['virtuemart_shoppergroup_id'] == $default->virtuemart_shoppergroup_id) {
                 $data['virtuemart_shoppergroup_id'] = array();
             }
             if (!empty($ids)) {
                 $ids = array_unique($ids);
                 //stAn, opc 250: $data['virtuemart_shoppergroup_id'] = $sg;
                 $data['virtuemart_shoppergroup_id'] = $ids;
                 // Bind the form fields to the table
                 $db = JFactory::getDBO();
                 if (!empty($ids)) {
                     foreach ($ids as $ssg) {
                         $q = 'select * from #__virtuemart_vmuser_shoppergroups where virtuemart_user_id = ' . (int) $newId . ' and virtuemart_shoppergroup_id = ' . (int) $ssg . ' limit 0,1';
                         $db->setQuery($q);
                         $res = $db->loadAssocList();
                         if (empty($res)) {
                             $q = "insert into `#__virtuemart_vmuser_shoppergroups` (id, virtuemart_user_id, virtuemart_shoppergroup_id) values (NULL, " . (int) $newId . ", " . (int) $ssg . ")";
                             $db->setQuery($q);
                             $db->query();
                         }
                     }
                 }
             }
         }
     }
     //$userAddress = $userModel->storeAddress($data);
     $userAddress = $opc->userStoreAddress($userModel, $data);
     if (!empty($data['quite'])) {
         $x = JFactory::getApplication()->set('messageQueue', $msgqx1);
         $x = JFactory::getApplication()->set('_messageQueue', $msgqx2);
     }
     if (empty($userdata) || empty($userAddress)) {
         // we will not show the error because if we display only register fields, but an account field is marked as required, it still gives an error
         if (empty($data['quite'])) {
             vmError('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USER_DATA');
         }
         // 			vmError(Jtext::_('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USERINFO_DATA'));
     }
     if (!$regfail) {
         if ($new) {
             // make sure that VM has proper user:
             if (!empty($newId)) {
                 //JFactory::getUser()->load($newId);
                 if (!class_exists('VirtueMartViewUser')) {
                     require_once JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'overrides' . DS . 'virtuemart.user.registration.view.html.php';
                 }
                 OPCUser::sendRegistrationEmail($user, $user->password_clear, $doUserActivation, $data);
             }
             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');
             }
         }
     }
     //The extra check for isset vendor_name prevents storing of the vendor if there is no form (edit address cart)
     // stAn, let's not alter vendor
     /*
     if((int)$data['user_is_vendor']==1 and isset($data['vendor_name'])){
     	vmdebug('vendor recognised '.$data['virtuemart_vendor_id']);
     	if($userModel->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' => !$regfail);
 }
Ejemplo n.º 10
0
	public static function juserRegister($juser) {
		$result = array();
		$oseMscconfig = oseRegistry::call('msc')->getConfig('', 'obj');
		$config = JFactory::getConfig();
		$params = JComponentHelper::getParams('com_users');
		$newUserType = self::getNewUserType($params->get('new_usertype'));
		$juser['gid'] = $newUserType;
		$data = (array) self::getJuserData($juser);
		// Initialise the table with JUser.
		$user = new JUser;
		foreach ($juser as $k => $v) {
			$data[$k] = $v;
		}
		// Prepare the data for the user object.
		$useractivation = $params->get('useractivation');
		// Check if the user needs to activate their account.
		if (($useractivation == 1) || ($useractivation == 2)) {
			jimport('joomla.user.helper');
			$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
			$data['block'] = 1;
		}
		// Bind the data.
		if (!$user->bind($data)) {
			$result['success'] = false;
			$result['title'] = 'Error';
			$result['content'] = JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError());
		}
		// Load the users plugin group.
		JPluginHelper::importPlugin('user');
		if (!$user->save()) {
			$result['success'] = false;
			$result['title'] = 'Error';
			$result['reload'] = ($oseMscconfig->error_registration == 'refresh') ? true : false;
			;
			$result['content'] = JText::_($user->getError());
		} else {
			// Mark the user_id in order to user in payment form
			if (($useractivation == 1) || ($useractivation == 2)) {
				$session = JFactory::getSession();
				$oseUser = array();
				$oseUser['user_id'] = $user->id;
				$oseUser['block'] = true;
				$oseUser['activation'] = true;
				$session->set('ose_user', $oseUser);
			}
			$result['success'] = true;
			$result['user'] = $user;
			$result['title'] = 'Done';
			$result['content'] = 'Juser saved successfully';
			// Compile the notification mail values.
			$data = $user->getProperties();
			$data['fromname'] = $config->get('fromname');
			$data['mailfrom'] = $config->get('mailfrom');
			$data['sitename'] = $config->get('sitename');
			$data['siteurl'] = JUri::base();
			if (JOOMLA16 == true) {
				// Handle account activation/confirmation emails.
				if ($useractivation == 2) {
					// Set the link to confirm the user email.
					$uri = JURI::getInstance();
					$base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
					$data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
					$emailSubject = JText::sprintf('COM_USERS_OSEMSC_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
					$emailBody = JText::sprintf('COM_USERS_OSEMSC_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'],
							$data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'],
							$data['password_clear']);
				} else if ($useractivation == 1) {
					// Set the link to activate the user account.
					$uri = JURI::getInstance();
					$base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
					$data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
					$emailSubject = JText::sprintf('COM_USERS_OSEMSC_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
					$emailBody = JText::sprintf('COM_USERS_OSEMSC_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'],
							$data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'],
							$data['password_clear']);
				} else {
					$emailSubject = "";
					$emailBody = "";
				}
				// Send the registration email.
				if (!empty($emailSubject) && !empty($emailBody)) {
					if (JOOMLA30 == true) {
						$mailer = new JMail();
						$return = $mailer->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody);
					} else {
						$return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody);
					}
				} else {
					$return = true;
				}
				// Check for an error.
				if ($return !== true) {
					$this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'));
					// Send a system message to administrators receiving system mails
					$db = JFactory::getDBO();
					$q = "SELECT id
						FROM #__users
						WHERE block = 0
						AND sendEmail = 1";
					$db->setQuery($q);
					$sendEmail = $db->loadResultArray();
					if (count($sendEmail) > 0) {
						$jdate = new JDate();
						// Build the query to add the messages
						$q = "INSERT INTO `#__messages` (`user_id_from`, `user_id_to`, `date_time`, `subject`, `message`)
							VALUES ";
						$messages = array();
						foreach ($sendEmail as $userid) {
							$messages[] = "(" . $userid . ", " . $userid . ", '" . $jdate->toMySQL() . "', '" . JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT') . "', '"
									. JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']) . "')";
						}
						$q .= implode(',', $messages);
						$db->setQuery($q);
						$db->query();
					}
					//return false;
				}
				if ($useractivation == 1) {
					$result['user_active'] = "useractivate";
				} else if ($useractivation == 2) {
					$result['user_active'] = "adminactivate";
				} else {
					$result['user_active'] = null;
				}
			} else {
				$mainframe = JFactory::getApplication('SITE');
				if ($useractivation == 1) {
					$password = $data['password_clear'];
					$db = JFactory::getDBO();
					$name = $user->get('name');
					$email = $user->get('email');
					$username = $user->get('username');
					$usersConfig = &JComponentHelper::getParams('com_users');
					$sitename = $mainframe->getCfg('sitename');
					$useractivation = $usersConfig->get('useractivation');
					$mailfrom = $mainframe->getCfg('mailfrom');
					$fromname = $mainframe->getCfg('fromname');
					$siteURL = JURI::base();
					$subject = sprintf(JText::_('ACCOUNT_DETAILS_FOR'), $name, $sitename);
					$subject = html_entity_decode($subject, ENT_QUOTES);
					$message = sprintf(JText::_('SEND_MSG_ACTIVATE'), $name, $sitename, $siteURL . "index.php?option=com_user&task=activate&activation=" . $user->get('activation'),
							$siteURL, $username, $password);
					$message = html_entity_decode($message, ENT_QUOTES);
					//get all super administrator
					$query = 'SELECT name, email, sendEmail' . ' FROM #__users' . ' WHERE LOWER( usertype ) = "super administrator"';
					$db->setQuery($query);
					$rows = $db->loadObjectList();
					// Send email to user
					if (!$mailfrom || !$fromname) {
						$fromname = $rows[0]->name;
						$mailfrom = $rows[0]->email;
					}
					JUtility::sendMail($mailfrom, $fromname, $email, $subject, $message);
					// Send notification to all administrators
					$subject2 = sprintf(JText::_('ACCOUNT_DETAILS_FOR'), $name, $sitename);
					$subject2 = html_entity_decode($subject2, ENT_QUOTES);
					// get superadministrators id
					foreach ($rows as $row) {
						if ($row->sendEmail) {
							$message2 = sprintf(JText::_('SEND_MSG_ADMIN'), $row->name, $sitename, $name, $email, $username);
							$message2 = html_entity_decode($message2, ENT_QUOTES);
							JUtility::sendMail($mailfrom, $fromname, $row->email, $subject2, $message2);
						}
					}
				} else {
					$name = $user->get('name');
					$email = $user->get('email');
					$username = $user->get('username');
					$usersConfig = &JComponentHelper::getParams('com_users');
					$sitename = $mainframe->getCfg('sitename');
					$useractivation = $usersConfig->get('useractivation');
					$mailfrom = $mainframe->getCfg('mailfrom');
					$fromname = $mainframe->getCfg('fromname');
					$siteURL = JURI::base();
					$message = sprintf(JText::_('SEND_MSG'), $name, $sitename, $siteURL);
				}
			}
		}
		return $result;
	}
Ejemplo n.º 11
0
 /** Check to see if the user may access (see/download) the attachments
  * @param JUser $user : the current user object
  * @param int $id : The id of the attachment
  * @return true if access is okay (false if not)
  */
 function user_may_access_attachment($user, $id)
 {
     // NOTE: This implementation is pretty dumb...
     // Get the component parameters
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     $who_can_see = $params->get('who_can_see', 'logged_in');
     $logged_in = $user->get('username') != '';
     if ($who_can_see == 'anyone' || $who_can_see == 'logged_in' && $logged_in) {
         return true;
     }
     return false;
 }
Ejemplo n.º 12
0
function doUserLogIn($username)
{
    $my = new JUser();
    jimport('joomla.user.helper');
    if ($id = intval(JUserHelper::getUserId($username))) {
        $my->load($id);
    } else {
        return JError::raiseWarning('SOME_ERROR_CODE', 'MigrationAssistant (doUserLogIn): Failed to load user');
    }
    // If the user is blocked, redirect with an error
    if ($my->get('block') == 1) {
        return JError::raiseWarning('SOME_ERROR_CODE', JText::_('E_NOLOGIN_BLOCKED'));
    }
    //Mark the user as logged in
    $my->set('guest', 0);
    // Discover the access group identifier
    // NOTE : this is a very basic for of permission handling, will be replaced by a full ACL in 1.6
    jimport('joomla.factory');
    $acl =& JFactory::getACL();
    $grp = $acl->getAroGroup($my->get('id'));
    $my->set('aid', 1);
    if ($acl->is_group_child_of($grp->name, 'Registered', 'ARO') || $acl->is_group_child_of($grp->name, 'Public Backend', 'ARO')) {
        // fudge Authors, Editors, Publishers and Super Administrators into the special access group
        $my->set('aid', 2);
    }
    //Set the usertype based on the ACL group name
    $my->set('usertype', $grp->name);
    // Register the needed session variables
    $session =& JFactory::getSession();
    $session->set('user', $my);
    // Get the session object
    $table =& JTable::getInstance('session');
    $table->load($session->getId());
    $table->guest = $my->get('guest');
    $table->username = $my->get('username');
    $table->userid = intval($my->get('id'));
    $table->usertype = $my->get('usertype');
    $table->gid = intval($my->get('gid'));
    $table->update();
    // Hit the user last visit field
    $my->setLastVisit();
    // Set remember me option
    $lifetime = time() + 365 * 24 * 60 * 60;
    setcookie('usercookie[username]', $my->get('username'), $lifetime, '/');
    setcookie('usercookie[password]', $my->get('password'), $lifetime, '/');
}
Ejemplo n.º 13
0
 /**
  * Saves the record
  */
 function save()
 {
     global $mainframe;
     // Check for request forgeries
     JRequest::checkToken() or die('Invalid Token');
     #-Kobby edits this section
     #-Insert the user redirects urls over here
     #-User Detail for our Redirects
     $redirect_URL_FRONT = JRequest::getVar('redirect_URL_FRONT');
     $redirect_URL_ADMIN = JRequest::getVar('redirect_URL_ADMIN');
     $user = new JUser(JRequest::getVar('id', 0, 'post', 'int'));
     $option = JRequest::getCmd('option');
     // Initialize some variables
     $db =& JFactory::getDBO();
     $me =& JFactory::getUser();
     $acl =& JFactory::getACL();
     $MailFrom = $mainframe->getCfg('mailfrom');
     $FromName = $mainframe->getCfg('fromname');
     $SiteName = $mainframe->getCfg('sitename');
     // Create a new JUser object
     $user = new JUser(JRequest::getVar('id', 0, 'post', 'int'));
     $original_gid = $user->get('gid');
     $post = JRequest::get('post');
     $post['username'] = JRequest::getVar('username', '', 'post', 'username');
     $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
     if (!$user->bind($post)) {
         $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $mainframe->enqueueMessage($user->getError(), 'error');
         //$mainframe->redirect( 'index.php?option=com_users', $user->getError() );
         //return false;
         return $this->execute('edit');
     }
     $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO');
     $groups = $acl->get_object_groups($objectID, 'ARO');
     $this_group = strtolower($acl->get_group_name($groups[0], 'ARO'));
     if ($user->get('id') == $me->get('id') && $user->get('block') == 1) {
         $msg = JText::_('You cannot block Yourself!');
         $mainframe->enqueueMessage($msg, 'message');
         return $this->execute('edit');
     } else {
         if ($this_group == 'super administrator' && $user->get('block') == 1) {
             $msg = JText::_('You cannot block a Super Administrator');
             $mainframe->enqueueMessage($msg, 'message');
             return $this->execute('edit');
         } else {
             if ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) {
                 $msg = JText::_('WARNBLOCK');
                 $mainframe->enqueueMessage($msg, 'message');
                 return $this->execute('edit');
             } else {
                 if ($this_group == 'super administrator' && $me->get('gid') != 25) {
                     $msg = JText::_('You cannot edit a super administrator account');
                     $mainframe->enqueueMessage($msg, 'message');
                     return $this->execute('edit');
                 }
             }
         }
     }
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if (!$isNew) {
         // if group has been changed and where original group was a Super Admin
         if ($user->get('gid') != $original_gid && $original_gid == 25) {
             // count number of active super admins
             $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count <= 1) {
                 // disallow change if only one Super Admin exists
                 $this->setRedirect('index.php?option=com_community_acl&mode=manage_users', JText::_('WARN_ONLY_SUPER'));
                 return false;
             }
         }
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $mainframe->enqueueMessage($user->getError(), 'error');
         return $this->execute('edit');
     }
     /*
      * Time for the email magic so get ready to sprinkle the magic dust...
      */
     if ($isNew) {
         $adminEmail = $me->get('email');
         $adminName = $me->get('name');
         $subject = JText::_('NEW_USER_MESSAGE_SUBJECT');
         $message = sprintf(JText::_('NEW_USER_MESSAGE'), $user->get('name'), $SiteName, JURI::root(), $user->get('username'), $user->password_clear);
         if ($MailFrom != '' && $FromName != '') {
             $adminName = $FromName;
             $adminEmail = $MailFrom;
         }
         JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message);
     }
     // If updating self, load the new user object into the session
     if ($user->get('id') == $me->get('id')) {
         // Get an ACL object
         $acl =& JFactory::getACL();
         // Get the user group from the ACL
         $grp = $acl->getAroGroup($user->get('id'));
         // Mark the user as logged in
         $user->set('guest', 0);
         $user->set('aid', 1);
         // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
         if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
             $user->set('aid', 2);
         }
         // Set the usertype based on the ACL group name
         $user->set('usertype', $grp->name);
         $session =& JFactory::getSession();
         $session->set('user', $user);
     }
     $cacl_group_id = JRequest::getVar('cacl_group_id', array(), '', 'array');
     JArrayHelper::toInteger($cacl_group_id, array());
     $cacl_role_id = JRequest::getVar('cacl_role_id', array(), '', 'array');
     JArrayHelper::toInteger($cacl_role_id, array());
     $cacl_func_id = JRequest::getVar('cacl_func_id', array(), '', 'array');
     JArrayHelper::toInteger($cacl_func_id, array());
     $publisher_notification = (int) JRequest::getInt('publisher_notification');
     $query = "DELETE FROM `#__community_acl_user_params` WHERE `user_id` = '" . $user->get('id') . "' AND `name` = '" . $publisher_notification . "'";
     $db->setQuery($query);
     $db->query();
     $query = "INSERT INTO `#__community_acl_user_params` " . " SET `user_id` = '" . $user->get('id') . "', " . " `name` = 'publisher_notification', " . " `value` = '" . $publisher_notification . "' ";
     $db->setQuery($query);
     $db->query();
     $query = "DELETE FROM `#__community_acl_users` WHERE `user_id` = '" . $user->get('id') . "'";
     $db->setQuery($query);
     $db->query();
     if (is_array($cacl_group_id) && count($cacl_group_id)) {
         foreach ($cacl_group_id as $i => $v) {
             $cacl_usr = new CACL_user($db);
             $cacl_usr->user_id = $user->get('id');
             $cacl_usr->group_id = isset($cacl_group_id[$i]) ? $cacl_group_id[$i] : 0;
             $cacl_usr->role_id = isset($cacl_role_id[$i]) ? $cacl_role_id[$i] : 0;
             $cacl_usr->function_id = isset($cacl_func_id[$i]) ? $cacl_func_id[$i] : 0;
             $cacl_usr->redirect_FRONT = $redirect_URL_FRONT;
             $cacl_usr->redirect_ADMIN = $redirect_URL_ADMIN;
             $cacl_usr->store();
         }
     }
     $query = "SELECT `id` FROM  `#__community_acl_sites` WHERE `is_main` = '1'";
     $db->setQuery($query);
     $sid = (int) $db->loadResult();
     if ($sid > 0) {
         $main = new CACL_site($db);
         $main->load($sid);
         $config = new CACL_config($main->_site_db);
         $config->load();
         if ($config->synchronize && $config->users_and_cb) {
             $sync = new CACL_syncronize($main);
             $sync->syncronize($user->get('id'), 'user');
             $sync->syncronize($user->get('id'), 'cb_user');
         }
     }
     switch ($this->getTask()) {
         case 'apply':
             $msg = JText::sprintf('Successfully Saved changes to User', $user->get('name'));
             $this->setRedirect('index.php?option=com_community_acl&mode=manage_users&view=user&task=edit&cid[]=' . $user->get('id'), $msg);
             break;
         case 'save':
         default:
             $msg = JText::sprintf('Successfully Saved User', $user->get('name'));
             $this->setRedirect('index.php?option=com_community_acl&mode=manage_users', $msg);
             break;
     }
 }
  function onAfterInitialise() {
    $lrdata = array(); $user_id = ''; $id = ''; $email = ''; $msg = ''; $defaultUserGroups = ''; $lr_settings = array();
    $lr_settings = plgSystemSocialLoginTools::sociallogin_getsettings ();

	// Get module configration option value
	$mainframe = JFactory::getApplication();
	$db = JFactory::getDBO();
    $config = JFactory::getConfig();
    $language = JFactory::getLanguage();
	$session = JFactory::getSession();
	$language->load('com_users');
	$language->load('com_socialloginandsocialshare', JPATH_ADMINISTRATOR);
	$authorize = JFactory::getACL();
	$input = JFactory::getApplication()->input;
	$code = $input->get('code', null, 'STRING');
	$provider = $input->get('provider', null, 'STRING');
	// Checking user is logged in.
	if (isset($code) && !empty($code)) {
		if($provider=='google'){
			$userprofile = googlelogin::acsses_token($code, $lr_settings);
			$lrdata = googlelogin::userprofile_data($userprofile);
		}elseif($provider=='facebook'){
			$userprofile = facebooklogin::acsses_token($code, $lr_settings);
			$lrdata = facebooklogin::userprofile_data($userprofile);
		}
	}

	// User is not logged in trying to make log in user.
	if (isset($lrdata) && !empty($lrdata) && !JFactory::getUser()->id) {

	  // Remove the session if any.
	  if ($session->get('tmpuser')) {
	    $session->clear('tmpuser');
	  }
	  //$lrdata = plgSystemSocialLoginTools::facebook_userprofile_data($userprofile);
	  // Find the not activate user.
	   $query = "SELECT u.id FROM #__users AS u INNER JOIN #__LoginRadius_users AS lu ON lu.id = u.id WHERE lu.LoginRadius_id = '".$lrdata['id']."' AND u.activation != '' AND u.activation != 0";
	   $db->setQuery($query);
	   $block_id = $db->loadResult();
	   if (!empty($block_id) || $block_id) {
	     JError::raiseWarning ('', JText::_ ('COM_SOCIALLOGIN_USER_NOTACTIVATE'));
		 return false;
	   }  

	  // Find the block user.
	   $query = "SELECT u.id FROM #__users AS u INNER JOIN #__LoginRadius_users AS lu ON lu.id = u.id WHERE lu.LoginRadius_id = '".$lrdata['id']."' AND u.block = 1";
	   $db->setQuery($query);
	   $block_id = $db->loadResult();
	   if (!empty($block_id) || $block_id) {
	     JError::raiseWarning ('', JText::_ ('COM_SOCIALLOGIN_USER_BLOCK'));
		 return false;
	   }
	 }

	// Checking user click on popup cancel button.
	if (isset($lrdata['id']) && !empty($lrdata['id']) && !empty($lrdata['email'])) {
	  // Filter username form data.
	  if (!empty($lrdata['fname']) && !empty($lrdata['lname'])) {
	    $username = $lrdata['fname'].$lrdata['lname'];
	    $name = $lrdata['fname'];

	  }
	  else {
	    $username = plgSystemSocialLoginTools::get_filter_username($lrdata);
	    $name = plgSystemSocialLoginTools::get_filter_username($lrdata);
	  }
	 $query="SELECT u.id FROM #__users AS u INNER JOIN #__LoginRadius_users AS lu ON lu.id = u.id WHERE lu.LoginRadius_id = '".$lrdata['id']."'";
	 $db->setQuery($query);
	 $user_id = $db->loadResult();      

	  // If not then check for email exist.
	  if (empty($user_id)) {
        $query = "SELECT id FROM #__users WHERE email='".$lrdata['email']."'";
        $db->setQuery($query);
        $user_id = $db->loadResult(); 
		if (!empty($user_id)) {
		  $query = "SELECT LoginRadius_id from #__LoginRadius_users WHERE LoginRadius_id=".$db->Quote ($lrdata['id'])." AND id = " . $user_id;
          $db->setQuery($query);
          $check_id = $db->loadResult();
	      if (empty($check_id)) {

		    // Add new id to db.
		    $userImage = $lrdata['thumbnail'];
		    $sql = "INSERT INTO #__LoginRadius_users SET id = " . $user_id . ", LoginRadius_id = " . $db->Quote ($lrdata['id']).", provider = " . $db->Quote ($lrdata['Provider']) . ", lr_picture = " . $db->Quote ($userImage);
            $db->setQuery ($sql);
	        $db->execute();
		  }
		}
	  }
	  $newuser = true;
      if (isset($user_id)) {
	    $user = JFactory::getUser($user_id);
        if ($user->id == $user_id) {
          $newuser = false;
        }
	  }
	  if ($newuser == true) {
	  $user = new JUser;
	  $need_verification = false;
	  
		// If user registration is not allowed, show 403 not authorized.
	    $usersConfig = JComponentHelper::getParams( 'com_users' );
        if ($usersConfig->get('allowUserRegistration') == '0') {
          JError::raiseWarning( '', JText::_( 'COM_SOCIALLOGIN_REGISTER_DISABLED'));
          return false;
        }

		// Default to Registered.
        $defaultUserGroups = $usersConfig->get('new_usertype', 2);
	    if (empty($defaultUserGroups)) {
          $defaultUserGroups = 'Registered';
        }

		// if username already exists
        $username = plgSystemSocialLoginTools::get_exist_username($username);

		// Remove special char if have.
		$username = plgSystemSocialLoginTools::remove_unescapedChar($username);
	    $name = plgSystemSocialLoginTools::remove_unescapedChar($name);

		//Insert data 
		jimport ('joomla.user.helper');
	    $userdata = array ();
	    $userdata ['name'] = $db->escape($name);
        $userdata ['username'] = $db->escape($username);
        $userdata ['email'] = $lrdata['email'];
        $userdata ['usertype'] = 'deprecated';
        $userdata ['groups'] = array($defaultUserGroups);
        $userdata ['registerDate'] = JFactory::getDate ()->toSql ();
        $userdata ['password'] = JUserHelper::genRandomPassword ();
        $userdata ['password2'] = $userdata ['password'];
		$useractivation = $usersConfig->get( 'useractivation' );
		if (isset($_POST['sociallogin_emailclick']) AND $useractivation != '2') {
            $need_verification = true;
		}
		if ($useractivation == '2' OR $need_verification == true) {
		  $userdata ['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
		  $userdata ['block'] = 1;
		}
		else {
		  $userdata ['activation'] = '';
		  $userdata ['block'] = 0;
		}
		if (!$user->bind ($userdata)) {
          JError::raiseWarning ('', JText::_ ('COM_USERS_REGISTRATION_BIND_FAILED'));
          return false;
        }

		//Save the user
        if (!$user->save()) {
          JError::raiseWarning ('', JText::_ ('COM_SOCIALLOGIN_REGISTER_FAILED'));
          return false;
        }
        $user_id = $user->get ('id');

		// Saving user extra profile.
       //plgSystemSocialLoginTools::save_userprofile_data($user_id, $lrdata);
	  // Trying to insert image.
		$userImage = $lrdata['thumbnail'];
		
        // Remove.
        $sql = "DELETE FROM #__LoginRadius_users WHERE LoginRadius_id = " . $db->Quote ($lrdata['id']);
        $db->setQuery ($sql);
        if ($db->execute()) {

		  //Add new id to db
          $sql = "INSERT INTO #__LoginRadius_users SET id = " . $db->quote ($user_id) . ",  LoginRadius_id = " . $db->Quote ($lrdata['id']).", provider = " . $db->Quote ($lrdata['Provider']).", lr_picture = " . $db->Quote ($userImage);
          $db->setQuery ($sql);
          $db->execute();
	    }   
		
		
		 // Handle account activation/confirmation emails.
		 if ($useractivation == '2' OR $need_verification == true) {
           if ($need_verification == true) {
		     $usermessgae = 3;
             $this->_sendMail($user, $usermessgae);
             $mainframe->enqueueMessage(JText::_ ('COM_USERS_REGISTRATION_COMPLETE_ACTIVATE'));
			 $session->clear('tmpuser');
             return false;
		   }
           else {
		   $usermessgae = 1;
		   $this->_sendMail($user, $usermessgae);
		   $mainframe->enqueueMessage(JText::_ ('COM_USERS_REGISTRATION_COMPLETE_VERIFY'));
           $session->clear('tmpuser');
		   return false;
		 }
	   }
	   else {
 	     $usermessgae = 2;
		 $this->_sendMail($user, $usermessgae);
       }
	   
     }
}
   if ($user_id) {
     $user = JUser::getInstance((int)$user_id);	 
	 
	  //Register session variables
	  $session = JFactory::getSession();
	  $query = "SELECT lr_picture from #__LoginRadius_users WHERE LoginRadius_id=".$db->Quote ($lrdata['id'])." AND id = " . $user->get('id');
	  $db->setQuery($query);
	  $check_picture = $db->loadResult();
	  $session->set('user_picture',$check_picture);
	  $session->set('user_lrid',$lrdata['id']);
	  $session->set('user',$user);
	  
	  // Getting the session object
	  $table =  JTable::getInstance('session');
	  $table->load( $session->getId());
	  $table->guest = '0';
	  $table->username = $user->get('username');
	  $table->userid = intval($user->get('id'));
	  $table->usertype = $user->get('usertype');
	  $table->gid  = $user->get('gid');
	  $table->update();
	  $user->setLastVisit();
	  $user = JFactory::getUser();
	  
	  //Redirect after Login
	  $session->clear('tmpuser');	 
	  ?>
      <script>
	  if (window.opener) {
		  window.opener.location.href='<?php echo JURI::root(); ?>';
		  window.close();
	  }
      </script>
      
      <?php
	 
	  
	}
  }
Ejemplo n.º 15
0
 public function register($temp, $configuration = array())
 {
     $config = JFactory::getConfig();
     $params = JComponentHelper::getParams('com_users');
     ## Initialise the table with JUser.
     $user = new JUser();
     $data = (array) $this->getUserData();
     ## Merge in the registration data.
     foreach ($temp as $k => $v) {
         $data[$k] = $v;
     }
     ## If we want autologin this is needed.
     $userlogin['username'] = $data[username];
     $userlogin['password'] = $data[password];
     $useractivation = $params->get('useractivation');
     ## Check if the user needs to activate their account.
     if ($useractivation == 1 || $useractivation == 2) {
         jimport('joomla.user.helper');
         $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
         $data['block'] = 1;
         $db = JFactory::getDBO();
         $sql = "SELECT activation_email, companyname \n\t\t\t\t\tFROM #__ticketmaster_config \n\t\t\t\t\tWHERE configid = 1";
         $db->setQuery($sql);
         $configuration = $db->loadObject();
         ## We need to send an email to let the user activate their account.
         ## Getting the desired info from the configuration table
         $sql = "SELECT * FROM #__ticketmaster_emails WHERE emailid = " . (int) $configuration->activation_email . "";
         $db->setQuery($sql);
         $config = $db->loadObject();
         $actvivation = JURI::base() . 'index.php?option=com_ticketmaster&controller=checkout&task=activate&token=' . $data['activation'];
         $message = str_replace('%%ACTIVATION_CODE%%', $actvivation, $config->mailbody);
         $message = str_replace('%%NAME%%', $data['name'], $message);
         $message = str_replace('%%FIRSTNAME%%', $data['firstname'], $message);
         $message = str_replace('%%COMPANY%%', $configuration->companyname, $message);
         $message = str_replace('%%EMAIL%%', $data['email'], $message);
         $message = str_replace('%%USERNAME%%', $userlogin['username'], $message);
         $message = str_replace('%%PASSWORD%%', $userlogin['password'], $message);
         $message = str_replace('%%CODE_ONLY%%', $data['activation'], $message);
         ## Imaport mail functions:
         jimport('joomla.mail.mail');
         ## Set the sender of the email:
         $sender[0] = $config->from_email;
         $sender[1] = $config->from_name;
         ## Compile mailer function:
         $obj = JFactory::getMailer();
         $obj->setSender($sender);
         $obj->isHTML(true);
         $obj->setBody($message);
         $obj->addRecipient($data['email']);
         ## Send blind copy to site admin?
         if ($config->receive_bcc == 1) {
             if ($config->reply_to_email != '') {
                 $obj->addRecipient($mail->reply_to_email);
             }
         }
         ## Add reply to and subject:
         $obj->addReplyTo($config->reply_to_email);
         $obj->setSubject($config->mailsubject);
         if ($config->published == 1) {
             $sent = $obj->Send();
         }
     } else {
         $data['activation'] = '';
         $data['block'] = 0;
     }
     ## Bind the data.
     if (!$user->bind($data)) {
         $this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
         return false;
     }
     ## Load the users plugin group.
     JPluginHelper::importPlugin('user');
     ## Store the data.
     $user->save();
     ## getting the userid.
     $userid = $user->get('id');
     return $userid;
 }
Ejemplo n.º 16
0
 public function storeUser_bk($post)
 {
     $app = JFactory::getApplication();
     $redshopMail = new redshopMail();
     // Start data into user table
     // Initialize some variables
     $db = JFactory::getDbo();
     $me = JFactory::getUser();
     $acl = JFactory::getACL();
     // Create a new JUser object
     $user = new JUser($post['id']);
     $original_gid = $user->get('gid');
     $post['name'] = isset($post['name']) ? $post['name'] : $post['username'];
     // Changed for shipping code moved out of condition
     if (!$user->bind($post)) {
         $app->enqueueMessage(JText::_('COM_REDSHOP_CANNOT_SAVE_THE_USER_INFORMATION'), 'message');
         $app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO');
     $groups = $acl->get_object_groups($objectID, 'ARO');
     $this_group = strtolower($acl->get_group_name($groups[0], 'ARO'));
     if ($user->get('id') == $me->get('id') && $user->get('block') == 1) {
         $msg = JText::_('COM_REDSHOP_YOU_CANNOT_BLOCK_YOURSELF');
         $app->enqueueMessage($msg, 'message');
         return false;
     } elseif ($this_group == 'super administrator' && $user->get('block') == 1) {
         $msg = JText::_('COM_REDSHOP_YOU_CANNOT_BLOCK_A_SUPER_ADMINISTRATOR');
         $app->enqueueMessage($msg, 'message');
         return false;
     } elseif ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) {
         $msg = JText::_('COM_REDSHOP_WARNBLOCK');
         $app->enqueueMessage($msg, 'message');
         return false;
     } elseif ($this_group == 'super administrator' && $me->get('gid') != 25) {
         $msg = JText::_('COM_REDSHOP_YOU_CANNOT_EDIT_A_SUPER_ADMINISTRATOR_ACCOUNT');
         $app->enqueueMessage($msg, 'message');
         return false;
     }
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if (!$isNew) {
         // If group has been changed and where original group was a Super Admin
         if ($user->get('gid') != $original_gid && $original_gid == 25) {
             // Count number of active super admins
             $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count <= 1) {
                 // Disallow change if only one Super Admin exists
                 $this->setRedirect('index.php?option=' . $option . '&view=user', JText::_('COM_REDSHOP_WARN_ONLY_SUPER'));
                 return false;
             }
         }
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         $app->enqueueMessage(JText::_('COM_REDSHOP_CANNOT_SAVE_THE_USER_INFORMATION'), 'message');
         $app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     /*
      * Time for the email magic so get ready to sprinkle the magic dust...
      */
     if ($isNew) {
         $redshopMail->sendRegistrationMail($post);
     }
     // If updating self, load the new user object into the session
     if ($user->get('id') == $me->get('id')) {
         // Get an ACL object
         $acl = JFactory::getACL();
         // Get the user group from the ACL
         $grp = $acl->getAroGroup($user->get('id'));
         // Mark the user as logged in
         $user->set('guest', 0);
         $user->set('aid', 1);
         // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
         if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
             $user->set('aid', 2);
         }
         // Set the usertype based on the ACL group name
         $user->set('usertype', $grp->name);
         $session = JFactory::getSession();
         $session->set('user', $user);
     }
     // End data into user table
     return $user;
 }
Ejemplo n.º 17
0
 /**
  * process the plugin, called when form is submitted
  *
  * @param	object	$params
  * @param	object	form model
  */
 function onBeforeStore(&$params, &$formModel)
 {
     $app = JFactory::getApplication();
     $config = JFactory::getConfig();
     $lang = JFactory::getLanguage();
     //load up com_users lang - used in email text
     $lang->load('com_users');
     //if the fabrik table is set to be jos_users and the this plugin is used
     //we need to alter the form model to tell it not to store the main row
     // but to still store any joined rows
     $ftable = str_replace('#__', $app->getCfg('dbprefix'), $formModel->getlistModel()->getTable()->db_table_name);
     $jos_users = $app->getCfg('dbprefix') . 'users';
     if ($ftable == $jos_users) {
         $formModel->_storeMainRow = false;
     }
     $usersConfig = JComponentHelper::getParams('com_users');
     // Initialize some variables
     $me = JFactory::getUser();
     $acl = JFactory::getACL();
     //$mailFrom = $app->getCfg('mailfrom');
     //$FromName = $app->getCfg('fromname');
     //$SiteName = $app->getCfg('sitename');
     $siteURL = JURI::base();
     $bypassActivation = $params->get('juser_bypass_activation', false);
     $bypassRegistration = $params->get('juser_bypass_registration', true);
     // load in the com_user language file
     $lang = JFactory::getLanguage();
     $lang->load('com_user');
     $data = $formModel->_formData;
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $option = JRequest::getCmd('option');
     $original_id = 0;
     if ($params->get('juser_field_userid') != '') {
         $this->useridfield = $this->getFieldName($params, 'juser_field_userid');
         if (!empty($formModel->_rowId)) {
             $original_id = (int) $formModel->_formData[$this->useridfield];
         }
     } else {
         $original_id = 0;
         $this->useridfield = '';
     }
     // Create a new JUser object
     $user = new JUser($original_id);
     $originalGroups = $user->getAuthorisedGroups();
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if ($isNew && $usersConfig->get('allowUserRegistration') == '0' && !$bypassRegistration) {
         JError::raiseError(403, JText::_('Access Forbidden - Registration not enabled'));
         return false;
     }
     $data = array();
     $this->passwordfield = $this->getFieldName($params, 'juser_field_password');
     $this->passwordvalue = $this->getFieldValue($params, 'juser_field_password', $formModel->_formData);
     $this->namefield = $this->getFieldName($params, 'juser_field_name');
     $this->namevalue = $this->getFieldValue($params, 'juser_field_name', $formModel->_formData);
     $this->usernamefield = $this->getFieldName($params, 'juser_field_username');
     $this->usernamevalue = $this->getFieldValue($params, 'juser_field_username', $formModel->_formData);
     $this->emailfield = $this->getFieldName($params, 'juser_field_email');
     $this->emailvalue = $this->getFieldValue($params, 'juser_field_email', $formModel->_formData);
     $data['id'] = $original_id;
     $this->gidfield = $this->getFieldName($params, 'juser_field_usertype');
     $defaultGroup = (int) $params->get('juser_field_default_group');
     $groupId = JArrayHelper::getValue($formModel->_formData, $this->gidfield, $defaultGroup);
     if (is_array($groupId)) {
         $groupId = $groupId[0];
     }
     $groupId = (int) $groupId;
     if (!$isNew) {
         if ($params->get('juser_field_usertype') != '') {
             if (in_array($groupId, $me->getAuthorisedGroups()) || $me->authorise('core.admin')) {
                 $data['gid'] = $groupId;
             } else {
                 JError::raiseNotice(500, "could not alter user group to {$groupId} as you are not assigned to that group");
             }
         } else {
             // if editing an existing user and no gid field being used,
             // use default group id
             $data['gid'] = $defaultGroup;
         }
     } else {
         $data['gid'] = $params->get('juser_field_usertype') != '' ? $groupId : $defaultGroup;
     }
     if ($data['gid'] === 0) {
         $data['gid'] = $defaultGroup;
     }
     $user->groups = (array) $data['gid'];
     if ($params->get('juser_field_block') != '') {
         $this->blockfield = $this->getFieldName($params, 'juser_field_block');
         $blocked = JArrayHelper::getValue($formModel->_formData, $this->blockfield, '');
         if (is_array($blocked)) {
             // probably a dropdown
             $data['block'] = (int) $blocked[0];
         } else {
             $data['block'] = (int) $blocked;
         }
     } else {
         $data['block'] = 0;
     }
     //$$$tom get password field to use in $origdata object if editing user and not changing password
     $origdata = $formModel->_origData;
     $pwfield = $this->passwordfield;
     $data['username'] = $this->usernamevalue;
     $data['password'] = $this->passwordvalue;
     $data['password2'] = $this->passwordvalue;
     $data['name'] = $this->namevalue;
     $name = $this->namevalue;
     $data['email'] = $this->emailvalue;
     $ok = $this->check($data, $formModel, $params);
     if (!$ok) {
         // @TODO - add some error reporting
         return false;
     }
     // Set the registration timestamp
     if ($isNew) {
         $now = JFactory::getDate();
         $user->set('registerDate', $now->toSql());
     }
     if ($isNew) {
         // If user activation is turned on, we need to set the activation information
         $useractivation = $usersConfig->get('useractivation');
         if ($useractivation == '1' && !$bypassActivation) {
             jimport('joomla.user.helper');
             $data['activation'] = JUtility::getHash(JUserHelper::genRandomPassword());
             $data['block'] = 1;
         }
     }
     // Check that username is not greater than 150 characters
     $username = $data['username'];
     if (strlen($username) > 150) {
         $username = substr($username, 0, 150);
         $user->set('username', $username);
     }
     // Check that password is not greater than 100 characters
     if (strlen($data['password']) > 100) {
         $data['password'] = substr($data['password'], 0, 100);
     }
     // end new
     if (!$user->bind($data)) {
         $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     $session = JFactory::getSession();
     JRequest::setVar('newuserid', $user->id);
     JRequest::setVar('newuserid', $user->id, 'cookie');
     $session->set('newuserid', $user->id);
     JRequest::setVar('newuserid_element', $this->useridfield);
     JRequest::setVar('newuserid_element', $this->useridfield, 'cookie');
     $session->set('newuserid_element', $this->useridfield);
     /*
      * Time for the email magic so get ready to sprinkle the magic dust...
      */
     $emailSubject = '';
     if ($isNew) {
         // Compile the notification mail values.
         $data = $user->getProperties();
         $data['fromname'] = $config->get('fromname');
         $data['mailfrom'] = $config->get('mailfrom');
         $data['sitename'] = $config->get('sitename');
         $data['siteurl'] = JUri::base();
         $uri = JURI::getInstance();
         $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
         // Handle account activation/confirmation emails.
         if ($useractivation == 2 && !$bypassActivation) {
             // Set the link to confirm the user email.
             $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
             $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
             $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']);
         } else {
             if ($useractivation == 1 && !$bypassActivation) {
                 // Set the link to activate the user account.
                 $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
                 $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
                 $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']);
             } elseif ($params->get('juser_bypass_accountdetails') != 1) {
                 $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
                 $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl']);
             }
         }
         // Send the registration email.
         if ($emailSubject !== '') {
             $return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody);
             // Check for an error.
             if ($return !== true) {
                 $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'));
                 // Send a system message to administrators receiving system mails
                 $db = JFactory::getDBO();
                 $q = "SELECT id\n\t\t\t\t\t\t\t\tFROM #__users\n\t\t\t\t\t\t\t\tWHERE block = 0\n\t\t\t\t\t\t\t\tAND sendEmail = 1";
                 $db->setQuery($q);
                 $sendEmail = $db->loadColumn();
                 if (count($sendEmail) > 0) {
                     $jdate = new JDate();
                     // Build the query to add the messages
                     $q = "INSERT INTO `#__messages` (`user_id_from`, `user_id_to`, `date_time`, `subject`, `message`)\n\t\t\t\t\t\t\t\t\tVALUES ";
                     $messages = array();
                     foreach ($sendEmail as $userid) {
                         $messages[] = "(" . $userid . ", " . $userid . ", '" . $jdate->toSql() . "', '" . JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT') . "', '" . JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']) . "')";
                     }
                     $q .= implode(',', $messages);
                     $db->setQuery($q);
                     $db->query();
                 }
             }
         }
     }
     // If updating self, load the new user object into the session
     // FIXME - doesnt work in J1.7??
     /* if ($user->get('id') == $me->get('id'))
     		{
     			// Get an ACL object
     			$acl = &JFactory::getACL();
     
     			// Get the user group from the ACL
     			$grp = $acl->getAroGroup($user->get('id'));
     
     			// Mark the user as logged in
     			$user->set('guest', 0);
     			$user->set('aid', 1);
     
     			// Fudge Authors, Editors, Publishers and Super Administrators into the special access group
     			if ($acl->is_group_child_of($grp->name, 'Registered')      ||
     			$acl->is_group_child_of($grp->name, 'Public Backend'))    {
     				$user->set('aid', 2);
     			}
     
     			// Set the usertype based on the ACL group name
     			$user->set('usertype', $grp->name);
     			$session->set('user', $user);
     		} */
     if (!empty($this->useridfield)) {
         $formModel->updateFormData($this->useridfield, $user->get('id'), true);
     }
     if ($ftable == $jos_users) {
         $formModel->_rowId = $user->get('id');
     }
 }
Ejemplo n.º 18
0
 /**
  * Before the record is stored, this plugin will see if it should process
  * and if so store the form data in the session.
  *
  * NOTE: if your Fabrik list saves directly to #__users then you CAN NOT add additonal fields to the list,
  * instead add to a joined list to contain 'profile' information.
  *
  * @return  bool  should the form model continue to save
  */
 public function onBeforeStore()
 {
     $formModel = $this->getModel();
     $params = $this->getParams();
     $input = $this->app->input;
     $mail = JFactory::getMailer();
     $mail->isHtml(true);
     // Load up com_users lang - used in email text
     $this->lang->load('com_users', JPATH_SITE);
     /*
      * If the fabrik table is set to be #__users and the this plugin is used
      * we need to alter the form model to tell it not to store the main row
      * but to still store any joined rows
      */
     $prefix = $this->config->get('dbprefix');
     $ftable = str_replace('#__', $prefix, $formModel->getlistModel()->getTable()->db_table_name);
     $jos_users = $prefix . 'users';
     if ($ftable == $jos_users) {
         $formModel->storeMainRow = false;
     }
     // Needed for shouldProcess...
     $this->data = $this->getProcessData();
     if (!$this->shouldProcess('juser_conditon', null, $params)) {
         return true;
     }
     $usersConfig = JComponentHelper::getParams('com_users');
     $userActivation = $usersConfig->get('useractivation');
     $sendpassword = $usersConfig->get('sendpassword', 1);
     // Initialize some variables
     $me = $this->user;
     $bypassActivation = $params->get('juser_bypass_activation', false);
     $bypassRegistration = $params->get('juser_bypass_registration', true);
     $autoLogin = $params->get('juser_auto_login', false);
     $data = $formModel->formData;
     // Check for request forgeries
     JSession::checkToken() or jexit('Invalid Token');
     $originalId = 0;
     if ($params->get('juser_field_userid') != '') {
         $this->useridfield = $this->getFieldName('juser_field_userid');
         /*
          * This test would cause a fail if you were editing a record which contained the user data in a join
          * E.g. Fabrikar.com/subscribe - user logged in but adding a new subscription
          * $$$ hugh - AOOOOGA!  Removing the rowId test means that when an admin creates a new
          * user when logged in, the admin's row in #__users will get overwritten with the new user
          * details, because the user element has set itself to the currently logged in ID.
          * Going to try looking at orig data instead, don't know if that'll cause the issue outlined above
          * but have to do SOMETHING to fix this issue.
          */
         // if (!empty($formModel->rowId))
         // {
         if ($formModel->origDataIsEmpty()) {
             $originalId = 0;
         } else {
             $originalId = $formModel->formData[$this->useridfield];
             // $$$ hugh - if it's a user element, it'll be an array
             if (is_array($originalId)) {
                 $originalId = FArrayHelper::getValue($originalId, 0, 0);
             }
         }
         // }
     } else {
         $originalId = 0;
         $this->useridfield = '';
     }
     // Create a new JUser object
     $user = new JUser($originalId);
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if ($isNew && $usersConfig->get('allowUserRegistration') == '0' && !$bypassRegistration) {
         throw new RuntimeException(FText::_('Access Forbidden - Registration not enabled'), 400);
         return false;
     }
     $data = array();
     $this->passwordfield = $this->getFieldName('juser_field_password');
     $this->passwordvalue = $this->getFieldValue('juser_field_password', $formModel->formData);
     $this->namefield = $this->getFieldName('juser_field_name');
     $this->namevalue = $this->getFieldValue('juser_field_name', $formModel->formData);
     $this->usernamefield = $this->getFieldName('juser_field_username');
     $this->usernamevalue = $this->getFieldValue('juser_field_username', $formModel->formData);
     $this->emailfield = $this->getFieldName('juser_field_email');
     $this->emailvalue = $this->getFieldValue('juser_field_email', $formModel->formData);
     $data['id'] = $originalId;
     $data['gid'] = $this->setGroupIds($me, $user);
     $user->groups = (array) $data['gid'];
     if ($params->get('juser_field_block') != '') {
         $this->blockfield = $this->getFieldName('juser_field_block');
         $blocked = FArrayHelper::getValue($formModel->formData, $this->blockfield, '');
         if (is_array($blocked)) {
             // Probably a dropdown
             $data['block'] = (int) $blocked[0];
         } else {
             $data['block'] = (int) $blocked;
         }
     } else {
         $data['block'] = 0;
     }
     $data['username'] = $this->usernamevalue;
     $data['password'] = $this->passwordvalue;
     $data['password2'] = $this->passwordvalue;
     $data['name'] = $this->namevalue;
     $data['email'] = $this->emailvalue;
     $ok = $this->check($data);
     if (!$ok) {
         // @TODO - add some error reporting
         return false;
     }
     if ($isNew) {
         // Set the registration timestamp
         $user->set('registerDate', $this->date->toSql());
         $this->setActivation($data);
     }
     $this->trimNamePassword($user, $data);
     // End new
     if (!$user->bind($data)) {
         $this->app->enqueueMessage(FText::_('CANNOT BIND THE USER INFORMATION'), 'message');
         $this->app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     // Lets save the JUser object
     if (!$user->save()) {
         $this->app->enqueueMessage(FText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $this->app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     $input->set('newuserid', $user->id);
     $input->cookie->set('newuserid', $user->id);
     $this->session->set('newuserid', $user->id);
     $input->set('newuserid_element', $this->useridfield);
     $input->cookie->set('newuserid_element', $this->useridfield);
     $this->session->set('newuserid_element', $this->useridfield);
     /*
      * Time for the email magic so get ready to sprinkle the magic dust...
      */
     if ($params->get('juser_use_email_plugin') != 1) {
         $emailSubject = '';
         if ($isNew) {
             // Compile the notification mail values.
             $data = $user->getProperties();
             $data['fromname'] = $this->config->get('fromname');
             $data['mailfrom'] = $this->config->get('mailfrom');
             $data['sitename'] = $this->config->get('sitename');
             $data['siteurl'] = JUri::base();
             $uri = JURI::getInstance();
             $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
             // Handle account activation/confirmation emails.
             if ($userActivation == 2 && !$bypassActivation && !$autoLogin) {
                 // Set the link to confirm the user email.
                 $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
                 $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
                 if ($sendpassword) {
                     $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']);
                 } else {
                     $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username']);
                 }
             } elseif ($userActivation == 1 && !$bypassActivation && !$autoLogin) {
                 // Set the link to activate the user account.
                 $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
                 $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
                 if ($sendpassword) {
                     $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']);
                 } else {
                     $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username']);
                 }
             } elseif ($autoLogin) {
                 $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
                 if ($sendpassword) {
                     $emailBody = JText::sprintf('PLG_FABRIK_FORM_JUSER_AUTO_LOGIN_BODY', $data['name'], $data['sitename'], $data['siteurl'], $data['username'], $data['password_clear']);
                 } else {
                     $emailBody = JText::sprintf('PLG_FABRIK_FORM_JUSER_AUTO_LOGIN_BODY', $data['name'], $data['sitename'], $data['siteurl'], $data['username'], 'xxxxxxxxxxxx');
                 }
             } elseif ($params->get('juser_bypass_accountdetails') != 1) {
                 $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
                 if ($sendpassword) {
                     $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl'], $data['username'], $data['password_clear']);
                 } else {
                     $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY_NOPW', $data['name'], $data['sitename'], $data['siteurl']);
                 }
             }
             // Send the registration email.
             if ($emailSubject !== '') {
                 $return = $mail->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody);
                 /*
                  * Added email to admin code, but haven't had a chance to test it yet.
                  */
                 // $this->emailToAdmin($data);
                 // Check for an error.
                 if ($return !== true) {
                     $this->reportFailedMail($data);
                 }
             }
         }
     }
     // If updating self, load the new user object into the session
     /* @FIXME - doesnt work in J1.7??
      * if ($user->get('id') == $me->get('id'))
      * {
      * $acl = &JFactory::getACL();
      *
      * $grp = $acl->getAroGroup($user->get('id'));
      *
      * $user->set('guest', 0);
      * $user->set('aid', 1);
      *
      * if ($acl->is_group_child_of($grp->name, 'Registered')      ||
      * $acl->is_group_child_of($grp->name, 'Public Backend'))    {
      * $user->set('aid', 2);
      * }
      *
      * $user->set('usertype', $grp->name);
      * $session->set('user', $user);
      * } */
     if (!empty($this->useridfield)) {
         $formModel->updateFormData($this->useridfield, $user->get('id'), true, true);
     }
     if ($ftable == $jos_users) {
         $formModel->rowId = $user->get('id');
     }
     return true;
 }
Ejemplo n.º 19
0
 function saveUser($auth_info)
 {
     // process the auth_info response
     if ($auth_info['stat'] == 'ok') {
         $db =& JFactory::getDBO();
         $rpxid = 'rpx' . md5($auth_info['profile']['identifier']);
         $query = "SELECT userid FROM #__rpx_mapping WHERE rpxid='" . $rpxid . "'";
         $db->setQuery($query);
         $userid = $db->loadResult();
         $newuser = true;
         if (isset($userid)) {
             $user =& JFactory::getUser($userid);
             if ($user->id == $userid) {
                 $newuser = false;
             } else {
                 // possible if previous registered, but meanwhile removed
                 // we have a userid without user...remove from the rpx_mapping
                 $query = "DELETE FROM #__rpx_mapping WHERE userid='" . $userid . "'";
                 $db->setQuery($query);
                 $db->query();
             }
         }
         if ($newuser == true) {
             // save the user
             $user = new JUser();
             $authorize =& JFactory::getACL();
             $newUsertype = 'Registered';
             $user->set('id', 0);
             $user->set('usertype', '');
             $user->set('gid', $authorize->get_group_id('', $newUsertype, 'ARO'));
             $date =& JFactory::getDate();
             $user->set('registerDate', $date->toMySQL());
             if (isset($auth_info['profile']['displayName'])) {
                 $displayName = $auth_info['profile']['displayName'];
             } else {
                 if (isset($auth_info['profile']['name']['displayName'])) {
                     $displayName = $auth_info['profile']['name']['displayName'];
                 }
             }
             if (isset($auth_info['profile']['preferredUsername'])) {
                 $preferredUsername = $auth_info['profile']['preferredUsername'];
             } else {
                 if (isset($auth_info['profile']['name']['preferredUsername'])) {
                     $preferredUsername = $auth_info['profile']['name']['preferredUsername'];
                 }
             }
             $user->set('name', $displayName);
             // if username already exists, just add an index to it
             $nameexists = true;
             $index = 0;
             $userName = $preferredUsername;
             while ($nameexists == true) {
                 if (JUserHelper::getUserId($userName) != 0) {
                     $index++;
                     $userName = $preferredUsername . $index;
                 } else {
                     $nameexists = false;
                 }
             }
             $user->set('username', $userName);
             $host = JFactory::getURI()->getHost();
             $domain = substr($host, 4);
             // strips the www.
             if ($this->params->get('fakemail') == 0) {
                 if (isset($auth_info['profile']['email'])) {
                     $user->set('email', $auth_info['profile']['email']);
                 } else {
                     if (isset($auth_info['profile']['name']['email'])) {
                         $user->set('email', $auth_info['profile']['email']);
                     } else {
                         $user->set('email', str_replace(" ", "_", $userName) . "@" . $domain);
                     }
                 }
             } else {
                 $user->set('email', str_replace(" ", "_", $userName) . "@" . $domain);
             }
             $pwd = JUserHelper::genRandomPassword();
             $user->set('password', $pwd);
             if (!$user->save()) {
                 echo "ERROR: ";
                 echo $user->getError();
             } else {
                 $query = "INSERT INTO #__rpx_mapping (userid, rpxid) VALUES ('" . $user->get('id') . "','" . $rpxid . "')";
                 $db->setQuery($query);
                 if (!$db->query()) {
                     JERROR::raiseError(500, $db->stderror());
                 }
             }
             // check if the community builder tables are there
             $query = "SHOW TABLES LIKE '%__comprofiler'";
             $db->setQuery($query);
             $tableexists = $db->loadResult();
             if (isset($tableexists)) {
                 $cbquery = "INSERT IGNORE INTO #__comprofiler(id,user_id) VALUES ('" . $user->get('id') . "','" . $user->get('id') . "')";
                 $db->setQuery($cbquery);
                 if (!$db->query()) {
                     JERROR::raiseError(500, $db->stderror());
                 }
             }
         }
         // Get an ACL object
         $acl =& JFactory::getACL();
         // Get the user group from the ACL
         if ($user->get('tmp_user') == 1) {
             $grp = new JObject();
             // This should be configurable at some point
             $grp->set('name', 'Registered');
         } else {
             $grp = $acl->getAroGroup($user->get('id'));
         }
         //Mark the user as logged in
         $user->set('guest', 0);
         $user->set('aid', 1);
         // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
         if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
             $user->set('aid', 2);
         }
         //Set the usertype based on the ACL group name
         $user->set('usertype', $grp->name);
         // Register the needed session variables
         $session =& JFactory::getSession();
         $session->set('user', $user);
         // Get the session object
         $table =& JTable::getInstance('session');
         $table->load($session->getId());
         $table->guest = $user->get('guest');
         $table->username = $user->get('username');
         $table->userid = intval($user->get('id'));
         $table->usertype = $user->get('usertype');
         $table->gid = intval($user->get('gid'));
         $table->update();
         // Hit the user last visit field
         $user->setLastVisit();
     }
 }
Ejemplo n.º 20
0
 public function createUser(&$tableModel)
 {
     jimport('joomla.mail.helper');
     $app =& JFactory::getApplication();
     $db =& JFactory::getDBO();
     $log =& JTable::getInstance('Log', 'Table');
     $log->id = null;
     $log->message = "";
     $log->referring_url = $_SERVER['HTTP_REFERER'];
     $log->message_type = 'plg.table.tablecsv.csv_import_user.information';
     $formModel =& $tableModel->getForm();
     $data =& $formModel->_formData;
     $clear_passwd = '';
     // grab username, name and email
     // @TODO - sanity check these config vars (plus userid) to make sure they have been edited.
     $userdata['username'] = $data[$this->username_element];
     $userdata['email'] = $data[$this->email_element];
     $userdata['name'] = $data[$this->name_element];
     if (!JMailHelper::isEmailAddress($userdata['email'])) {
         if ($app->isAdmin()) {
             $app->enqueueMessage("No email for {$userdata['username']}");
         }
         $log->message_type = 'plg.table.tablecsv.csv_import_user.warning';
         $log->message = "No email for {$userdata['username']}";
         $log->store();
         return false;
     }
     $db->setQuery("SELECT * FROM #__users WHERE username = "******"SELECT * FROM #__users WHERE username != " . $db->Quote($userdata['username']) . " AND email = " . $db->Quote($userdata['email']));
         $existing_email = $db->loadObject();
         if (!empty($existing_email)) {
             if ($app->isAdmin()) {
                 $app->enqueueMessage("Email {$userdata['email']} for {$userdata['username']} already in use by {$existing_email->username}");
             }
             $log->message_type = 'plg.table.tablecsv.csv_import_user.warning';
             $log->message = "Email {$userdata['email']} for {$userdata['username']} already in use by {$existing_email->username}";
             $log->store();
             return false;
         }
         $user_id = 0;
         $isNew = true;
         if (!empty($this->password_element)) {
             $clear_passwd = $userdata['password'] = $userdata['password2'] = $data[$this->password_element];
             $data[$this->password_element] = '';
         } else {
             $clear_passwd = $userdata['password'] = $userdata['password2'] = $this->rand_str();
         }
     }
     $user = new JUser($user_id);
     $userdata['gid'] = 18;
     $userdata['block'] = 0;
     $userdata['id'] = $user_id;
     if ($isNew) {
         $now =& JFactory::getDate();
         $user->set('registerDate', $now->toMySQL());
     }
     if (!$user->bind($userdata)) {
         if ($app->isAdmin()) {
             $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
             $app->enqueueMessage($user->getError(), 'error');
         }
         $log->message_type = 'plg.table.tablecsv.csv_import_user.error';
         $log->message = "Error storing user info for: {$userdata['username']}";
         $log->store();
         return false;
     }
     if (!$user->save()) {
         if ($app->isAdmin()) {
             $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
             $app->enqueueMessage($user->getError(), 'error');
         }
         $log->message_type = 'plg.table.tablecsv.csv_import_user.error';
         $log->message = "Error storing user info for: {$userdata['username']}";
         $log->store();
         return false;
     }
     // save clear text password if requested
     if ($isNew && !empty($this->first_password_element)) {
         $data[$this->first_password_element] = $clear_passwd;
     }
     // store the userid
     $data[$this->userid_element] = $user->get('id');
     // optionally set 'created' flag
     if (!empty($this->user_created_element)) {
         $data[$this->user_created_element] = $this->user_created_value;
     }
     if ($isNew) {
         $log->message = "Created user: {$userdata['username']}";
     } else {
         $log->message = "Modified user: {$userdata['username']}";
     }
     $log->store();
     return true;
 }
Ejemplo n.º 21
0
 /**
  * process the plugin, called when form is submitted
  *
  * @param object $params
  * @param object form
  */
 function onBeforeStore(&$params, &$formModel)
 {
     $app =& JFactory::getApplication();
     //if the fabrik table is set to be jos_users and the this plugin is used
     //we need to alter the form model to tell it not to store the main row
     // but to still store any joined rows
     $ftable = str_replace('#__', $app->getCfg('dbprefix'), $formModel->getTableModel()->getTable()->db_table_name);
     $jos_users = $app->getCfg('dbprefix') . 'users';
     if ($ftable == $jos_users) {
         $formModel->_storeMainRow = false;
     }
     $usersConfig =& JComponentHelper::getParams('com_users');
     // Initialize some variables
     $me =& JFactory::getUser();
     $acl =& JFactory::getACL();
     $MailFrom = $app->getCfg('mailfrom');
     $FromName = $app->getCfg('fromname');
     $SiteName = $app->getCfg('sitename');
     $siteURL = COM_FABRIK_LIVESITE;
     $bypassActivation = $params->get('juser_bypass_activation', false);
     $bypassRegistration = $params->get('juser_bypass_registration', true);
     $usertype_max = (int) $params->get('juser_usertype_max', 18);
     // load in the com_user language file
     $lang =& JFactory::getLanguage();
     $lang->load('com_user');
     $data =& $formModel->_formData;
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $option = JRequest::getCmd('option');
     $original_id = 0;
     if ($params->get('juser_field_userid') != '') {
         $this->useridfield = $this->getFieldName($params, 'juser_field_userid');
         if (!empty($formModel->_rowId)) {
             $original_id = (int) $data[$this->useridfield];
         }
     } else {
         $original_id = 0;
         $this->useridfield = '';
     }
     // Create a new JUser object
     $user = new JUser($original_id);
     $original_gid = $user->get('gid');
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     //$post = JRequest::get('post');
     if ($isNew && $usersConfig->get('allowUserRegistration') == '0' && !$bypassRegistration) {
         JError::raiseError(403, JText::_('Access Forbidden - Registration not enabled'));
         return false;
     }
     //new
     $post = array();
     $this->passwordfield = $this->getFieldName($params, 'juser_field_password');
     $this->passwordvalue = $this->getFieldValue($params, 'juser_field_password', $data);
     $this->namefield = $this->getFieldName($params, 'juser_field_name');
     $this->namevalue = $this->getFieldValue($params, 'juser_field_name', $data);
     $this->usernamefield = $this->getFieldName($params, 'juser_field_username');
     $this->usernamevalue = $this->getFieldValue($params, 'juser_field_username', $data);
     $this->emailfield = $this->getFieldName($params, 'juser_field_email');
     $this->emailvalue = $this->getFieldValue($params, 'juser_field_email', $data);
     $post['id'] = $original_id;
     if (!$isNew) {
         // for now, don't allow changing f GIDthru JUser plugin!
         // $post['gid'] = $original_gid;
         // $$$ hugh - let's allow gid to be changed as long as it doesn't
         // exceed the currently logged on user's level
         // yes, i know this duplicates codce from below, for now I'm just noodling around
         if ($params->get('juser_field_usertype') != '') {
             $this->gidfield = $this->getFieldName($params, 'juser_field_usertype');
             $post['gid'] = JArrayHelper::getValue($data, $this->gidfield, 18);
             if (is_array($post['gid'])) {
                 $post['gid'] = $post['gid'][0];
             }
             $post['gid'] = (int) $post['gid'];
             if ($post['gid'] > $me->get('gid')) {
                 $post['gid'] = $me->get('gid');
             }
         } else {
             // if editing an existing user and no gid field being used,
             // use existing gid.
             $post['gid'] = $original_gid;
         }
     } else {
         if ($params->get('juser_field_usertype') != '') {
             $this->gidfield = $this->getFieldName($params, 'juser_field_usertype');
             $post['gid'] = JArrayHelper::getValue($data, $this->gidfield, 18);
             if (is_array($post['gid'])) {
                 $post['gid'] = $post['gid'][0];
             }
         } else {
             $post['gid'] = 18;
         }
     }
     $post['gid'] = (int) $post['gid'];
     if ($post['gid'] === 0) {
         $post['gid'] = 18;
     }
     // $$$ hugh - added 'usertype_max' param, as a safety net to prevent GID's being
     // set to arbitrarily high values thru spoofing.
     if ($post['gid'] > $usertype_max && $post['gid'] != $original_gid) {
         //$post['gid'] = $usertype_max;
         $msg = JText::_('Attempting to set usertype above allowed level!');
         $app->enqueueMessage($msg, 'message');
         return false;
     }
     if ($params->get('juser_field_block') != '') {
         $this->blockfield = $this->getFieldName($params, 'juser_field_block');
         $blocked = JArrayHelper::getValue($data, $this->blockfield, '');
         if (is_array($blocked)) {
             // probably a dropdown
             $post['block'] = (int) $blocked[0];
         } else {
             $post['block'] = (int) $blocked;
         }
     } else {
         $post['block'] = 0;
     }
     //$$$tom get password field to use in $origdata object if editing user and not changing password
     $origdata =& $formModel->_origData;
     $pwfield = $this->passwordfield;
     $post['username'] = $this->usernamevalue;
     $post['password'] = $this->passwordvalue;
     $post['password2'] = $this->passwordvalue;
     $post['name'] = $this->namevalue;
     $name = $this->namevalue;
     $post['email'] = $this->emailvalue;
     $ok = $this->check($post, $formModel, $params);
     if (!$ok) {
         // @TODO - add some error reporting
         return false;
     }
     // Set the registration timestamp
     if ($isNew) {
         $now =& JFactory::getDate();
         $user->set('registerDate', $now->toMySQL());
     }
     // Check that username is not greater than 25 characters
     $username = $post['username'];
     if (strlen($username) > 150) {
         $username = substr($username, 0, 150);
         $user->set('username', $username);
     }
     // Check that password is not greater than 100 characters
     if (strlen($post['password']) > 100) {
         $post['password'] = substr($post['password'], 0, 100);
     }
     //$$$tom Is password field empty on edit?
     if (!$isNew && strlen($password) == 0) {
         $keepPassword = true;
     }
     // end new
     if (!$user->bind($post)) {
         $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     // $$$ rob 23/05/2011 moved after bind as we want to ensure block is set to the right level based on the plugin and J's options
     if ($isNew) {
         // If user activation is turned on, we need to set the activation information
         $useractivation = $usersConfig->get('useractivation');
         if ($useractivation == '1' && !$bypassActivation) {
             jimport('joomla.user.helper');
             $user->set('activation', md5(JUserHelper::genRandomPassword()));
             $user->set('block', '1');
         }
     }
     // $$$ rob 20/052011 if a new user then they won't have an acl group assigned
     if ($isNew) {
         $this_group = '';
     } else {
         $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO');
         $groups = $acl->get_object_groups($objectID, 'ARO');
         $this_group = strtolower($acl->get_group_name($groups[0], 'ARO'));
     }
     if (!$isNew) {
         if ($user->get('id') == $me->get('id') && $user->get('block') == 1) {
             $msg = JText::_('You cannot block Yourself!');
             $app->enqueueMessage($msg, 'message');
             return false;
         } else {
             if ($this_group == 'super administrator' && $user->get('block') == 1) {
                 $msg = JText::_('You cannot block a Super Administrator');
                 $app->enqueueMessage($msg, 'message');
                 return false;
             } else {
                 if ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) {
                     $msg = JText::_('WARNBLOCK');
                     $app->enqueueMessage($msg, 'message');
                     return false;
                 } else {
                     if ($this_group == 'super administrator' && $me->get('gid') != 25) {
                         $msg = JText::_('You cannot edit a super administrator account');
                         $app->enqueueMessage($msg, 'message');
                         return false;
                     }
                 }
             }
         }
         //$$$tom Keep original password
         if ($keepPassword) {
             //$user->set('password', $origdata->$pwfield);
         }
         // if group has been changed and where original group was a Super Admin
         if ($user->get('gid') != $original_gid && $original_gid == 25) {
             $db =& JFactory::getDBO();
             // count number of active super admins
             $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count <= 1) {
                 // disallow change if only one Super Admin exists
                 $this->setRedirect('index.php?option=com_users', JText::_('WARN_ONLY_SUPER'));
                 return false;
             }
         }
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message');
         $app->enqueueMessage($user->getError(), 'error');
         return false;
     }
     $session =& JFactory::getSession();
     JRequest::setVar('newuserid', $user->id);
     JRequest::setVar('newuserid', $user->id, 'cookie');
     $session->set('newuserid', $user->id);
     JRequest::setVar('newuserid_element', $this->useridfield);
     JRequest::setVar('newuserid_element', $this->useridfield, 'cookie');
     $session->set('newuserid_element', $this->useridfield);
     /*
      * Time for the email magic so get ready to sprinkle the magic dust...
      */
     if ($isNew) {
         $adminEmail = $me->get('email');
         $adminName = $me->get('name');
         $subject = sprintf(JText::_('PLG_FABRIK_FORM_JUSER_ACCOUNT_DETAILS_FOR'), $name, $SiteName);
         $subject = html_entity_decode($subject, ENT_QUOTES);
         if ($useractivation == 1 && !$bypassActivation) {
             $message = sprintf(JText::_('PLG_FABRIK_FORM_JUSER_SEND_MSG_ACTIVATE'), $name, $SiteName, $siteURL . "index.php?option=com_user&task=activate&activation=" . $user->get('activation'), $siteURL, $username, $user->password_clear);
         } else {
             if ($params->get('juser_bypass_accountdetails', 0) != 1) {
                 //$$$tom adding Bypass Joomla's "Account details for..." email
                 $message = sprintf(JText::_('PLG_FABRIK_FORM_JUSER_SEND_MSG'), $name, $SiteName, $siteURL);
             }
         }
         $message = html_entity_decode($message, ENT_QUOTES);
         if ($MailFrom != '' && $FromName != '') {
             $adminName = $FromName;
             $adminEmail = $MailFrom;
         }
         if ($message) {
             //$$$tom see comment above about bypassing Joomla's email
             JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message);
         }
     }
     // If updating self, load the new user object into the session
     if ($user->get('id') == $me->get('id')) {
         // Get an ACL object
         $acl =& JFactory::getACL();
         // Get the user group from the ACL
         $grp = $acl->getAroGroup($user->get('id'));
         // Mark the user as logged in
         $user->set('guest', 0);
         $user->set('aid', 1);
         // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
         if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
             $user->set('aid', 2);
         }
         // Set the usertype based on the ACL group name
         $user->set('usertype', $grp->name);
         $session->set('user', $user);
     }
     if (!empty($this->useridfield)) {
         $data[$this->useridfield] = $user->id;
         $data[$this->useridfield . '_raw'] = $user->id;
     }
     if ($ftable == $jos_users) {
         $formModel->_rowId = $user->get('id');
     }
 }
Ejemplo n.º 22
0
 /**
  * Genera el Ecualizador por defecto para el usuario. Este método también
  * reconstruye el ecualizador del usuario en caso de que haya si borrado.
  *
  * @param Array $user Arreglo con información del usuario.
  * @param Array $options Arreglo con opciones varias.
  * @return True En todos los casos. Si falla la creació del Ecualizador el
  *              modulo correspondiente mostrará un mensaje de error.
  */
 function onLoginUser($user, $options)
 {
     // No ejecutar si se accede al backend administrativo
     $app = JFactory::getApplication();
     if ($app->isAdmin()) {
         return true;
     }
     // Recupera información del usuario
     jimport('joomla.user.helper');
     $instance = new JUser();
     $id = intval(JUserHelper::getUserId($user['username']));
     if ($id) {
         $instance->load($id);
     }
     // Arreglo con datos del usuario relevantes
     $userTmp['id'] = intval($instance->get('id'));
     $userTmp['name'] = $instance->get('name');
     // Si el usuario no cuenta con un ecualizador, se lo genera
     $userEq = $this->_ctrlEq->retrieveUserEqImpl($id);
     if (is_null($userEq) || empty($userEq)) {
         $this->_ctrlEq->_createNewDefaultEq($userTmp);
     }
     return true;
 }
Ejemplo n.º 23
0
 function publish()
 {
     $mainframe = JFactory::getApplication();
     // Check for request forgeries
     JRequest::checkToken() or die('Invalid Token');
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $cid = JRequest::getVar('cid', array(), '', 'array');
     $task = JRequest::getCmd('task');
     $publish = $task == 'publish';
     $option = JRequest::getCmd('option');
     $section = JRequest::getVar('section');
     JArrayHelper::toInteger($cid);
     // nichts ausgewählt
     if (empty($cid)) {
         JError::raiseWarning(500, 'No items selected');
         $mainframe->redirect('index.php?option=' . $option . '&section=' . $section);
     }
     $clmAccess = clm_core::$access;
     // Prüfen ob User Berechtigung zum (un-)publishen hat
     $row = JTable::getInstance('users', 'TableCLM');
     $row->load($cid[0]);
     $id = $row->jid;
     $jid = $user->get('id');
     $gid = $user->get('gid');
     // User kann sich nicht selbst blocken
     $user_publish = new JUser($id);
     if ($user_publish->get('id') == $user->get('id') and $task != "publish") {
         JError::raiseWarning(500, JText::_('USERS_NO_BLOCK'));
         $link = 'index.php?option=' . $option . '&section=' . $section;
         $mainframe->redirect($link, $msg, "message");
     }
     // User 62 (1. Superadmin) kann von niemanden geblockt werden
     if ($user_publish->get('id') == 62 and $task != "publish") {
         JError::raiseWarning(500, JText::_('USERS_ZURUECKZIEHEN'));
         $link = 'index.php?option=' . $option . '&section=' . $section;
         $mainframe->redirect($link, $msg, "message");
     }
     // Es können keine Admin / Superadmin geblockt werden von nicht-Superadmin-User
     if ($user_publish->get('gid') > 23 and $gid < 25) {
         JError::raiseWarning(500, JText::_('USERS_NO_JOOMLA'));
         $link = 'index.php?option=' . $option . '&section=' . $section;
         $mainframe->redirect($link, $msg, "message");
     }
     if (!$clmAccess->compare($row->usertype)) {
         JError::raiseWarning(500, JText::_('USERS_NO_ZURUECK'));
         $link = 'index.php?option=' . $option . '&section=' . $section;
         $mainframe->redirect($link, $msg, "message");
     }
     $cids = implode(',', $cid);
     $query = ' UPDATE #__clm_user' . ' SET published = ' . (int) $publish . ' WHERE id IN ( ' . $cids . ' )' . ' AND jid <> ' . clm_core::$access->getJid() . ' AND ( checked_out = 0 OR ( checked_out = ' . (int) $user->get('id') . ' ) )';
     if ($task == 'publish') {
         $block = 0;
     } else {
         $block = 1;
     }
     for ($x = 0; $x < count($cid); $x++) {
         $row->load($cid[$x]);
         $block_id = $row->jid;
         $user_block = JUser::getInstance($block_id);
         if ($user_block->gid < 24) {
             $user_block->set('block', $block);
             $user_block->save();
         } else {
             $err = 1;
         }
     }
     if ($err == "1") {
         JError::raiseNotice(6000, JText::_('USERS_GEWAEHLTER'));
     }
     $db->setQuery($query);
     if (!$db->query()) {
         JError::raiseError(500, $db->getErrorMsg());
     }
     if (count($cid) == 1) {
         $row = JTable::getInstance('users', 'TableCLM');
         $row->load($cid[0]);
     }
     // Log schreiben
     $clmLog = new CLMLog();
     $clmLog->aktion = "User " . $task;
     $clmLog->params = array('jid' => $cid[0], 'cids' => $cids);
     $clmLog->write();
     if ($task == 'publish') {
         $msg = JText::_('USERS_VEROEFFENTLICH');
     } else {
         $msg = JText::_('USERS_ZURUECK');
     }
     if ($row->aktive == 0) {
         JError::raiseNotice(6000, JText::_('USERS_INAKTIVE'));
     }
     $mainframe->redirect('index.php?option=' . $option . '&section=' . $section, $msg, "message");
 }
Ejemplo n.º 24
0
 /**
  * Save controller that receives arguments via HTTP POST.
  **/
 public function save()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $lang =& JFactory::getLanguage();
     $lang->load('com_users');
     $userId = JRequest::getVar('userid', '', 'POST');
     $mainframe =& JFactory::getApplication();
     $message = '';
     $url = JRoute::_('index.php?option=com_community&view=users', false);
     $my =& JFactory::getUser();
     $acl =& JFactory::getACL();
     $cacl =& CACL::getInstance();
     $mailFrom = $mainframe->getCfg('mailfrom');
     $fromName = $mainframe->getCfg('fromname');
     $siteName = $mainframe->getCfg('sitename');
     if (empty($userId)) {
         $message = JText::_('COM_COMMUNITY_USERS_EMPTY_USER_ID');
         $mainframe->redirect($url, $message);
     }
     // Create a new JUser object
     $user = new JUser($userId);
     $original_gid = $user->get('gid');
     $post = JRequest::get('post');
     $post['username'] = JRequest::getVar('username', '', 'post', 'username');
     $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $notifyEmailSystem = JRequest::getVar('sendEmail', '', 'post', 'sendEmail');
     if (!$user->bind($post)) {
         $message = JText::_('COM_COMMUNITY_USERS_SAVE_USER_INFORMATION_ERROR') . ' : ' . $user->getError();
         $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false);
         $mainframe->redirect($url, $message);
         exit;
     }
     //$objectID 	= $acl->get_object_id( 'users', $user->get('id'), 'ARO' );
     //$groups 	= $acl->get_object_groups( $objectID, 'ARO' );
     //$this_group = JString::strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );
     $this_group = $cacl->getGroupsByUserId($user->get('id'));
     if ($user->get('id') == $my->get('id') && $user->get('block') == 1) {
         $message = JText::_('COM_COMMUNITY_USERS_BLOCK_YOURSELF');
         $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false);
         $mainframe->redirect($url, $message);
         exit;
     }
     if ($this_group == 'super administrator' && $user->get('block') == 1) {
         $message = JText::_('COM_COMMUNITY_USERS_BLOCK_SUPER_ADMINISTRATOR');
         $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false);
         $mainframe->redirect($url, $message);
         exit;
     }
     if ($this_group == 'administrator' && $my->get('gid') == 24 && $user->get('block') == 1) {
         $message = JText::_('COM_COMMUNITY_USERS_WARNBLOCK');
         $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false);
         $mainframe->redirect($url, $message);
         exit;
     }
     if ($this_group == 'super administrator' && $my->get('gid') != 25) {
         $message = JText::_('COM_COMMUNITY_USERS_SUPER_ADMINISTRATOR_EDIT');
         $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false);
         $mainframe->redirect($url, $message);
         exit;
     }
     $isNew = $user->get('id') == 0;
     if (!$isNew) {
         if ($user->get('gid') != $original_gid && $original_gid == 25) {
             $query = 'SELECT COUNT( ' . $db->nameQuote('id') . ' )' . ' FROM ' . $db->nameQuote('#__users') . ' WHERE ' . $db->nameQuote('gid') . ' = ' . $db->Quote(25) . ' AND ' . $db->nameQuote('block') . ' = ' . $db->Quote(0);
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count <= 1) {
                 $message = JText::_('COM_COMMUNITY_USERS_WARN_ONLY_SUPER');
                 $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false);
                 $mainframe->redirect($url, $message);
                 exit;
             }
         }
     }
     //Joomla 1.6 patch to keep the group ID of user intact when saving
     if (property_exists($user, 'groups')) {
         foreach ($user->groups as $groupid => $groupname) {
             $user->groups[$groupid] = $groupid;
         }
     }
     if (!$user->save()) {
         $message = JText::_('COM_COMMUNITY_USERS_SAVE_USER_INFORMATION_ERROR') . ' : ' . $user->getError();
         $mainframe->redirect($url, $message);
         exit;
     }
     $appsLib =& CAppPlugins::getInstance();
     $appsLib->loadApplications();
     $userRow = array();
     $userRow[] = $user;
     $appsLib->triggerEvent('onUserDetailsUpdate', $userRow);
     // @rule: Send out email if it is a new user.
     if ($isNew) {
         $adminEmail = $my->get('email');
         $adminName = $my->get('name');
         $subject = JText::_('COM_COMMUNITY_USERS_NEW_USER_MESSAGE_SUBJECT');
         $message = sprintf(JText::_('COM_COMMUNITY_USERS_NEW_USER_MESSAGE'), $user->get('name'), $siteName, JURI::root(), $user->get('username'), $user->password_clear);
         if (!empty($mailfrom) && !empty($fromName)) {
             $adminName = $fromName;
             $adminEmail = $mailFrom;
         }
         JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message);
     }
     // If updating self, load the new user object into the session
     if ($user->get('id') == $my->get('id')) {
         jimport('joomla.version');
         $version = new JVersion();
         $joomla_ver = $version->getHelpVersion();
         // Get the user group from the ACL
         if ($joomla_ver <= '0.15') {
             $grp = $acl->getAroGroup($user->get('id'));
             // Mark the user as logged in
             $user->set('guest', 0);
             $user->set('aid', 1);
             // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
             if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
                 $user->set('aid', 2);
             }
             // Set the usertype based on the ACL group name
             $user->set('usertype', $grp->name);
         } elseif ($joomla_ver >= '0.16') {
             $grp_name = $cacl->getGroupUser($user->get('id'));
             // Mark the user as logged in
             $user->set('guest', 0);
             $user->set('aid', 1);
             // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
             if ($cacl->is_group_child_of($grp_name, 'Registered') || $cacl->is_group_child_of($grp_name, 'Public Backend')) {
                 $user->set('aid', 2);
             }
             // Set the usertype based on the ACL group name
             $user->set('usertype', $grp_name);
         }
         $session =& JFactory::getSession();
         $session->set('user', $user);
     }
     // Process and save custom fields
     $user = CFactory::getUser($userId);
     $model =& $this->getModel('users');
     $userModel = CFactory::getModel('profile');
     $values = array();
     $profile = $userModel->getEditableProfile($userId, $user->getProfileType());
     CFactory::load('libraries', 'profile');
     foreach ($profile['fields'] as $group => $fields) {
         foreach ($fields as $data) {
             // Get value from posted data and map it to the field.
             // Here we need to prepend the 'field' before the id because in the form, the 'field' is prepended to the id.
             $postData = JRequest::getVar('field' . $data['id'], '', 'POST');
             $values[$data['id']] = CProfileLibrary::formatData($data['type'], $postData);
             // @rule: Validate custom profile if necessary
             if (!CProfileLibrary::validateField($data['id'], $data['type'], $values[$data['id']], $data['required'])) {
                 // If there are errors on the form, display to the user.
                 $message = JText::sprintf('The field "%1$s" contain improper values', $data['name']);
                 $mainframe->redirect('index.php?option=com_community&view=users&layout=edit&id=' . $user->id, $message, 'error');
                 return;
             }
         }
     }
     // Update user's parameter DST
     $params =& $user->getParams();
     $offset = $post['daylightsavingoffset'];
     $params->set('daylightsavingoffset', $offset);
     $params->set('notifyEmailSystem', $notifyEmailSystem);
     // Update user's point
     $points = JRequest::getVar('userpoint', '', 'REQUEST');
     if (!empty($points)) {
         $user->_points = $points;
         $user->save();
     }
     // Update user's status
     if ($user->getStatus() != $post['status']) {
         $user->setStatus($post['status']);
     }
     $user->save('params');
     $valuesCode = array();
     foreach ($values as $key => &$val) {
         $fieldCode = $userModel->getFieldCode($key);
         if ($fieldCode) {
             $valuesCode[$fieldCode] =& $val;
         }
     }
     // Trigger before onBeforeUserProfileUpdate
     $args = array();
     $args[] = $userId;
     $args[] = $valuesCode;
     $saveSuccess = false;
     $result = $appsLib->triggerEvent('onBeforeProfileUpdate', $args);
     if (!$result || !in_array(false, $result)) {
         $saveSuccess = true;
         $userModel->saveProfile($userId, $values);
     }
     // Trigger before onAfterUserProfileUpdate
     $args = array();
     $args[] = $userId;
     $args[] = $saveSuccess;
     $result = $appsLib->triggerEvent('onAfterProfileUpdate', $args);
     if (!$saveSuccess) {
         $message = JText::_('COM_COMMUNITY_USERS_PROFILE_NOT_UPDATED');
         $mainframe->redirect($url, $message, 'error');
     }
     $message = JText::_('COM_COMMUNITY_USERS_UPDATED_SUCCESSFULLY');
     $mainframe->redirect($url, $message);
 }
Ejemplo n.º 25
0
	private function jvsave($member_id, $post) {
		$mainframe = JFactory :: getApplication();
		$option = JRequest :: getCmd('option');
		// Initialize some variables
		$msg = "";
		$me = & JFactory :: getUser();
		$MailFrom = $mainframe->getCfg('mailfrom');
		$FromName = $mainframe->getCfg('fromname');
		$SiteName = $mainframe->getCfg('sitename');
		// Create a new JUser object
		$user = new JUser($member_id);
		$original_gid = $user->get('gid');
		if (!$user->bind($post)) {
			$result = array ();
			$result['success'] = false;
			$result['title'] = 'Error';
			$result['content'] = JText :: _('Failed Updating Member Information');
			$result = oseJSON :: encode($result);
			oseExit($result);
		}
		// Are we dealing with a new user which we need to create?
		$isNew = ($user->get('id') < 1);
		if (!$isNew) {
			// if group has been changed and where original group was a Super Admin
			if ($user->get('gid') != $original_gid && $original_gid == 25) {
				// count number of active super admins
				$query = 'SELECT COUNT( id )' .				' FROM #__users' .				' WHERE gid = 25' .				' AND block = 0';
				$this->db->setQuery($query);
				$count = $this->db->loadResult();
				if ($count <= 1) {
					$result = array ();
					$result['success'] = false;
					$result['title'] = 'Error';
					$result['content'] = JText :: _('Failed Updating Member Information');
					$result = oseJSON :: encode($result);
					oseExit($result);
				}
			}
		}
		/*
			 * Lets save the JUser object
			 */
		if (!$user->save()) {
			$result = array ();
			$result['success'] = false;
			$result['title'] = 'Error';
			$result['content'] = $user->getError();
			$result = oseJSON :: encode($result);
			oseExit($result);
		}
		// For new users, email username and password
		// Capture the new user id
		if ($isNew) {
			$newUserId = $user->get('id');
		} else {
			$newUserId = null;
		}
		return $newUserId;
	}
Ejemplo n.º 26
0
 /**
  * Saves a user into Joomla! 1.5 
  *
  * @return int An integer user_id if the user was saved successfully, false if not
  */
 function save()
 {
     global $mainframe, $vmLogger, $VM_LANG;
     $option = JRequest::getCmd('option');
     // Initialize some variables
     $db =& JFactory::getDBO();
     $me =& JFactory::getUser();
     $MailFrom = $mainframe->getCfg('mailfrom');
     $FromName = $mainframe->getCfg('fromname');
     $SiteName = $mainframe->getCfg('sitename');
     // Create a new JUser object
     $user = new JUser(JRequest::getVar('id', 0, 'post', 'int'));
     $original_gid = $user->get('gid');
     $post = JRequest::get('post');
     $post['username'] = JRequest::getVar('username', '', 'post', 'username');
     $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
     if (!$user->bind($post)) {
         echo "<script type=\"text/javascript\"> alert('" . vmHtmlEntityDecode($user->getError()) . "');</script>\n";
         return false;
     }
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if (!$isNew) {
         // if group has been changed and where original group was a Super Admin
         if ($user->get('gid') != $original_gid && $original_gid == 25) {
             // count number of active super admins
             $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count <= 1) {
                 // disallow change if only one Super Admin exists
                 $vmLogger->err($VM_LANG->_('VM_USER_ERR_ONLYSUPERADMIN'));
                 return false;
             }
         }
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         echo "<script type=\"text/javascript\"> alert('" . vmHtmlEntityDecode($user->getError()) . "');</script>\n";
         return false;
     }
     // For new users, email username and password
     if ($isNew) {
         $name = $user->get('name');
         $email = $user->get('email');
         $username = $user->get('username');
         $password = $user->password_clear;
         $this->_sendMail($name, $email, $username, $password);
     }
     // Capture the new user id
     if ($isNew) {
         $newUserId = $user->get('id');
     } else {
         $newUserId = false;
     }
     return $newUserId;
 }
Ejemplo n.º 27
0
 function confirmOrder($order_id, $params = array())
 {
     $db = oseDB::instance();
     $where = array();
     $where[] = '`order_id` = ' . $db->Quote($order_id);
     $orderInfo = $this->getOrder($where, 'obj');
     if (!isset($params['params'])) {
         $params['params'] = oseJson::decode($orderInfo->params);
         $params['params']->recurrence_times = 1 + oseObject::getValue($params['params'], 'recurrence_times', 0);
         $params['params'] = oseJson::encode($params['params']);
     }
     $this->updateOrder($order_id, "confirmed", $params);
     $user_id = $orderInfo->user_id;
     $payment_mode = $orderInfo->payment_mode;
     $payment_method = $orderInfo->payment_method;
     $user = new JUser($user_id);
     $email = $user->get('email');
     $query = " SELECT * FROM `#__osemsc_order_item`" . " WHERE `order_id` = '{$orderInfo->order_id}'";
     $db->setQuery($query);
     $items = oseDB::loadList('obj');
     foreach ($items as $item) {
         switch ($item->entry_type) {
             case 'license':
                 $license = oseRegistry::call('lic')->getInstance(0);
                 $licenseInfo = $license->getKeyInfo($item->entry_id, 'obj');
                 $licenseInfoParams = oseJson::decode($licenseInfo->params);
                 $msc_id = $licenseInfoParams->msc_id;
                 $updated = $this->joinMsc($order_id, $item->order_item_id, $msc_id, $user_id);
                 break;
             default:
             case 'msc':
                 $updated = $this->joinMsc($order_id, $item->order_item_id, $item->entry_id, $user_id);
                 break;
         }
         if (!$updated['success']) {
             return $updated;
         }
     }
     //Auto reucrring email control
     $emailConfig = oseMscConfig::getConfig('email', 'obj');
     $send = true;
     $orderparams = oseJson::decode($params['params']);
     $recurrence_times = oseObject::getValue($orderparams, 'recurrence_times', 1);
     if ($recurrence_times > 1 && oseObject::getValue($emailConfig, 'sendReceiptOnlyOneTime', false)) {
         if ($orderparams->has_trial) {
             $send = false;
         } else {
             if ($recurrence_times > 2) {
                 $send = false;
             }
         }
     }
     if ($send) {
         $memEmail = oseRegistry::call('member')->getInstance('Email');
         $receipt = $memEmail->getReceipt($orderInfo);
         $memEmail->sendEmail($receipt, $email);
         if (!empty($emailConfig->sendReceipt2Admin)) {
             $memEmail->sendToAdminGroup($receipt, $emailConfig->admin_group);
         }
     }
     /*
     $query= "SELECT id FROM `#__menu` WHERE `link` LIKE 'index.php?option=com_osemsc&view=member'";
     $db->setQuery($query);
     $result= $db->loadResult();
     
     if(empty($result))
     {
     	$return_url= "index.php?option=com_osemsc&view=member";
     }
     else
     {
     	$return_url= "index.php?option=com_osemsc&view=member&Itemid=".$result;
     }
     */
     $orderInfoParams = oseJson::decode($orderInfo->params);
     $session = JFactory::getSession();
     $return_url = isset($orderInfoParams->returnUrl) ? urldecode($orderInfoParams->returnUrl) : "index.php";
     //$session = JFactory::getSession();
     //$return_url = $session->get('oseReturnUrl');
     $return['success'] = true;
     $return['payment'] = $payment_method;
     $return['title'] = JText::_('Success');
     $return['content'] = JText::_(' Your membership is activated successfully. Please click the OK button to continue');
     $return['url'] = $return_url;
     $return['returnUrl'] = $return_url;
     $this->updateOrder($order_id, "confirmed");
     //osePayment::getInstance('Cart')->init();
     return $return;
 }
Ejemplo n.º 28
0
 /**
  * Checks if the user need to be blocked
  *
  * @access	public
  * @param   JUser   $instance holds the user data
  * @param 	string  $restriction_type Holds the restriction type value (from plugin parameters)
  * @param 	string  $user_list_str Holds the string with comma-delimited user logins which are to be blocked if needed (from plugin parameters)
  * @param 	string  $intervals_value Holds the string with time intervals value (from plugin parameters)
  * @param 	string  $weekdays_value Holds the string with comma-delimited weekdays (from plugin parameters)
  * @param 	JDate  $p_start Restriction period start (from plugin parameters)
  * @param 	JDate  $p_end Restriction period end (from plugin parameters)
  * @return	string	The replaced string on success
  * @since	1.0.3
  */
 private function checkUserForBlock(&$instance, $restriction_type, $user_list_str, $intervals_value, $weekdays_value, $p_start, $p_end)
 {
     if (empty($instance)) {
         return false;
     }
     global $mainframe;
     $t_now = new JDate(date("Y-m-d H:i:s eP"));
     $user_list_str = trim($user_list_str);
     $users_array = array();
     if (empty($user_list_str)) {
         // check all users, the user being logged-in will be always checked for blocking
         array_push($users_array, $instance->get('username'));
     } else {
         // check only particular users
         $users_array = split(",", $user_list_str);
     }
     foreach ($users_array as $user_login) {
         $user_login = trim($user_login);
         if ($instance->get('username') == $user_login) {
             // The user, being logged-in must be blocked
             if ($restriction_type == "intervals") {
                 return $this->checkTimeIntervals($t_now, $intervals_value);
             } else {
                 if ($restriction_type == "weekdays") {
                     return $this->checkWeekDays($t_now, $weekdays_value);
                 } else {
                     if ($restriction_type == "period") {
                         return $this->checkTimePeriod($t_now, $p_start, $p_end);
                     } else {
                         if ($restriction_type == "weekdays_intervals") {
                             return $this->checkTimeIntervals($t_now, $intervals_value) && $this->checkWeekDays($t_now, $weekdays_value);
                         } else {
                             if ($restriction_type == "weekdays_period") {
                                 return $this->checkTimePeriod($t_now, $p_start, $p_end) && $this->checkWeekDays($t_now, $weekdays_value);
                             } else {
                                 if ($restriction_type == "weekdays_period_intervals") {
                                     return $this->checkTimeIntervals($t_now, $intervals_value) && $this->checkTimePeriod($t_now, $p_start, $p_end) && $this->checkWeekDays($t_now, $weekdays_value);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
Ejemplo n.º 29
0
 /**
  * Get an attribute of the CMS user object
  *
  * @param   string|string[]  $key      Name of index or array of names of indexes, each with name or html-input-name-encoded array selection, e.g. a[b][c]
  * @param   mixed            $default  [optional] Default value, or, if instanceof GetterInterface, parent GetterInterface for the default value
  * @param   string|array     $type     [optional] Default: GetterInterface::RAW. Or const int GetterInterface::COMMAND|GetterInterface::INT|... or array( const ) or array( $key => const )
  * @return  mixed
  *
  * @throws \InvalidArgumentException
  */
 public function get($key, $default = null, $type = GetterInterface::RAW)
 {
     return Get::clean($this->cmsOwnUser->get($key, $default), $type);
 }
Ejemplo n.º 30
0
 public function apply()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $mainframe = JFactory::getApplication();
     $db = DiscussHelper::getDBO();
     $my = JFactory::getUser();
     $acl = JFactory::getACL();
     $config = DiscussHelper::getConfig();
     // Create a new JUser object
     $user = new JUser(JRequest::getVar('id', 0, 'post', 'int'));
     $original_gid = $user->get('gid');
     $post = JRequest::get('post');
     $user->name = $post['fullname'];
     if (DiscussHelper::getJoomlaVersion() >= '1.6') {
         $jformPost = JRequest::getVar('jform', array(), 'post', 'array');
         $post['params'] = $jformPost['params'];
     }
     if (!$user->bind($post)) {
         DiscussHelper::setMessageQueue($user->getError(), DISCUSS_QUEUE_ERROR);
         $this->_saveError($user->id);
     }
     if (DiscussHelper::getJoomlaVersion() >= '1.6') {
         if ($user->get('id') == $my->get('id') && $user->get('block') == 1) {
             DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_YOURSELF'), DISCUSS_QUEUE_ERROR);
             $this->_saveError($user->id);
         } else {
             if ($user->authorise('core.admin') && $user->get('block') == 1) {
                 DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_SUPERUSER'), DISCUSS_QUEUE_ERROR);
                 $this->_saveError($user->id);
             } else {
                 if ($user->authorise('core.admin') && !$my->authorise('core.admin')) {
                     DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_EDIT_SUPERUSER'), DISCUSS_QUEUE_ERROR);
                     $this->_saveError($user->id);
                 }
             }
         }
         //replacing thr group name with group id so it is save correctly into the Joomla group table.
         $jformPost = JRequest::getVar('jform', array(), 'post', 'array');
         if (!empty($jformPost['groups'])) {
             $user->groups = array();
             foreach ($jformPost['groups'] as $groupid) {
                 $user->groups[$groupid] = $groupid;
             }
         }
     } else {
         $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO');
         $groups = $acl->get_object_groups($objectID, 'ARO');
         $this_group = strtolower($acl->get_group_name($groups[0], 'ARO'));
         if ($user->get('id') == $my->get('id') && $user->get('block') == 1) {
             DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_YOURSELF'), DISCUSS_QUEUE_ERROR);
             $this->_saveError($user->id);
         } else {
             if ($this_group == 'super administrator' && $user->get('block') == 1) {
                 DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_SUPERUSER'), DISCUSS_QUEUE_ERROR);
                 $this->_saveError($user->id);
             } else {
                 if ($this_group == 'administrator' && $my->get('gid') == 24 && $user->get('block') == 1) {
                     DiscussHelper::setMessageQueue(JText::_('WARNBLOCK'), DISCUSS_QUEUE_ERROR);
                     $this->_saveError($user->id);
                 } else {
                     if ($this_group == 'super administrator' && $my->get('gid') != 25) {
                         DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_EDIT_SUPERUSER'), DISCUSS_QUEUE_ERROR);
                         $this->_saveError($user->id);
                     }
                 }
             }
         }
     }
     // Are we dealing with a new user which we need to create?
     $isNew = $user->get('id') < 1;
     if (DiscussHelper::getJoomlaVersion() <= '1.5') {
         // do this step only for J1.5
         if (!$isNew) {
             // if group has been changed and where original group was a Super Admin
             if ($user->get('gid') != $original_gid && $original_gid == 25) {
                 // count number of active super admins
                 $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
                 $db->setQuery($query);
                 $count = $db->loadResult();
                 if ($count <= 1) {
                     DiscussHelper::setMessageQueue(JText::_('WARN_ONLY_SUPER'), DISCUSS_QUEUE_ERROR);
                     // disallow change if only one Super Admin exists
                     $this->setRedirect('index.php?option=com_easydiscuss&view=users');
                     return false;
                 }
             }
         }
     }
     /*
      * Lets save the JUser object
      */
     if (!$user->save()) {
         DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_SAVE_THE_USER_INFORMATION'), DISCUSS_QUEUE_ERROR);
         return $this->execute('edit');
     }
     // If updating self, load the new user object into the session
     if (DiscussHelper::getJoomlaVersion() <= '1.5') {
         // If updating self, load the new user object into the session
         if ($user->get('id') == $my->get('id')) {
             // Get an ACL object
             $acl = JFactory::getACL();
             // Get the user group from the ACL
             $grp = $acl->getAroGroup($user->get('id'));
             // Mark the user as logged in
             $user->set('guest', 0);
             $user->set('aid', 1);
             // Fudge Authors, Editors, Publishers and Super Administrators into the special access group
             if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) {
                 $user->set('aid', 2);
             }
             // Set the usertype based on the ACL group name
             $user->set('usertype', $grp->name);
             $session = JFactory::getSession();
             $session->set('user', $user);
         }
     }
     $post = JRequest::get('post');
     if ($isNew) {
         // if this is a new account, we unset the id so
         // that profile jtable will add new record properly.
         unset($post['id']);
     }
     $profile = DiscussHelper::getTable('Profile');
     $profile->load($user->id);
     $profile->bind($post);
     $file = JRequest::getVar('Filedata', '', 'Files', 'array');
     if (!empty($file['name'])) {
         $newAvatar = DiscussHelper::uploadAvatar($profile, true);
         $profile->avatar = $newAvatar;
     }
     //save params
     $userparams = DiscussHelper::getRegistry('');
     if (isset($post['facebook'])) {
         $userparams->set('facebook', $post['facebook']);
     }
     if (isset($post['show_facebook'])) {
         $userparams->set('show_facebook', $post['show_facebook']);
     }
     if (isset($post['twitter'])) {
         $userparams->set('twitter', $post['twitter']);
     }
     if (isset($post['show_twitter'])) {
         $userparams->set('show_twitter', $post['show_twitter']);
     }
     if (isset($post['linkedin'])) {
         $userparams->set('linkedin', $post['linkedin']);
     }
     if (isset($post['show_linkedin'])) {
         $userparams->set('show_linkedin', $post['show_linkedin']);
     }
     if (isset($post['skype'])) {
         $userparams->set('skype', $post['skype']);
     }
     if (isset($post['show_skype'])) {
         $userparams->set('show_skype', $post['show_skype']);
     }
     if (isset($post['website'])) {
         $userparams->set('website', $post['website']);
     }
     if (isset($post['show_website'])) {
         $userparams->set('show_website', $post['show_website']);
     }
     $profile->params = $userparams->toString();
     // Save site details
     $siteDetails = DiscussHelper::getRegistry('');
     if (isset($post['siteUrl'])) {
         $siteDetails->set('siteUrl', $post['siteUrl']);
     }
     if (isset($post['siteUsername'])) {
         $siteDetails->set('siteUsername', $post['siteUsername']);
     }
     if (isset($post['sitePassword'])) {
         $siteDetails->set('sitePassword', $post['sitePassword']);
     }
     if (isset($post['ftpUrl'])) {
         $siteDetails->set('ftpUrl', $post['ftpUrl']);
     }
     if (isset($post['ftpUsername'])) {
         $siteDetails->set('ftpUsername', $post['ftpUsername']);
     }
     if (isset($post['ftpPassword'])) {
         $siteDetails->set('ftpPassword', $post['ftpPassword']);
     }
     if (isset($post['optional'])) {
         $siteDetails->set('optional', $post['optional']);
     }
     $profile->site = $siteDetails->toString();
     $profile->store();
     // Update points
     DiscussHelper::getHelper('ranks')->assignRank($profile->id, 'points');
     $app = JFactory::getApplication();
     $task = $this->getTask();
     $url = $task == 'apply' ? 'index.php?option=com_easydiscuss&view=user&id=' . $profile->id : 'index.php?option=com_easydiscuss&view=users';
     DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_USER_INFORMATION_SAVED'), DISCUSS_QUEUE_SUCCESS);
     $app->redirect($url);
 }