Solved

Information not being updated in Cake PHP

Posted on 2010-09-16
11
586 Views
Last Modified: 2013-11-10
Hey, Folks!

I've got an admin page that allows the administrator to update a user's password info. While everything looks fine on the surface, the password isn't being changed in the database.

I'm new to CAKE, so I'm looking for an UPDATE statement or something familiar that I could attempt to troubleshoot and I'm not coming up with anything.

The code for the page is attached.

Any help would be very appreciated.
<?php

/**

 * @package eLivestockAuctions

 * @version 1.0

 * @author Scott Stanger <sstanger@highcorral.com>

 * @link http://www.highcorral.com/

 * @filesource

 */

?>



<?php echo $this->element('admin_sidebar'); ?>



<div id="main-column">

	<h2>Edit Member</h2>



	<div style="float: left;">

	

		<?php echo $form->create('User', array('url'=>'/admin/users/edit/'.$this->data['User']['id'], 'class' => 'simple', 'type'=>'file')); ?> 

		<?php echo $form->hidden('id', array('value'=>$this->data['User']['id'])); ?>

		<?php echo $form->hidden('ranchName', array('value'=>$this->data['User']['ranchName'])); ?>

		<?php echo $this->element('form_message'); ?>



		<p>* Denotes a required field.</p>

		

        <fieldset>

            <legend id="legend-0">Approved Member</legend>

            <?php

                echo $form->input('approved',  array( 

                    'type'	=> 'checkbox',

                    'label' => 'Approved', 

                    'div'=>'item', 

                    //'checked'=>(($this->data['User']['group_id'] == 2)?'checked':''),

                    'error' => array(

                        'wrap' => 'div', 

                        'class' => 'formerror'

                        ),

                    ));

            ?>

        </fieldset>

		

		<fieldset>

			<legend id="legend-1">Personal Information</legend>

			<?php

				echo $form->input('fullName',  array( 

					'label' => '* Full Name:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('driversLicense',  array( 

					'label' => '* Drivers License:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('dlState',  array( 

					'type' => 'select',

					'options' => $stateList,

					'label' => '* Drivers License State:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

					

				echo $form->input('dob',  array( 

					'label' => '* Date of Birth:', 

					'minYear' => date('Y') - 100,

					'maxYear' => date('Y') - 13,

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('screenName',  array( 

					'label' => '* Screen Name:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

			?>

		</fieldset>



		<fieldset>

			<legend id="legend-2">Ranch/Company Information</legend>

			<?php

				echo $form->input('ranchName',  array( 

					'label' => '* Ranch/Company Name:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

					

				echo $form->label('Ranch Profile: ') . $this->data['User']['ranchSlug'].'<br /><br />';

				echo $form->input('address1',  array( 

					'label' => '* Address:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('address2',  array( 

					'label' => ':', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('city',  array( 

					'label' => '* City:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('state',  array( 

					'type' => 'select',

					'options' => $stateList,

					'label' => '* State:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('zipcode',  array( 

					'label' => '* Zip Code:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

			?>

		</fieldset>

		

		<fieldset>

			<legend id="legend-3">Bank Information</legend>

			<?php

				echo $form->input('bankName',  array( 

					'label' => '* Bank Name:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('bankCity',  array( 

					'label' => '* City:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('bankState',  array( 

					'type' => 'select',

					'options' => $stateList,

					'label' => '* State:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('bankContact',  array( 

					'label' => '* Contact Name:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

			?>

		</fieldset>

		

		<fieldset>

			<legend id="legend-4">Contact Information</legend>

			<?php

				echo $form->input('homePhone',  array( 

					'label' => 'Home Phone:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('officePhone',  array( 

					'label' => 'Office Phone:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('mobilePhone',  array( 

					'label' => 'Mobile Phone:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('faxPhone',  array( 

					'label' => 'Fax Phone:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

			?>

		</fieldset>

		

		<fieldset>

			<legend id="legend-5">Login Information</legend>

			<?php

				echo $form->input('email',  array( 

					'label' => '* E-mail Address:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('new_password',  array( 

#					'value' => '',

					'type' => 'password',

					'label' => 'New Password:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

				echo $form->input('confirm_password',  array( 

#					'value' => '',

					'type' => 'password',

					'label' => 'Confirm Password:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));

			?>

		</fieldset>

				

		<fieldset>

			<legend id="legend-6">Seller Information</legend>

			<p>The following information only applies if the Member is designated as a Seller.</p>

			<?php

                echo $form->hidden('Upload.user_id', array('value'=>$this->data['User']['id']));



				echo $form->input('seller',  array( 

					'type'	=> 'checkbox',

					'label' => 'Member is a Seller:', 

					'div'=>'item', 

					'error' => array(

						'wrap' => 'div', 

						'class' => 'formerror'

						),

					));



                // ----------------------------------------------------------------------------------------------------

                // ---------------------------------------------------------------------------------------------------(

                // LOGO

                //

                    // Current Logo

                    echo 'Current Logo: ';

                    if (!empty($UploadedFiles[@$UploadedFilesKey.'0']))

                         echo $html->image("/files/thumbs/{$UploadedFiles[$UploadedFilesKey.'0']['name']}");

                    else echo 'Not uploaded.';



                    // New Logo

                    echo $form->input('Upload.0.file',  array( 

                        'type'	=> 'file',

                        'label' => 'Logo:', 

                        'div'=>'item', 

                        'error' => array(

                            'wrap' => 'div', 

                            'class' => 'formerror'

                            ),

                        ));

                //

                // )---------------------------------------------------------------------------------------------------

                // ----------------------------------------------------------------------------------------------------





                // ----------------------------------------------------------------------------------------------------

                // ---------------------------------------------------------------------------------------------------(

                // PICTURE

                //

                    // Current Picture

                    echo "Current Picture: ";

                    if (!empty($UploadedFiles[@$UploadedFilesKey.'1']))

                         echo $html->image("/files/thumbs/{$UploadedFiles[$UploadedFilesKey.'1']['name']}");

                    else echo 'Not uploaded.';



                    // New Picture

                    echo $form->input('Upload.1.file',  array( 

                        'type'	=> 'file',

                        'label' => 'Picture:', 

                        'div'=>'item', 

                        'error' => array(

                            'wrap' => 'div', 

                            'class' => 'formerror'

                            ),

                        ));

                //

                // )---------------------------------------------------------------------------------------------------

                // ----------------------------------------------------------------------------------------------------





                // ----------------------------------------------------------------------------------------------------

                // ---------------------------------------------------------------------------------------------------(

                // BROCHURE

                //

                    //Current Brochure

                    echo "Current Brochure: ";

                    if (!empty($UploadedFiles[@$UploadedFilesKey.'2']))

                         echo $html->link($UploadedFiles[$UploadedFilesKey.'2']['name'], "/files/{$UploadedFiles[$UploadedFilesKey.'2']['name']}");

                    else echo 'Not uploaded.';



                    // New Brochure

                    echo $form->input('Upload.2.file',  array( 

                        'type'	=> 'file',

                        'label' => 'Brochure:', 

                        'div'=>'item', 

                        'error' => array(

                            'wrap' => 'div', 

                            'class' => 'formerror'

                            ),

                        ));

                //

                // )---------------------------------------------------------------------------------------------------

                // ----------------------------------------------------------------------------------------------------





                // ----------------------------------------------------------------------------------------------------

                // ---------------------------------------------------------------------------------------------------(

                // VIDEO

                //

                    // Current Video

                    /*

                    echo "Current Video: ";

                    if (!empty($UploadedFiles[$UploadedFilesKey.'3']))

                         echo $html->link($UploadedFiles[$UploadedFilesKey.'3']['name'], "/files/{$UploadedFiles[$UploadedFilesKey.'3']['name']}");

                    else echo 'Not uploaded.';

                    */



                    // New Video (.flv only)

                    echo $form->input('videoClip',  array( 

                        'label' => 'Video Clip Name:', 

                        'div'=>'item',

                        'error' => array(

                            'wrap' => 'div', 

                            'class' => 'formerror'

                            ),

                        ));

                //

                // )---------------------------------------------------------------------------------------------------

                // ----------------------------------------------------------------------------------------------------





			?>

		</fieldset>

				

		<fieldset class="buttons">

			<?php echo $form->submit('Update'); ?> 

		</fieldset>



		<?php echo $form->end(); ?>



		<script type="text/javascript">

		/* <![CDATA[ */

			document.getElementById('UserFullName').focus();

		/* ]]> */

		</script>



		<?php #pr($this->data); ?>

	</div>

	<div style="clear:both;"></div>



</div>

Open in new window

0
Comment
Question by:brucegust
  • 7
  • 3
11 Comments
 
LVL 40

Expert Comment

by:RQuadling
ID: 33701174
You probably won't.

Instead, you need to retrieve the user as an object. Use the object's method to amend the password and then save the user.

The User object will know how to save all the data you supply to it.

http://book.cakephp.org/view/1031/Saving-Your-Data should help you.
0
 

Author Comment

by:brucegust
ID: 33701867
RQuadling, I'm hoping you've got a couple of minutes because I need to figure this out.

A couple of pointers, if you're willing:

When I edit any of the other information on the form, the next page that I get is one that says, "User has been saved!" at the very top. That message doesn't appear if I make any changes to the password. If I change the first name and just the first name - fine. If I change the first name and the password, no changes are made.

When I look at the admin_edit.ctp page there is a "#" sign to the left of the password and confirm_password fileds. Does that mean anything?

echo $form->input('new_password',  array(
#                              'value' => '',
                        'type' => 'password',
                        'label' => 'New Password:',
                        'div'=>'item',
                        'error' => array(
                              'wrap' => 'div',
                              'class' => 'formerror'
                              ),
                        ));
                  echo $form->input('confirm_password',  array(
#                              'value' => '',
                        'type' => 'password',
                        'label' => 'Confirm Password:',
                        'div'=>'item',
                        'error' => array(
                              'wrap' => 'div',
                              'class' => 'formerror'

                              ),
                        ));

Reason being is that the editing function does work, it just falters when you add anything to the new password and confirm password field. Is the fact that there's a pound sign to the left of each of those values significant? I removed them to see if it would have any impact and it didn't, but I still wouldn't mind some additional commentary if you think it's something noteworthy.

Next, every tutorial that I've looked at has me thinking there's going to be a "post" and an "action" method somewhere and there isn't. Thus, I'm clueless as to where the actual code is that's facilitating the saving of the data. I can't help but think that my problem is with that code. Where would I look for that object? Is the answer in the above syntax and I'm just not seeing it?
0
 

Author Comment

by:brucegust
ID: 33701944
I found it!

I went to the controller directory and found the script that updates the password. Do you see anything that would prevent the new password from being saved?

public function admin_edit($id=null)
      {
            $this->User->id = (int)$id;
        $user = $this->User->read();
            if (empty($this->data)) {

                  $this->data = $user;
                  $this->data['UploadTypes'] = Set::combine($this->data['Upload'], '{n}.type', '{n}');
                  if (empty($this->data)) {

                        $this->pageTitle = 'Member Does Not Exist';

                  } else {

                        $this->pageTitle = $this->data['User']['fullName'];
                  }
            } else {

                  // are we changing the password?
                  if (!empty($this->data['User']['new_password'])) {

                        // Verify that both passwords match
                        if ($this->data['User']['new_password'] == $this->data['User']['confirm_password']) {

                              $this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);

                        } else {

                              // Did not properly confirm password
                              $this->set('error', 'ERROR: Please confirm your Password.');
                        }
            } else {

/*
                if ($this->data['User']['approved']) {
                    if ($user['User']['group_id'] != 1)
                        $this->data['User']['group_id'] = 2;
                } else {
                    if ($user['User']['group_id'] != 1)
                        $this->data['User']['group_id'] = 3;
                }
*/
                $this->doSave('User', array('uploadOptions'=>$this->uploadOptions, 'create'=>false));
            }

            #// Throw in the group_id for good measure (we'll need it in the view)
            #$this->User->contain();
            #$this->data['User']['group_id'] = $this->User->field('group_id', array('User.`id`'=>$this->User->id));
            }

        $this->set('UploadedFiles', Set::combine($this->data['Upload'], '{n}.derived_id', '{n}'));
        $this->set('UploadedFilesKey', "user$id-memberinfo");

      } // admin_edit()
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 33702241
The password will be updated when ...

1 - The new_password is not empty.
2 - The new_password and the confirm_password agree.

Do you ask for 2 passwords? (new_password and confirm_password)?


Just before the line ...


            // are we changing the password?

can you add ...

echo '
';
var_dump($this->data['User']);
echo '

Open in new window

';

What output do you have?



The # is a single line comment.

<?php
// The next line will NOT generate a divide by zero error due to the # commenting the line.
# echo 1 / 0;
?>

0
 

Author Comment

by:brucegust
ID: 33702344
Yup, I am asking for two passwords (BTW, I didn't build this page, I've just been tasked with cleaning up some of the code that's not firing correctly, so if I sound like I'm not sure about what's going on, that's part of it.)

Here's the output you asked for:

array(26) {
  ["id"]=>
  string(2) "22"
  ["ranchName"]=>
  string(13) "brucegust.com"
  ["approved"]=>
  string(1) "1"
  ["fullName"]=>
  string(16) "Bruce David Gust"
  ["driversLicense"]=>
  string(4) "4587"
  ["dlState"]=>
  string(2) "tn"
  ["dob"]=>
  array(3) {
    ["month"]=>
    string(2) "08"
    ["day"]=>
    string(2) "26"
    ["year"]=>
    string(4) "1963"
  }
  ["screenName"]=>
  string(9) "brucegust"
  ["address1"]=>
  string(21) "1503 Danville Circle "
  ["address2"]=>
  string(0) ""
  ["city"]=>
  string(17) "Thompsons Station"
  ["state"]=>
  string(2) "tn"
  ["zipcode"]=>
  string(5) "37179"
  ["bankName"]=>
  string(15) "First Tennessee"
  ["bankCity"]=>
  string(8) "Franklin"
  ["bankState"]=>
  string(2) "tn"
  ["bankContact"]=>
  string(10) "Bruce Gust"
  ["homePhone"]=>
  string(12) "615.595.4219"
  ["officePhone"]=>
  string(12) "615.618.2059"
  ["mobilePhone"]=>
  string(12) "615.618.2059"
  ["faxPhone"]=>
  string(0) ""
  ["email"]=>
  string(19) "bruce@brucegust.com"
  ["new_password"]=>
  string(6) "[EDITED]"
  ["confirm_password"]=>
  string(6) "[EDITED]"
  ["seller"]=>
  string(1) "0"
  ["videoClip"]=>
  string(0) ""
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:brucegust
ID: 33702410
Richard, I'm thinking this looks like a slam dunk in that the system is "seeing" new_password and confirm_password.

Maybe it's a permissions thing?

In any event, I'm sending you the whole controllers doc just so you've got a comprehensive snapshot of what's happening.
<?php

/**

 * @package eLivestockAuctions

 * @version 1.0

 * @author Scott Stanger <sstanger@highcorral.com>

 * @link http://www.highcorral.com/

 * @filesource

 */



/**

 * 

 */

class UsersController extends AppController 

{

	/**

	 * The name of this controller

	 *

	 * @access public

	 * @var array

	 */

    public $name = 'Users';

	

	/**

	 * List of models this controller uses

	 *

	 * @access public

	 * @var array

	 */

	public $uses = array('User', 'Upload');

	

	/**

	 * List of components

	 *

	 * @access public

	 * @var array

	 */

	public $components = array('FileUpload.FileUpload', 'PhpThumb');



    /**

     * uploadOptions

     * 

     * @var array

     * @access private

     */

    private $uploadOptions = array(

        'numberUploads'   => 3             ,

        'derived_id_part' => 'memberinfo'  ,

        'thumbs'          => array(0, 1, 2),

    );

	

	/**

	 *

	 */

	public function beforeFilter()

	{

		parent::beforeFilter();

		$this->Auth->allow(array('login', 'logout', 'register', 'remind', 'resetpassword'));

		$this->set('stateList', Configure::read('stateList'));

	}

	

	/**

	 * This is called if the user is logged in.

	 *

	 * @return boolean

	 */	

	public function isAuthorized() { return true; }



	

	/**

	 * Log In action

	 */

    public function login()

	{

		//-- code inside this function will execute only when autoRedirect is set to false (i.e. in a beforeFilter).



		if (!empty($this->data)) 

		{

			// Form has been posted

			$ok = true;

			if ($user = $this->Auth->user()) 

			{

                if ($user['User']['active'] == 0) 

				{

                    $this->set('error', 'Invalid email / password combination. Please try again. (user is not active)');

					$ok = false;

                }

				

				if ($ok && $user['User']['approved'] == 0) 

				{

                    $this->set('error', 'Your account is pending approval.');

					$ok = false;

                }



				if ($ok && !empty($this->data['User']['remember_me']))

				{

					$cookie = array(

						'email'		=> $this->data['User']['email'],

						'password' 	=> $this->data['User']['password'],

					);

					$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');

					unset($this->data['User']['remember_me']);

				}

				

				if ($ok)

				{

					$this->redirect($this->data['User']['redirect']);

				}

				else

				{

                    $this->Auth->logout();

					$this->set('redirect', $this->data['User']['redirect']);

				}

				

			}

			else

			{

				// Log In failed

				$this->set('error', 'Invalid e-mail / password combination.  Please try again. (auth failed)');

				$this->set('redirect', $this->data['User']['redirect']);

			}

		}

		else

		{

			// Form was not posted



			// If a user is already logged in then they should not be here

			if ($this->Auth->user())

			{

				$this->redirect('/');

			}



			$redirect = empty($_SERVER['HTTP_REFERER'])?'/':$_SERVER['HTTP_REFERER'];

			

			// There are certain pages we do not want to redirect to

			if (substr_count($redirect, 'logout') > 0 || substr_count($redirect, 'resetpassword') > 0 || substr_count($redirect, 'remind') > 0)

			{

				$redirect = '/';

			}

			$this->set('redirect', $redirect);

		}



	} // login()

	

	/**

	 * Log Out action

	 */

    public function logout()

	{

		$this->Cookie->delete('Auth.User');

		$this->Auth->logout();

		// redirect the user back to the page he was just on

#		$this->flash('You have successfully Logged Out.', $_SERVER['HTTP_REFERER']);

		$this->redirect($_SERVER['HTTP_REFERER']);

		

	} // logout()

	

	/**

	 * Register action

	 */

	public function register()

	{

		$this->pageTitle = 'Register with eLivestock Auctions';

		$this->selectedMenu = 'register';

		

		if (!empty($this->data)) 

		{



			if ($this->data['User']['password'] != $this->Auth->password($this->data['User']['confirm_password']))

			{

				$this->set('error', 'ERROR: Please confirm your Password.');

				$this->set('redirect', $this->data['User']['redirect']);

			}

			else

			{

                // The user MUST start un-approved!

                $this->data['User']['approved'] = 0;



				$this->User->create();

				$user = $this->User->save($this->data);

				if (empty($user))

				{

					// Could not save

					$this->set('error', 'ERROR: Unable to create account.');

					$this->set('redirect', $this->data['User']['redirect']);

				}

				else

				{

					// We do not want to automatically log the user in!

					// The admin must first approve the new member

					#if ($this->Auth->login($user) === true)

					#{

					#	$this->Session->write('User', $user);	// sign them in

					#}

					

					// TODO: Send a welcome email



					#$this->redirect($this->data['User']['redirect']);

					$this->set('thankyou', true);

				}

			}

		}

		else

		{

			// If a user is already logged in then they should not be here

			if ($this->Auth->user())

			{

				$this->redirect('/');

			}



			// Capture the page they came from so we can redirect back there after they register

			$redirect = empty($_SERVER['HTTP_REFERER'])?'/':$_SERVER['HTTP_REFERER'];

			$this->set('redirect', $redirect);

		}



        $this->data['Page']['id'] = 4; // HARD CODED.  THIS IS NOT DYNAMIC AND CANNOT BE CHANGED.



	} // register()





    /**

     * bidHistory

     * 

     * @param integer $lotId 

     * @access public

     * @return void

     */

    public function bidHistory($lotId) {



        $lotId = (int)$lotId; // Sanitize the incoming ID

        if ($lotId < 1) {

            $this->Session->setFlash('Invalid Lot selected for Bid history');

            return $this->redirect($this->referer());

        }



        $this->loadModel('Lot');

        $this->Lot->contain();

        $lot = $this->Lot->findById($lotId);



        $conditions = array(

            'Bid.`lot_id`'  => $lotId,

            'Bid.`user_id`' => $this->loggedInUser['User']['id'],

        );

        $this->page('Bid', 'created', $conditions, array('contain'=>false), 'DESC');

        $this->set('lot', $lot);

    }



    /**

     * auctionHistory

     * 

     * @param string $type 

     * @access public

     * @return void

     */

    public function auctionHistory($type='rta') {



        // Force the type...

        if ($type != 'rta' && $type != 'esa')

            $type = 'rta';



        // TODO : This function could be modified to show ANY user's bid history, by changing the user below...

        //        By say, allowing an admin to pass in a user id and doing a lookup on that id...

        $user = $this->loggedInUser;





        // ----------------------------------------------------------------------------------------------------

        // ---------------------------------------------------------------------------------------------------(

        // Build options for the pager...

        //

            $options = array(

                'contain' => false,

                'conditions' => array(

                    'User.`id`'      => $user['User']['id'],

                    'Auction.`type`' => $type,

                ),

                'joins' => array(

                    array(

                        'table'      => 'users',

                        'alias'      => 'User' ,

                        'type'       => 'INNER',

                        'conditions' => array(

                            'User.`id` = Bid.`user_id`',

                        ),

                    ),

                    array(

                        'table'      => 'lots',

                        'alias'      => 'Lot' ,

                        'type'       => 'LEFT',

                        'conditions' => array(

                            'Lot.`id` = Bid.`lot_id`',

                        ),

                    ),

                    array(

                        'table'      => 'auctions',

                        'alias'      => 'Auction' ,

                        'type'       => 'LEFT',

                        'conditions' => array(

                            'Auction.`id` = Lot.`auction_id`',

                        ),

                    ),

                ),

                'fields' => array(

                    'Auction.id'  ,

                    'Auction.name',

                    'Auction.type',

                    'Lot.id'      ,

                    'Lot.lotName' ,

                    'Lot.sold'    ,

                    'MAX(Bid.`amount`) As MaxBid',

                    'COUNT(Bid.`id`) AS BidCount',

                ),

                'group' => 'Auction.`id`, Lot.`id`',

                'order' => 'Auction.`id` DESC, Lot.`id` DESC',

            );

        //

        // )---------------------------------------------------------------------------------------------------

        // ----------------------------------------------------------------------------------------------------





        $this->page('Bid', 'id', array(), $options, '', PROFILE_AUCTION_LIST_LIMIT, true, true);



        $this->set('user', $user);

        $this->set('type', $type);

    }



    /**

     * profile 

     * 

     * @access public

     * @return void

     */

	public function profile()

	{

        // Basic Profile info

        $this->User->contain('Classified');

        $user = $this->User->read(null, $this->loggedInUser['User']['id']);

        $this->set('user', $user);



        if ($user['User']['approved'] == 1) {



            // ----------------------------------------------------------------------------------------------------

            // ---------------------------------------------------------------------------------------------------(

            // Get the user's bid information...

            //

                $this->loadModel('Bid');

                $this->Bid->contain();

                $options = array(

                    'conditions' => array(

                        'User.`id`'      => $this->loggedInUser['User']['id'],

                        'Auction.`type`' => 'rta',

                    ),

                    'joins' => array(

                        array(

                            'table'      => 'users',

                            'alias'      => 'User' ,

                            'type'       => 'INNER',

                            'conditions' => array(

                                'User.`id` = Bid.`user_id`',

                            ),

                        ),

                        array(

                            'table'      => 'lots',

                            'alias'      => 'Lot' ,

                            'type'       => 'LEFT',

                            'conditions' => array(

                                'Lot.`id` = Bid.`lot_id`',

                            ),

                        ),

                        array(

                            'table'      => 'auctions',

                            'alias'      => 'Auction' ,

                            'type'       => 'LEFT',

                            'conditions' => array(

                                'Auction.`id` = Lot.`auction_id`',

                            ),

                        ),

                    ),

                    'fields' => array(

                        'Auction.id'  ,

                        'Auction.name',

                        'Auction.type',

                        'Lot.id'      ,

                        'Lot.lotName' ,

                        'Lot.sold'    ,

                        'MAX(Bid.`amount`) As MaxBid',

                        'COUNT(Bid.`id`) AS BidCount',

                    ),

                    'group' => 'Auction.`id`, Lot.`id`',

                    'order' => 'Auction.`id` DESC, Lot.`id` DESC',

                    'limit' => PROFILE_AUCTION_LIST_LIMIT,

                );

                $rtaData = $this->Bid->find('all', $options);







                $this->Bid->contain();

                $options['conditions']['Auction.`type`'] = 'esa';

                $esaData = $this->Bid->find('all', $options);

            //

            // )---------------------------------------------------------------------------------------------------

            // ----------------------------------------------------------------------------------------------------



            // Organize the Bid data in an easy to loop manner...

            //  ... Yeah, let's see the Set class do this!  ;)

            $bidData = array();

            $i = 0;

            foreach ($rtaData as $d) {

                $bidData['rta'][$d['Auction']['id']]['Auction']                                = $d['Auction'];

                $bidData['rta'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]                  = $d['Lot'];

                $bidData['rta'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]['MaxBid']        = $d[0]['MaxBid'];

                $bidData['rta'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]['BidCount']      = $d[0]['BidCount'];

                $bidData['rta'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]['TotalBidCount'] = $this->Bid->find('count', array('conditions' => array('lot_id'=>$d['Lot']['id'])));

                $i++;

            }

            $bidData['rta']['recordCount'] = $i;



            $i = 0;

            foreach ($esaData as $d) {

                $bidData['esa'][$d['Auction']['id']]['Auction']                                = $d['Auction'];

                $bidData['esa'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]                  = $d['Lot'];

                $bidData['esa'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]['MaxBid']        = $d[0]['MaxBid'];

                $bidData['esa'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]['BidCount']      = $d[0]['BidCount'];

                $bidData['esa'][$d['Auction']['id']]['Lots'][$d['Lot']['id']]['TotalBidCount'] = $this->Bid->find('count', array('conditions' => array('lot_id'=>$d['Lot']['id'])));

                $i++;

            }

            $bidData['esa']['recordCount'] = $i;



            

            $this->Bid->contain();

            $options = array(

                'conditions' => array(

                    'Auction.`user_id`' => $user['User']['id'],

                ),

                'joins' => array(

                    array(

                        'table'      => 'lots',

                        'alias'      => 'Lot' ,

                        'type'       => 'LEFT',

                        'conditions' => array(

                            'Lot.`id` = Bid.`lot_id`',

                        ),

                    ),

                    array(

                        'table'      => 'auctions',

                        'alias'      => 'Auction' ,

                        'type'       => 'LEFT',

                        'conditions' => array(

                            'Auction.`id` = Lot.`auction_id`',

                        ),

                    ),

                ),

                'fields' => array(

                    'Auction.`id`'       ,

                    'Auction.`name`'     ,

                    'Auction.`completed`',

                    'Lot.`id`'           ,

                    'Lot.`lotName`'      ,

                    'Lot.`sold`'         ,

                    'MAX(Bid.`amount`) As MaxBid',

                    'COUNT(Bid.`id`) AS BidCount',

                ),

                'group' => 'Auction.`id`',

                'order' => 'Auction.`id` DESC',

                'limit' => PROFILE_AUCTION_LIST_LIMIT,

            );

            $myAuctions = $this->Bid->find('all', $options);



            // Get the Classified Ads





            $this->data['MyAuctions'] = $myAuctions;

            $this->data['BidData'   ] = $bidData   ;

        }

	} // profile()





	/**

	 * edit

	 * Edit a Member.  We don't need to pass in the ID since we will grab

	 * the user details from Auth.

	 *

     * @access public

	 * @param int $id

     * @return void

	 */

	public function edit()

	{

		if (!empty($this->data))

		{

			// If the email address has changed we need to ensure it is still unique

			$valid = true;

			if ($this->data['User']['email'] != $this->data['User']['original_email'])

			{

				$existingUser = $this->User->find(array('User.email'=>$this->data['User']['email']));

				if (!empty($existingUser))

				{

					$this->set('error', 'ERROR: The email address already exists.  Please choose another one.');

					$valid = false;

				}

			}

			if ($valid)

			{

				// are we changing the password?

				if (!empty($this->data['User']['new_password']))

				{

					// Verify that both passwords match

					if ($this->data['User']['new_password'] == $this->data['User']['confirm_password'])

					{

						$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);

					}

					else

					{

						// Did not properly confirm password

						$this->set('error', 'ERROR: Please confirm your Password.');

						$valid = false;

					}

				}

			}

			if ($valid)

			{

				// By setting the user's id, Cake will do an update instead of a create.

				$this->User->id = $this->data['User']['id'];



				if ($this->User->save($this->data)) 

				{

					$user = $this->User->find(array('User.id'=>$this->data['User']['id']), array('User.email', 'User.password'));

					$login = array(

						'email'		=> $user['User']['email'],

						'password' 	=> $user['User']['password'],

					);

					$this->Auth->login($login);

					

					// If there is a cookie we need to update it

					if (!is_null($this->Cookie->read('Auth.User')))

					{

						$this->Cookie->write('Auth.User', $login, true, '+2 weeks');

					} 

					$this->set('success', 'Your profile has been updated.');

				}

				else

				{

					// Update failed

					$this->set('error', 'ERROR: Unable to update your profile.');

				}

			}

		}

		else

		{

			// First time through -- pre-load the form

			$this->data = $this->Auth->user();

			$this->data['User']['original_email'] = $this->data['User']['email'];

			$this->pageTitle = $this->data['User']['fullName'];

		}

		

	} // edit()





    /**

     * admin_index

     * 

     * @access public

     * @return void

     */

    public function admin_index() {



        // 1. Check to see if we are "deleting" a user (and do it)

        $this->checkDelete('User', '', 'user\'s "active" status', '', '', true); // See app_controller.php for the definition of this function





        // ---------------------------------------------------------------------------

        // --------------------------------------------------------------------------(

        // 2. Check to see if an action was requested

        //    (activate a user or approve them)...

        //

            if (Set::check($this->data, 'ActivateSuspend.action')) {



                // Here's the User's id...

                $data = array('id' => (int)$this->data['ActivateSuspend']['userId']);



                // If we are approving

                if ($this->data['ActivateSuspend']['action'] == 'approve')

                    $data['approved'] = 1;

                // If we are activating

                elseif ($this->data['ActivateSuspend']['action'] == 'activate')

                    $data['active'] = 1;



                // Go!

                $this->User->save($data);

            }

        //

        // )--------------------------------------------------------------------------

        // ---------------------------------------------------------------------------





        // ----------------------------------------------------------------------------------------------------------------------

        // ---------------------------------------------------------------------------------------------------------------------(

        // 3. Build any filtering conditions

        //

            $conditions = array();

            if ($filterData = $this->getFilterData('MemberList')) {



                $filterFields = array('User' => array(

                    'string' => array(

                        'screenName',

                        'ranchName' ,

                        'fullName'  ,

                        'email'     ,

                    ),

                ));

                $conditions = $this->buildFilterConditions($filterData, $filterFields); // See app_controller.php for the definition of this function



                // Active

                if (!empty($filterData['active'])) {

                    // Yes

                    if ((int)$filterData['active'] == 1)  // 1 is the value sent from the FORM

                        $conditions['User.`active`'] = 1; // 1 is also the value in the DATABASE

                    // No

                    elseif ((int)$filterData['active'] == 2) // 2 is the value sent from the FORM

                        $conditions['User.`active`'] = 0;    // 0 is the value in the DATABASE

                }



                // Approved

                if (!empty($filterData['approved'])) {

                    // Yes

                    if ((int)$filterData['approved'] == 1)  // 1 is the value sent from the FORM

                        $conditions['User.`approved`'] = 1;

                    // No

                    elseif ((int)$filterData['approved'] == 2) // 2 is the value sent from the FORM

                        $conditions['User.`approved`'] = 0;    // 0 is the value in the DATABASE

                }

            }

        //

        // )---------------------------------------------------------------------------------------------------------------------

        // ----------------------------------------------------------------------------------------------------------------------





        // 4. Do the filtering & pagination

        $this->page('User', 'fullName', $conditions, array('contain'=>false)); // See app_controller.php for the definition of this function

    }



    /**

     * admin_add 

     *

     * Add a Member (via Admin)

     * 

     * @access public

     * @return void

     */

    public function admin_add() {



        $this->pageTitle = 'Add a Member';



        if (!empty($this->data)) {



            // -------------------------------------------------------------------------------------------------------

            // ------------------------------------------------------------------------------------------------------(

            // 1. Check the Password fields

            //

	



                if (!empty($this->data['User']['new_password']))

                {

                    // Verify that both passwords match

                    if ($this->data['User']['new_password'] == $this->data['User']['confirm_password'])

                    {

                        $this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);

                    }

                    else

                    {

                        // Did not properly confirm password

                        $this->set('error', 'ERROR: Please confirm your Password.');

                        return;

                    }

                }

            //

            // )------------------------------------------------------------------------------------------------------

            // -------------------------------------------------------------------------------------------------------





            // 2. Save the user

            $this->doSave('User', array('uploadOptions'=>$this->uploadOptions));

        }

    }



	/**

	 * admin_edit

     *

	 * Edit a Member (via Admin)

	 *

     * @access public

	 * @param integer $id

     * @return void

	 */

	public function admin_edit($id=null)

	{

		$this->User->id = (int)$id;

        $user = $this->User->read();

		if (empty($this->data)) {



			$this->data = $user;

			$this->data['UploadTypes'] = Set::combine($this->data['Upload'], '{n}.type', '{n}');

			if (empty($this->data)) {



				$this->pageTitle = 'Member Does Not Exist';



			} else {



				$this->pageTitle = $this->data['User']['fullName'];

			}

		} else {

		echo '<pre>';

var_dump($this->data['User']);

echo '</pre>';

			// are we changing the password?

			if (!empty($this->data['User']['new_password'])) {



				// Verify that both passwords match

				if ($this->data['User']['new_password'] == $this->data['User']['confirm_password']) {



					$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);



				} else {



					// Did not properly confirm password

					$this->set('error', 'ERROR: Please confirm your Password.');

				}

            } else {



/*

                if ($this->data['User']['approved']) {

                    if ($user['User']['group_id'] != 1)

                        $this->data['User']['group_id'] = 2;

                } else {

                    if ($user['User']['group_id'] != 1)

                        $this->data['User']['group_id'] = 3;

                }

*/				$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);	

                $this->doSave('User', array('uploadOptions'=>$this->uploadOptions, 'create'=>false));

            }



            #// Throw in the group_id for good measure (we'll need it in the view)

            #$this->User->contain();

            #$this->data['User']['group_id'] = $this->User->field('group_id', array('User.`id`'=>$this->User->id));

		}



        $this->set('UploadedFiles', Set::combine($this->data['Upload'], '{n}.derived_id', '{n}'));

        $this->set('UploadedFilesKey', "user$id-memberinfo");



	} // admin_edit()





    /**

     * admin_ajaxlist

     * 

     * @access public

     * @return void

     */

    public function admin_ajaxlist() {



        $search = $this->params['form']['value'];



        $users = $this->User->find('all',

            array(

                'conditions' => array(

                    'OR' => array(

                        'User.`fullName` LIKE'   => $this->sanit($search).'%',

                        'User.`screenName` LIKE' => $this->sanit($search).'%',

                        'User.`email` LIKE'      => $this->sanit($search).'%',

                    ),

                ),

                'fields' => array(

                    'User.`id`'        ,

                    'User.`fullName`'  ,

                    'User.`screenName`',

                    'User.`email`'     ,

                ),

                'contain' => false,

                'limit'   => 5    ,

                'order'   => 'User.`fullName` ASC, User.`screenName` ASC, User.`email` ASC',

            )

        );

        $this->set('users', $users);

    }



	

	/**

	 * Password Request action

	 * Since passwords are encrypted in the database we cannot recover them.  Therefore,

	 * We will send an email to the user (provided they enter the correct email address)

	 * with a special URL.  When they click this URL we will generate a new password

	 * for them.

	 */

	public function remind()

	{

		if (!empty($this->data)) 

		{

			$user = $this->User->findByEmail($this->data['User']['email']);



			if (empty($user))

			{

				// Could not find the user

				$this->set('error', 'ERROR: That email address is not on file.');

				$this->set('redirect', $this->data['User']['redirect']);

			}

			else

			{

				// If the user has already made a request but has not reset his password yet

				// then there will be a "resetcode" in his user record.

				// If not, then we create one and store it.

				if (empty($user['User']['resetcode']))

				{

					// Create a code and store it

					$user['User']['resetcode'] = md5($user['User']['email'] . time());

					$this->User->id = $user['User']['id'];

					$this->User->saveField('resetcode', $user['User']['resetcode']);

				}



				// Build the Reset URL ex: http://<website>/reset/123adfecesdrfer2323

				$user['remindUrl'] = HTTP_HOST . '/resetpassword/'.$user['User']['resetcode'];



				// Send the Pasword Request Email

				$this->sendRemindEmail($user);

				$this->flash('Please check your email for instructions on how to retrieve your password.', $this->data['User']['redirect']);        

			}

		}

		else

		{

			// Capture the page they came from so we can redirect back there afterwords

			$redirect = empty($_SERVER['HTTP_REFERER'])?'/':$_SERVER['HTTP_REFERER'];

			$this->set('redirect', $redirect);

		}



	} // remind()



	/**

	 * Generate a new password.  This action is called by clicking a "reset" URL in the

	 * password request email.

	 *

	 * @param strint $resetcode

	 */

	public function resetpassword($resetcode = false)

	{

		// password: TEST

		// f53accdde5fcd632d6af2474b6207789df9e1019

		$user = $this->User->findByResetcode($resetcode);

#		pr($user); exit;



		if (empty($user))

		{

			$this->set('error', 'ERROR: Invalid Reset Code.');

		}

		else

		{

			$pass1 = array('blue','green','black','red','white','brown','yellow');

			$pass2 = array('cat','dog','pig','bird','horse','cow','snake');

			// Pick a random word from both arrays

			$max1 = count($pass1)-1;

			$max2 = count($pass2)-1;

			$word1 = ucfirst($pass1[rand(0, $max1)]);

			$word2 = ucfirst($pass2[rand(0, $max2)]);

			$newpassword = $word1 . $word2 . rand(1, 9);

			

			$this->User->id = $user['User']['id'];

			$this->User->saveField('resetcode', '');	// We clear the current reset code

			$this->User->saveField('password', $this->Auth->password($newpassword));

			

			$this->set('newpassword', $newpassword);

		}

		





	} // resetpassword()

	

	/**

	 * Send the Password Request Email to the user.

	 *

	 * TODO:  Move this to a component

	 * @param array

	 */

	public function sendRemindEmail($data) 

	{

		$options = array(

#			'to'			=> array('Scott W. Stanger <sstanger@highcorral.com>'),

			'to'			=> array($data['User']['fullName'].' <'.$data['User']['email'].'>'),

			'subject'		=> 'Account Password',

			'layout'		=> 'system',

			'template'		=> 'remind',

		);

		

		// Set view variables which will be available to the email template

		$data['subject'] 		= $options['subject'];



		$this->sendEmail($options, $data);

		

	} // sendRemindEmail()



}



?>

Open in new window

0
 

Author Comment

by:brucegust
ID: 33702523
When I do this:

if ($this->data['User']['new_password'] == $this->data['User']['confirm_password']) {
                              echo "Yes";
                              $this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);

I get a "Yes." So the system sees that both the new_password and the confirm_password fields match.
0
 

Author Comment

by:brucegust
ID: 33702544
When I check to see that the new password is being seen after the if statement has been accomplished...

// Verify that both passwords match
if ($this->data['User']['new_password'] == $this->data['User']['confirm_password']) {
$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);
echo $this->data['User']['new_password'];
} else {

It prints the new password. So, everything seems to be intact, it's just not saving it to the database.
0
 
LVL 40

Accepted Solution

by:
RQuadling earned 500 total points
ID: 33710468
The nesting of the admin_edit() code is extremely untidy and doesn't help readability at all.

Once I'd sorted it out, the issue was clear.

Your code is like this ...


Try to get the user based upon the ID passed to the admin_edit() method.
Do we have any data for the user?
      If we don't, then set the title to either "member does not exist" or their name.
ELSE
      Report the user data (the
 stuff)
	Do we have a new password
		If we do, verify that the passwords are the same.
	ELSE
		Save the data


As you can see the save data is only called if you DON'T change the passwords.

Take a look at how the normal edit() method works.

Below is a quick hack to see if this is the case.

Please examine the differences first before you use it.

Open in new window

Try to get the user based upon the ID passed to the admin_edit() method.
Do we have any data for the user?
	If we don't, then set the title to either "member does not exist" or their name.
ELSE
	Report the user data (the <pre> stuff)
	Do we have a new password
		If we do, verify that the passwords are the same.
	ELSE
		Save the data


<?php
	public function admin_edit($id=null)
	{
		$this->User->id = (int)$id;
		$user = $this->User->read();
		if (empty($this->data)) {

			$this->data = $user;
			$this->data['UploadTypes'] = Set::combine($this->data['Upload'], '{n}.type', '{n}');
			if (empty($this->data)) {

				$this->pageTitle = 'Member Does Not Exist';

			} else {

				$this->pageTitle = $this->data['User']['fullName'];
			}
		} else {
			$valid = false;
			// are we changing the password?
			if (!empty($this->data['User']['new_password'])) {

				// Verify that both passwords match
				if ($this->data['User']['new_password'] == $this->data['User']['confirm_password']) {

					$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);
					$valid = true;

				} else {

					// Did not properly confirm password
					$this->set('error', 'ERROR: Please confirm your Password.');
				}
			if ($valid) {

/*
                if ($this->data['User']['approved']) {
                    if ($user['User']['group_id'] != 1)
                        $this->data['User']['group_id'] = 2;
                } else {
                    if ($user['User']['group_id'] != 1)
                        $this->data['User']['group_id'] = 3;
                }
*/
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);	
				$this->doSave('User', array('uploadOptions'=>$this->uploadOptions, 'create'=>false));
			}

            #// Throw in the group_id for good measure (we'll need it in the view)
            #$this->User->contain();
            #$this->data['User']['group_id'] = $this->User->field('group_id', array('User.`id`'=>$this->User->id));
		}

        $this->set('UploadedFiles', Set::combine($this->data['Upload'], '{n}.derived_id', '{n}'));
        $this->set('UploadedFilesKey', "user$id-memberinfo");

	} // admin_edit()

Open in new window

0
 

Author Comment

by:brucegust
ID: 33716744
RQuadling, you nailed it!

The due date for this little fix was Friday afternoon and I was going nuts trying to figure what was wrong or what I could do differently to make this thing work.

As it turned out, I was able to to clarify the situation exactly as you described it above and by repositioning the actual save action in a different position within the if statement, BOOM, new password was saved.

As far as the untidy dynamic you reference, that may very well be the case. It's not my code, I'm just the one they're bringing in to clean it up. Rest assured, this isn't the only dilemma they need to fix so I may be asking for you wisdom again in the near future.

Thanks!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now