Modify User Form to prevent e-mail changes

Need help with the Administration of your Joomla! 1.5 site? This is the spot for you.

Moderator: General Support Moderators

Forum rules
Forum Rules
Absolute Beginner's Guide to Joomla! <-- please read before posting, this means YOU.
Forum Post Assistant - If you are serious about wanting help, you will use this tool to help you post.
miamialbert
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Feb 15, 2011 11:18 am

Modify User Form to prevent e-mail changes

Postby miamialbert » Tue Feb 15, 2011 11:42 am

Hello Joomla Forum,

I've been trying for hours to make what I thought would be a simple modification to User Layout From. option=com_user&view=user&layout=form

I want to allow users to only change passwords. I would like the Username and E-Mail displayed, but not allow users to modify.

I have tried several methods, including edits to the following files:

/com_user/views/user/tmpl/default.php
/com_user/views/user/tmpl/form.php
/com_user/views/register/tmpl/default.php

I have been trying to edit the following code and make it readonly:

Code: Select all

<input type="text" name="name" id="name" size="40" value="<?php echo $this->escape($this->user->get( 'name' ));?>" class="inputbox required" maxlength="50" />


Can someone please help me with the file that needs modifying and the syntax required to make the fields read only.

I understand that this will be a core hack, however I would just like to test results and then I will create a template over ride.

Also - I do not allow front-end user registrations - so a mod of the registration form is OK.

Thanks!
Albert

User avatar
dylanjh
Joomla! Ace
Joomla! Ace
Posts: 1823
Joined: Fri Sep 22, 2006 6:22 pm
Location: UK
Contact:

Re: Modify User Form to prevent e-mail changes

Postby dylanjh » Tue Feb 15, 2011 12:10 pm

Albert, as you point out, the best method for this would be a template override.
Also, it is quite a simple change, although Im not sure if you are trying to affect the email or name field (your code snippet is of the name field)
Anyway, the principles are the same:
1) copy /components/com_user/views/user/tmpl/form.php to /templates/<your template>/html/com_user/user
2) Find the field you want to change. If you want the value to show, but not be editable, then just change the code from

Code: Select all

<input type="text" name="name" id="name" size="40" value="<?php echo $this->escape($this->user->get( 'name' ));?>" class="inputbox required" maxlength="50" />

to

Code: Select all

<?php echo $this->escape($this->user->get( 'name' ));?>


So that will still show the username to the user, but of course, not in a field (hence read only)

Keep in mind that you will then have to add (ideally, somewhere near the closing </form> tag) the username in a hidden field

Code: Select all

<input type="hidden" name="name" value="<?php echo $this->escape($this->user->get( 'name' ));?>">


Then when the user presses submit, joomla will think the name has been entered, but of course it wont have been edited!

Good luck!
EmailAsUsername - Remove Usernames Joomla! Virtuemart And JomSocial registration http://www.lunarhotel.co.uk Many other extensions supported.

miamialbert
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Feb 15, 2011 11:18 am

Re: Modify User Form to prevent e-mail changes

Postby miamialbert » Tue Feb 15, 2011 5:15 pm

Awesome - Thanks Dylan,

Coincidentally, I purchased your EmailAsUsername extension and this is the primary reason I trying to accomplish this.

The code snippet I posted was misleading - however you fully understood. So, I followed your directions, and had a good result. The changes I made now serve a form that allows the User to only change the password while the UN and Name are displayed.

This will work - however, to make it perfect I'd like to have the user have to validate their current password.

Modifications made to

Code: Select all

<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>

<script type="text/javascript">
<!--
   Window.onDomReady(function(){
      document.formvalidator.setHandler('passverify', function (value) { return ($('password').value == value); }   );
   });
// -->
</script>

<form action="<?php echo JRoute::_( 'index.php' ); ?>" method="post" name="userform" autocomplete="off" class="form-validate">
<?php if ( $this->params->def( 'show_page_title', 1 ) ) : ?>
   <div class="componentheading<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
      <?php echo $this->escape($this->params->get('page_title')); ?>
   </div>
<?php endif; ?>
<table cellpadding="5" cellspacing="0" border="0" width="100%">
<tr>
   <td>
      <label for="username">
         <?php echo JText::_( 'User Name' ); ?>:
      </label>
   </td>
   <td>
      <span><?php echo $this->user->get('username');?></span>
   </td>
</tr>
<tr>
   <td width="120">
      <label for="name">
         <?php echo JText::_( 'Your Name' ); ?>:
      </label>
   </td>
   <td>
      
<?php echo $this->escape($this->user->get( 'name' ));?>
   </td>
</tr>
<tr>
   <td>
      <label for="email">
         <?php echo JText::_( 'email' ); ?>:
      </label>
   </td>
   <td>
   <?php echo $this->escape($this->user->get( 'email' ));?>
   </td>
</tr>
<?php if($this->user->get('password')) : ?>
<tr>
   <td>
      <label for="password">
         <?php echo JText::_( 'Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-password" type="password" id="password" name="password" value="" size="40" />
   </td>
</tr>
<tr>
   <td>
      <label for="password2">
         <?php echo JText::_( 'Verify Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-passverify" type="password" id="password2" name="password2" size="40" />
   </td>
</tr>
<?php endif; ?>
</table>
<?php if(isset($this->params)) :  echo $this->params->render( 'params' ); endif; ?>
   <button class="button validate" type="submit" onclick="submitbutton( this.form );return false;"><?php echo JText::_('Save'); ?></button>

   <input type="hidden" name="username" value="<?php echo $this->user->get('username');?>" />
   <input type="hidden" name="email" value="<?php echo $this->user->get('email');?>" />   
   <input type="hidden" name="name" value="<?php echo $this->user->get('name');?>" />      
   <input type="hidden" name="id" value="<?php echo $this->user->get('id');?>" />
   <input type="hidden" name="gid" value="<?php echo $this->user->get('gid');?>" />
   <input type="hidden" name="option" value="com_user" />
   <input type="hidden" name="task" value="save" />
   <?php echo JHTML::_( 'form.token' ); ?>
</form>


Any idea what I can add to to force the user to enter their current password?

Thank you so much for your help. And BTW your Email as Username Extension works like a charm! I will be sure to rate it on JED.

Albert

User avatar
dylanjh
Joomla! Ace
Joomla! Ace
Posts: 1823
Joined: Fri Sep 22, 2006 6:22 pm
Location: UK
Contact:

Re: Modify User Form to prevent e-mail changes

Postby dylanjh » Tue Feb 15, 2011 9:45 pm

Ah! Excellent. Im glad you like it Albert. Yes, A JED review would be very much appreciated. Now then, getting the user to enter thier current password is a bit more involved.
You see for starters, Joomla! doesnt store users passwords either in clear text, or in an excryption that can be reversed (md5) as such, you would need to encrypt the users input, and make sure that they matched, returning an error message if not.
Now this is beyond what should normally be put in the template file (which is what we are editing here) and So, would have to go into the controller.php of com_user.

Looking at the code, it appears that function save is called when the form is submitted. So thats where we'd need to add the code to check, and of course, the code to check the password is correct should be found in the Joomla authentication plugin:

Code: Select all

      // Joomla does not like blank passwords
      if (empty($credentials['password']))
      {
         $response->status = JAUTHENTICATE_STATUS_FAILURE;
         $response->error_message = 'Empty password not allowed';
         return false;
      }

      // Initialize variables
      $conditions = '';

      // Get a database object
      $db =& JFactory::getDBO();

      $query = 'SELECT `id`, `password`, `gid`'
         . ' FROM `#__users`'
         . ' WHERE username=' . $db->Quote( $credentials['username'] )
         ;
      $db->setQuery( $query );
      $result = $db->loadObject();


      if($result)
      {
         $parts   = explode( ':', $result->password );
         $crypt   = $parts[0];
         $salt   = @$parts[1];
         $testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);

         if ($crypt == $testcrypt) {
            $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
            $response->email = $user->email;
            $response->fullname = $user->name;
            $response->status = JAUTHENTICATE_STATUS_SUCCESS;
            $response->error_message = '';
         } else {
            $response->status = JAUTHENTICATE_STATUS_FAILURE;
            $response->error_message = 'Invalid password';
         }
      }
      else
      {


So we can see near the top, we're checking that the user has entered a password.
Where it says "$db->Quote( $credentials['username'] )" you'll want to replace this with the current logged in user's username

Code: Select all

$user = JFactory::getUser();
$username = $user->username;


have a look at this for what more info you can get from the user object (sadly, password isnt one of them!!)
http://docs.joomla.org/JFactory/getUser

Further down where the line starts "$testcrypt = JUserHelper... " you'll want to replace $credentials['password'] with the value the user entered in the form... retrievable with JRequest::get("password","POST") or something like

Then at the if ($crypt == $testcrypt) { comparrison, you'd probably only want to tell your user about it if it was wrong (of course:

Code: Select all

if ($crypt != $testcrypt) {
)

You can do this by enquing a message:

Code: Select all

$app =& JFactory::getApplication();
$app->enqueueMessage( "You entered the wrong password" );

then a mainframe redirect to the original page.

Phew! :pop
EmailAsUsername - Remove Usernames Joomla! Virtuemart And JomSocial registration http://www.lunarhotel.co.uk Many other extensions supported.

User avatar
dylanjh
Joomla! Ace
Joomla! Ace
Posts: 1823
Joined: Fri Sep 22, 2006 6:22 pm
Location: UK
Contact:

Re: Modify User Form to prevent e-mail changes

Postby dylanjh » Tue Feb 15, 2011 9:56 pm

Just remembered, you may also need to include the user helper, if its not already

Code: Select all

jimport('joomla.user.helper');
EmailAsUsername - Remove Usernames Joomla! Virtuemart And JomSocial registration http://www.lunarhotel.co.uk Many other extensions supported.

miamialbert
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Feb 15, 2011 11:18 am

Re: Modify User Form to prevent e-mail changes

Postby miamialbert » Wed Feb 16, 2011 1:18 am

Hi Dylan,

Thank you so much for the detailed instructions - I know how time consuming and boring it is. Although I learn more about PHP everyday - I'm pretty much at the cut and paste level.

I followed your instructions as best I could - but apparently not as well as I should have. So now essentially the form.php is the same as before - however with exposed php code.

You can check it out at: http://nectarcorp.com/albert_sandbox/ - you can login as: Albert/1234

when you navigate to "User Form Layout" you will see the out I am referring to.

Code: Select all

<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>

<script type="text/javascript">
<!--
   Window.onDomReady(function(){
      document.formvalidator.setHandler('passverify', function (value) { return ($('password').value == value); }   );
   });
// -->
</script>

<form action="<?php echo JRoute::_( 'index.php' ); ?>" method="post" name="userform" autocomplete="off" class="form-validate">
<?php if ( $this->params->def( 'show_page_title', 1 ) ) : ?>
   <div class="componentheading<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
      <?php echo $this->escape($this->params->get('page_title')); ?>
   </div>
<?php endif; ?>
<table cellpadding="5" cellspacing="0" border="0" width="100%">
<tr>
   <td>
      <label for="username">
         <?php echo JText::_( 'User Name' ); ?>:
      </label>
   </td>
   <td>
      <span><?php echo $this->user->get('username');?></span>
   </td>
</tr>
<tr>
   <td width="120">
      <label for="name">
         <?php echo JText::_( 'Your Name' ); ?>:
      </label>
   </td>
   <td>
     
<?php echo $this->escape($this->user->get( 'name' ));?>
   </td>
</tr>
<tr>
   <td>
      <label for="email">
         <?php echo JText::_( 'email' ); ?>:
      </label>
   </td>
   <td>
   <?php echo $this->escape($this->user->get( 'email' ));?>
   </td>
</tr>
<?php if($this->user->get('password')) : ?>
<tr>
   <td>
      <label for="password">
         <?php echo JText::_( 'Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-password" type="password" id="password" name="password" value="" size="40" />
   </td>
</tr>
<tr>
   <td>
      <label for="password2">
         <?php echo JText::_( 'Verify Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-passverify" type="password" id="password2" name="password2" size="40" />
   </td>
</tr>
<?php endif; ?>
</table>
<?php if(isset($this->params)) :  echo $this->params->render( 'params' ); endif; ?>
   <button class="button validate" type="submit" onclick="submitbutton( this.form );return false;"><?php echo JText::_('Save'); ?></button>
// Joomla does not like blank passwords
      if (empty($credentials['password']))
      {
         $response->status = JAUTHENTICATE_STATUS_FAILURE;
         $response->error_message = 'Empty password not allowed';
         return false;
      }

      // Initialize variables
      $conditions = '';

      // Get a database object
      $db =& JFactory::getDBO();

      $query = 'SELECT `id`, `password`, `gid`'
         . ' FROM `#__users`'
         . ' WHERE username=' . $user = JFactory::getUser();
$username = $user->username;
      $db->setQuery( $query );
      $result = $db->loadObject();


      if($result)
      {
         $parts   = explode( ':', $result->password );
         $crypt   = $parts[0];
         $salt   = @$parts[1];
         $testcrypt = JUserHelper::getCryptedPassword(JRequest::get("password","POST")

        if ($crypt != $testcrypt) {
            $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
            $response->email = $user->email;
            $response->fullname = $user->name;
            $response->status = JAUTHENTICATE_STATUS_SUCCESS;
            $response->error_message = '';
         } else {
            $response->status = JAUTHENTICATE_STATUS_FAILURE;
            $response->error_message = 'Invalid password';
         }
      }
      else
      {
   <input type="hidden" name="username" value="<?php echo $this->user->get('username');?>" />
   <input type="hidden" name="email" value="<?php echo $this->user->get('email');?>" />   
   <input type="hidden" name="name" value="<?php echo $this->user->get('name');?>" />     
   <input type="hidden" name="id" value="<?php echo $this->user->get('id');?>" />
   <input type="hidden" name="gid" value="<?php echo $this->user->get('gid');?>" />
   <input type="hidden" name="option" value="com_user" />
   <input type="hidden" name="task" value="save" />
$app =& JFactory::getApplication();
$app->enqueueMessage( "You entered the wrong password" );<?php echo JHTML::_( 'form.token' ); ?>

</form>


I hadn't thought to test the original modifications I made - but you were 100% correct. The form successfully submitted with blank passwords.

At this point - I do not care if the user does not have to enter their current pasword. The site will not contain any content that need to be so secure - and its a fair assumption that if someone is logged in, they have successfully entered a correct password.

So the only thing I need to correct is the blank pasword issue.

What do you say - can you help me out one more time? :-[

User avatar
dylanjh
Joomla! Ace
Joomla! Ace
Posts: 1823
Joined: Fri Sep 22, 2006 6:22 pm
Location: UK
Contact:

Re: Modify User Form to prevent e-mail changes

Postby dylanjh » Wed Feb 16, 2011 9:12 am

At the moment,
Im getting this:

Code: Select all

Fatal error: Can't use function return value in write context in /home/content/23/5831523/html/albert_sandbox/components/com_user/views/user/tmpl/form.php on line 74
EmailAsUsername - Remove Usernames Joomla! Virtuemart And JomSocial registration http://www.lunarhotel.co.uk Many other extensions supported.

miamialbert
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Feb 15, 2011 11:18 am

Re: Modify User Form to prevent e-mail changes

Postby miamialbert » Wed Feb 16, 2011 10:14 am

Sorry Dylan,

A friend of mine is working on it. I was just getting ready to post about it but did not get a chance to. The change he made to the form.php that is returning the fatal error si as follows:

Code: Select all

<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>

<script type="text/javascript">
<!--
   Window.onDomReady(function(){
      document.formvalidator.setHandler('passverify', function (value) { return ($('password').value == value); }   );
   });
// -->
</script>

<form action="<?php echo JRoute::_( 'index.php' ); ?>" method="post" name="userform" autocomplete="off" class="form-validate">
<?php if ( $this->params->def( 'show_page_title', 1 ) ) : ?>
   <div class="componentheading<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
      <?php echo $this->escape($this->params->get('page_title')); ?>
   </div>
<?php endif; ?>
<table cellpadding="5" cellspacing="0" border="0" width="100%">
<tr>
   <td>
      <label for="username">
         <?php echo JText::_( 'User Name' ); ?>:
      </label>
   </td>
   <td>
      <span><?php echo $this->user->get('username');?></span>
   </td>
</tr>
<tr>
   <td width="120">
      <label for="name">
         <?php echo JText::_( 'Your Name' ); ?>:
      </label>
   </td>
   <td>
      <?php echo $this->escape($this->user->get( 'name' ));?>
   </td>
</tr>
<tr>
   <td>
      <label for="email">
         <?php echo JText::_( 'email' ); ?>:
      </label>
   </td>
   <td>
      <?php echo $this->escape($this->user->get( 'email' ));?>
   </td>
</tr>
<?php if($this->user->get('password')) { ?>
<tr>
   <td>
      <label for="password">
         <?php echo JText::_( 'Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-password" type="password" id="password" name="password" value="" size="40" />
   </td>
</tr>
<tr>
   <td>
      <label for="password2">
         <?php echo JText::_( 'Verify Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-passverify" type="password" id="password2" name="password2" size="40" />
   </td>
</tr>
<?php } ?>
</table>
<?php if(isset($this->params)) { echo $this->params->render( 'params' ); } ?>
   <button class="button validate" type="submit" onclick="submitbutton( this.form );return false;"><?php echo JText::_('Save'); ?></button>
   <?php if(empty($credentials['password'])) {
         $response->status = JAUTHENTICATE_STATUS_FAILURE;
         $response->error_message = 'Empty password not allowed';
         return false;
      } ?>

   <input type="hidden" name="username" value="<?php echo $this->user->get('username');?>" />
   <input type="hidden" name="id" value="<?php echo $this->user->get('id');?>" />
   <input type="hidden" name="gid" value="<?php echo $this->user->get('gid');?>" />
   <input type="hidden" name="option" value="com_user" />
   <input type="hidden" name="task" value="save" />
   <?php echo JHTML::_( 'form.token' ); ?>
</form>

miamialbert
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Feb 15, 2011 11:18 am

Re: Modify User Form to prevent e-mail changes

Postby miamialbert » Wed Feb 16, 2011 10:16 am

Another note - he told me the following:

The problem with the form is going to be in the controller file <Joomla root>/components/com_user/controller.php

He's working on it now.

User avatar
dylanjh
Joomla! Ace
Joomla! Ace
Posts: 1823
Joined: Fri Sep 22, 2006 6:22 pm
Location: UK
Contact:

Re: Modify User Form to prevent e-mail changes

Postby dylanjh » Wed Feb 16, 2011 10:51 am

Ok, Well the user layout looks good so far. You have both password fields back.
EmailAsUsername - Remove Usernames Joomla! Virtuemart And JomSocial registration http://www.lunarhotel.co.uk Many other extensions supported.

miamialbert
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Feb 15, 2011 11:18 am

Joomls FIles we hacked

Postby miamialbert » Wed Feb 16, 2011 7:45 pm

Modification to: <Joomla root>/components/com_user/views/user/tmpl/form.php


Code: Select all

<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>

<script type="text/javascript">
<!--
   Window.onDomReady(function(){
      document.formvalidator.setHandler('passverify', function (value) { return ($('password').value == value); }   );
   });
// -->
</script>

<form action="<?php echo JRoute::_( 'index.php' ); ?>" method="post" name="userform" autocomplete="off" class="form-validate">
<?php if ( $this->params->def( 'show_page_title', 1 ) ) : ?>
   <div class="componentheading<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
      <?php echo $this->escape($this->params->get('page_title')); ?>
   </div>
<?php endif; ?>
<table cellpadding="5" cellspacing="0" border="0" width="100%">
<tr>
   <td>
      <label for="username">
         <?php echo JText::_( 'User Name' ); ?>:
      </label>
   </td>
   <td>
      <span><?php echo $this->user->get('username');?></span>
   </td>
</tr>
<tr>
   <td width="120">
      <label for="name">
         <?php echo JText::_( 'Your Name' ); ?>:
      </label>
   </td>
   <td>
      <?php echo $this->escape($this->user->get( 'name' ));?>
   </td>
</tr>
<tr>
   <td>
      <label for="email">
         <?php echo JText::_( 'email' ); ?>:
      </label>
   </td>
   <td>
      <?php echo $this->escape($this->user->get( 'email' ));?>
   </td>
</tr>
<?php if($this->user->get('password')) { ?>
<tr>
   <td>
      <label for="password">
         <?php echo JText::_( 'Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-password" type="password" id="password" name="password" value="" size="40" />
   </td>
</tr>
<tr>
   <td>
      <label for="password2">
         <?php echo JText::_( 'Verify Password' ); ?>:
      </label>
   </td>
   <td>
      <input class="inputbox validate-passverify" type="password" id="password2" name="password2" size="40" />
   </td>
</tr>
<?php } ?>
</table>
<?php if(isset($this->params)) { echo $this->params->render( 'params' ); } ?>
   <button class="button validate" type="submit" onclick="submitbutton( this.form );return false;"><?php echo JText::_('Save'); ?></button>

   <input type="hidden" name="username" value="<?php echo $this->user->get('username');?>" />
   <input type="hidden" name="id" value="<?php echo $this->user->get('id');?>" />
   <input type="hidden" name="gid" value="<?php echo $this->user->get('gid');?>" />
   <input type="hidden" name="option" value="com_user" />
   <input type="hidden" name="task" value="save" />
   <?php echo JHTML::_( 'form.token' ); ?>
</form>



Modification to <Joomla root>/components/com_user/controller.php


Code: Select all

<?php
/**
 * @version      $Id: controller.php 16385 2010-04-23 10:44:15Z ian $
 * @package      Joomla
 * @subpackage   Content
 * @copyright   Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
 * @license      GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.controller');

/**
 * User Component Controller
 *
 * @package      Joomla
 * @subpackage   Weblinks
 * @since 1.5
 */
class UserController extends JController
{
   /**
    * Method to display a view
    *
    * @access   public
    * @since   1.5
    */
   function display()
   {
      parent::display();
   }

   function edit()
   {
      global $mainframe, $option;

      $db      =& JFactory::getDBO();
      $user   =& JFactory::getUser();

      if ( $user->get('guest')) {
         JError::raiseError( 403, JText::_('Access Forbidden') );
         return;
      }

      JRequest::setVar('layout', 'form');

      parent::display();
   }

   function save()
   {
      // Check for request forgeries
      JRequest::checkToken() or jexit( 'Invalid Token' );

      $user    =& JFactory::getUser();
      $userid = JRequest::getVar( 'id', 0, 'post', 'int' );

      // preform security checks
      if ($user->get('id') == 0 || $userid == 0 || $userid <> $user->get('id')) {
         JError::raiseError( 403, JText::_('Access Forbidden') );
         return;
      }

      //clean request
      $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);
   
      // get the redirect
      $return = JURI::base();
      
      // do a password safety check
      if(strlen($post['password']) || strlen($post['password2'])) { // so that "0" can be used as password e.g.
         if($post['password'] != $post['password2']) {
            $msg   = JText::_('PASSWORDS_DO_NOT_MATCH');
            // something is wrong. we are redirecting back to edit form.
            // TODO: HTTP_REFERER should be replaced with a base64 encoded form field in a later release
            $return = str_replace(array('"', '<', '>', "'"), '', @$_SERVER['HTTP_REFERER']);
            if (empty($return) || !JURI::isInternal($return)) {
               $return = JURI::base();
            }
            $this->setRedirect($return, $msg, 'error');
            return false;
         }
      }

      if (empty($post['password']) || empty($post['password2'])) {
         $msg = JText::_('Empty password not allowed');
         $return = str_replace(array('"', '<', '>', "'"), '', @$_SERVER['HTTP_REFERER']);
         if (empty($return) || !JURI::isInternal($return)) {
            $return = JURI::base();
         }
         $this->setRedirect($return, $msg, 'error');
         return false;
      }

      // we don't want users to edit certain fields so we will unset them
      unset($post['gid']);
      unset($post['block']);
      unset($post['usertype']);
      unset($post['registerDate']);
      unset($post['activation']);

      // store data
      $model = $this->getModel('user');

      if ($model->store($post)) {
         $msg   = JText::_( 'Your settings have been saved.' );
      } else {
         //$msg   = JText::_( 'Error saving your settings.' );
         $msg   = $model->getError();
      }

      
      $this->setRedirect( $return, $msg );
   }

   function cancel()
   {
      $this->setRedirect( 'index.php' );
   }

   function login()
   {
      // Check for request forgeries
      JRequest::checkToken('request') or jexit( 'Invalid Token' );

      global $mainframe;

      if ($return = JRequest::getVar('return', '', 'method', 'base64')) {
         $return = base64_decode($return);
         if (!JURI::isInternal($return)) {
            $return = '';
         }
      }

      $options = array();
      $options['remember'] = JRequest::getBool('remember', false);
      $options['return'] = $return;

      $credentials = array();
      $credentials['username'] = JRequest::getVar('username', '', 'method', 'username');
      $credentials['password'] = JRequest::getString('passwd', '', 'post', JREQUEST_ALLOWRAW);

      //preform the login action
      $error = $mainframe->login($credentials, $options);

      if(!JError::isError($error))
      {
         // Redirect if the return url is not registration or login
         if ( ! $return ) {
            $return   = 'index.php?option=com_user';
         }

         $mainframe->redirect( $return );
      }
      else
      {
         // Facilitate third party login forms
         if ( ! $return ) {
            $return   = 'index.php?option=com_user&view=login';
         }

         // Redirect to a login form
         $mainframe->redirect( $return );
      }
   }

   function logout()
   {
      global $mainframe;

      //preform the logout action
      $error = $mainframe->logout();

      if(!JError::isError($error))
      {
         if ($return = JRequest::getVar('return', '', 'method', 'base64')) {
            $return = base64_decode($return);
            if (!JURI::isInternal($return)) {
               $return = '';
            }
         }

         // Redirect if the return url is not registration or login
         if ( $return && !( strpos( $return, 'com_user' )) ) {
            $mainframe->redirect( $return );
         }
      } else {
         parent::display();
      }
   }

   /**
    * Prepares the registration form
    * @return void
    */
   function register()
   {
      $usersConfig = &JComponentHelper::getParams( 'com_users' );
      if (!$usersConfig->get( 'allowUserRegistration' )) {
         JError::raiseError( 403, JText::_( 'Access Forbidden' ));
         return;
      }

      $user    =& JFactory::getUser();

      if ( $user->get('guest')) {
         JRequest::setVar('view', 'register');
      } else {
         $this->setredirect('index.php?option=com_user&task=edit',JText::_('You are already registered.'));
      }

      parent::display();
   }

   /**
    * Save user registration and notify users and admins if required
    * @return void
    */
   function register_save()
   {
      global $mainframe;

      // Check for request forgeries
      JRequest::checkToken() or jexit( 'Invalid Token' );

      // Get required system objects
      $user       = clone(JFactory::getUser());
      $pathway    =& $mainframe->getPathway();
      $config      =& JFactory::getConfig();
      $authorize   =& JFactory::getACL();
      $document   =& JFactory::getDocument();

      // If user registration is not allowed, show 403 not authorized.
      $usersConfig = &JComponentHelper::getParams( 'com_users' );
      if ($usersConfig->get('allowUserRegistration') == '0') {
         JError::raiseError( 403, JText::_( 'Access Forbidden' ));
         return;
      }

      // Initialize new usertype setting
      $newUsertype = $usersConfig->get( 'new_usertype' );
      if (!$newUsertype) {
         $newUsertype = 'Registered';
      }

      // Bind the post array to the user object
      if (!$user->bind( JRequest::get('post'), 'usertype' )) {
         JError::raiseError( 500, $user->getError());
      }

      // Set some initial user values
      $user->set('id', 0);
      $user->set('usertype', $newUsertype);
      $user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));

      $date =& JFactory::getDate();
      $user->set('registerDate', $date->toMySQL());

      // If user activation is turned on, we need to set the activation information
      $useractivation = $usersConfig->get( 'useractivation' );
      if ($useractivation == '1')
      {
         jimport('joomla.user.helper');
         $user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
         $user->set('block', '1');
      }

      // If there was an error with registration, set the message and display form
      if ( !$user->save() )
      {
         JError::raiseWarning('', JText::_( $user->getError()));
         $this->register();
         return false;
      }

      // Send registration confirmation mail
      $password = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
      $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email
      UserController::_sendMail($user, $password);

      // Everything went fine, set relevant message depending upon user activation state and display message
      if ( $useractivation == 1 ) {
         $message  = JText::_( 'REG_COMPLETE_ACTIVATE' );
      } else {
         $message = JText::_( 'REG_COMPLETE' );
      }

      $this->setRedirect('index.php', $message);
   }

   function activate()
   {
      global $mainframe;

      // Initialize some variables
      $db         =& JFactory::getDBO();
      $user       =& JFactory::getUser();
      $document   =& JFactory::getDocument();
      $pathway    =& $mainframe->getPathWay();

      $usersConfig = &JComponentHelper::getParams( 'com_users' );
      $userActivation         = $usersConfig->get('useractivation');
      $allowUserRegistration   = $usersConfig->get('allowUserRegistration');

      // Check to see if they're logged in, because they don't need activating!
      if ($user->get('id')) {
         // They're already logged in, so redirect them to the home page
         $mainframe->redirect( 'index.php' );
      }

      if ($allowUserRegistration == '0' || $userActivation == '0') {
         JError::raiseError( 403, JText::_( 'Access Forbidden' ));
         return;
      }

      // create the view
      require_once (JPATH_COMPONENT.DS.'views'.DS.'register'.DS.'view.html.php');
      $view = new UserViewRegister();

      $message = new stdClass();

      // Do we even have an activation string?
      $activation = JRequest::getVar('activation', '', '', 'alnum' );
      $activation = $db->getEscaped( $activation );

      if (empty( $activation ))
      {
         // Page Title
         $document->setTitle( JText::_( 'REG_ACTIVATE_NOT_FOUND_TITLE' ) );
         // Breadcrumb
         $pathway->addItem( JText::_( 'REG_ACTIVATE_NOT_FOUND_TITLE' ));

         $message->title = JText::_( 'REG_ACTIVATE_NOT_FOUND_TITLE' );
         $message->text = JText::_( 'REG_ACTIVATE_NOT_FOUND' );
         $view->assign('message', $message);
         $view->display('message');
         return;
      }

      // Lets activate this user
      jimport('joomla.user.helper');
      if (JUserHelper::activateUser($activation))
      {
         // Page Title
         $document->setTitle( JText::_( 'REG_ACTIVATE_COMPLETE_TITLE' ) );
         // Breadcrumb
         $pathway->addItem( JText::_( 'REG_ACTIVATE_COMPLETE_TITLE' ));

         $message->title = JText::_( 'REG_ACTIVATE_COMPLETE_TITLE' );
         $message->text = JText::_( 'REG_ACTIVATE_COMPLETE' );
      }
      else
      {
         // Page Title
         $document->setTitle( JText::_( 'REG_ACTIVATE_NOT_FOUND_TITLE' ) );
         // Breadcrumb
         $pathway->addItem( JText::_( 'REG_ACTIVATE_NOT_FOUND_TITLE' ));

         $message->title = JText::_( 'REG_ACTIVATE_NOT_FOUND_TITLE' );
         $message->text = JText::_( 'REG_ACTIVATE_NOT_FOUND' );
      }

      $view->assign('message', $message);
      $view->display('message');
   }

   /**
    * Password Reset Request Method
    *
    * @access   public
    */
   function requestreset()
   {
      // Check for request forgeries
      JRequest::checkToken() or jexit( 'Invalid Token' );

      // Get the input
      $email      = JRequest::getVar('email', null, 'post', 'string');

      // Get the model
      $model = &$this->getModel('Reset');

      // Request a reset
      if ($model->requestReset($email) === false)
      {
         $message = JText::sprintf('PASSWORD_RESET_REQUEST_FAILED', $model->getError());
         $this->setRedirect('index.php?option=com_user&view=reset', $message);
         return false;
      }

      $this->setRedirect('index.php?option=com_user&view=reset&layout=confirm');
   }

   /**
    * Password Reset Confirmation Method
    *
    * @access   public
    */
   function confirmreset()
   {
      // Check for request forgeries
      JRequest::checkToken() or jexit( 'Invalid Token' );

      // Get the input
      $token = JRequest::getVar('token', null, 'post', 'alnum');
      $username = JRequest::getVar('username', null, 'post');

      // Get the model
      $model = &$this->getModel('Reset');

      // Verify the token
      if ($model->confirmReset($token, $username) !== true)
      {
         $message = JText::sprintf('PASSWORD_RESET_CONFIRMATION_FAILED', $model->getError());
         $this->setRedirect('index.php?option=com_user&view=reset&layout=confirm', $message);
         return false;
      }
      $this->setRedirect('index.php?option=com_user&view=reset&layout=complete');
   }

   /**
    * Password Reset Completion Method
    *
    * @access   public
    */
   function completereset()
   {
      // Check for request forgeries
      JRequest::checkToken() or jexit( 'Invalid Token' );

      // Get the input
      $password1 = JRequest::getVar('password1', null, 'post', 'string', JREQUEST_ALLOWRAW);
      $password2 = JRequest::getVar('password2', null, 'post', 'string', JREQUEST_ALLOWRAW);

      // Get the model
      $model = &$this->getModel('Reset');

      // Reset the password
      if ($model->completeReset($password1, $password2) === false)
      {
         $message = JText::sprintf('PASSWORD_RESET_FAILED', $model->getError());
         $this->setRedirect('index.php?option=com_user&view=reset&layout=complete', $message);
         return false;
      }

      $message = JText::_('PASSWORD_RESET_SUCCESS');
      $this->setRedirect('index.php?option=com_user&view=login', $message);
   }

   /**
    * Username Reminder Method
    *
    * @access   public
    */
   function remindusername()
   {
      // Check for request forgeries
      JRequest::checkToken() or jexit( 'Invalid Token' );

      // Get the input
      $email = JRequest::getVar('email', null, 'post', 'string');

      // Get the model
      $model = &$this->getModel('Remind');

      // Send the reminder
      if ($model->remindUsername($email) === false)
      {
         $message = JText::sprintf('USERNAME_REMINDER_FAILED', $model->getError());
         $this->setRedirect('index.php?option=com_user&view=remind', $message);
         return false;
      }

      $message = JText::sprintf('USERNAME_REMINDER_SUCCESS', $email);
      $this->setRedirect('index.php?option=com_user&view=login', $message);
   }

   function _sendMail(&$user, $password)
   {
      global $mainframe;

      $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);

      if ( $useractivation == 1 ){
         $message = sprintf ( JText::_( 'SEND_MSG_ACTIVATE' ), $name, $sitename, $siteURL."index.php?option=com_user&task=activate&activation=".$user->get('activation'), $siteURL, $username, $password);
      } else {
         $message = sprintf ( JText::_( 'SEND_MSG' ), $name, $sitename, $siteURL);
      }

      $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);
         }
      }
   }
}
?>


Return to “Administration 1.5”

Who is online

Users browsing this forum: No registered users and 7 guests