Beispiel #1
0
 function setUp()
 {
     // backup the project unique identifier field
     $this->member_unique_identifier_field = Member::get_unique_identifier_field();
     Member::set_unique_identifier_field('Email');
     parent::setUp();
 }
 function doSave($data, $form)
 {
     if (isset($data['Password']) && is_array($data['Password'])) {
         $data['Password'] = $data['Password']['_Password'];
     }
     // We need to ensure that the unique field is never overwritten
     $uniqueField = Member::get_unique_identifier_field();
     if (isset($data[$uniqueField])) {
         $SQL_unique = Convert::raw2sql($data[$uniqueField]);
         $existingUniqueMember = Member::get()->filter(array($uniqueField => $SQL_unique))->first();
         if ($existingUniqueMember && $existingUniqueMember->exists()) {
             if (Member::currentUserID() != $existingUniqueMember->ID) {
                 die("current member does not match enrolled member.");
                 return false;
             }
         }
     }
     $member = Member::currentUser();
     if (!$member) {
         $member = new Member();
     }
     $member->update($data);
     $member->write();
     $arrayExtraFields = array();
     if (isset($data["SelectedOption"])) {
         $arrayExtraFields["SelectedOption"] = $data["SelectedOption"];
     }
     if (isset($data["BookingCode"])) {
         $arrayExtraFields["BookingCode"] = $data["BookingCode"];
     }
     $this->controller->addAttendee($member, $arrayExtraFields);
     $this->redirect($this->getController()->Link("thankyou"));
     return;
 }
Beispiel #3
0
 public function setUp()
 {
     parent::setUp();
     // Fixtures assume Email is the field used to identify the log in identity
     self::$original_unique_identifier_field = Member::get_unique_identifier_field();
     Member::set_unique_identifier_field('Email');
 }
 public function getRequiredFields(Order $order)
 {
     if (Member::currentUserID() || !Checkout::membership_required()) {
         return array();
     }
     return array(Member::get_unique_identifier_field(), 'Password');
 }
Beispiel #5
0
 function setUp()
 {
     parent::setUp();
     $this->orig['Member_unique_identifier_field'] = Member::get_unique_identifier_field();
     Member::set_unique_identifier_field('Email');
     Member::set_password_validator(null);
 }
 function testEcommerceRoleCreateOrMerge()
 {
     $member = $this->objFromFixture('Member', 'member1');
     $this->session()->inst_set('loggedInAs', $member->ID);
     $uniqueField = Member::get_unique_identifier_field();
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField), 'The unique field is the email address');
     $this->assertEquals('US', $member->getField('Country'), 'The country is US');
     /* Change the email address to a new one (doesn't exist) */
     $member = EcommerceRole::createOrMerge(array('Country' => 'AU', $uniqueField => '*****@*****.**'));
     $this->assertType('object', $member, 'The member is an object, not FALSE');
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField), 'The unique field is changed (no member with that email)');
     $this->assertEquals('AU', $member->getField('Country'), 'The member country is now AU');
     /* Change the data (update existing record - logged in member owns this email) */
     $member = EcommerceRole::createOrMerge(array('Country' => 'NZ', $uniqueField => '*****@*****.**'));
     $this->assertType('object', $member, 'The member is an object, not FALSE');
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField), 'The unique field is the same (updated own record)');
     $this->assertEquals('NZ', $member->getField('Country'), 'The member country is now NZ');
     /* Change the email address to one exists (we should not get a member back when trying to merge!) */
     $member = EcommerceRole::createOrMerge(array('Country' => 'US', $uniqueField => '*****@*****.**'));
     $this->assertFalse($member, 'No member returned because we tried to merge an email that already exists in the DB');
     /* Log the member out */
     $this->session()->inst_set('loggedInAs', null);
     /* Non-logged in site user creating a new member with email that doesn't exist */
     $member = EcommerceRole::createOrMerge(array('Country' => 'NZ', $uniqueField => '*****@*****.**'));
     $this->assertType('object', $member, 'The member is an object, not FALSE');
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField));
     $this->assertEquals('NZ', $member->getField('Country'), 'The member country is NZ');
     /* Non-logged in site user creating a member with email that DOES exist */
     $member = EcommerceRole::createOrMerge(array('Country' => 'AU', $uniqueField => '*****@*****.**'));
     $this->assertFalse($member, 'The new user tried to create a member with an email that already exists, FALSE returned');
     $member = EcommerceRole::createOrMerge(array('Country' => 'AU', $uniqueField => '*****@*****.**'));
     $this->assertFalse($member, 'Even if the email has a different case, FALSE is still returned');
 }
Beispiel #7
0
 function testCustomIdentifierField()
 {
     $origField = Member::get_unique_identifier_field();
     Member::set_unique_identifier_field('Username');
     $label = singleton('Member')->fieldLabel(Member::get_unique_identifier_field());
     $this->assertEquals($label, 'Username');
     Member::set_unique_identifier_field($origField);
 }
 public function getMembershipFields()
 {
     $fields = $this->getContactFields();
     $idfield = Member::get_unique_identifier_field();
     if (!$fields->fieldByName($idfield)) {
         $fields->push(TextField::create($idfield, $idfield));
         //TODO: scaffold the correct id field
     }
     $fields->push($this->getPasswordField());
     return $fields;
 }
 public function Link($action = null)
 {
     $dashboard = $this->currentDashboard;
     if ($dashboard && $dashboard->URLSegment != 'main') {
         $identifier = Member::get_unique_identifier_field();
         $identifier = $dashboard->Owner()->{$identifier};
         $segment = $dashboard->URLSegment ? $dashboard->URLSegment : 'main';
         return Controller::join_links($this->data()->Link(true), 'board', $segment, $dashboard->Owner()->ID, $action);
     } else {
         return $this->data()->Link($action ? $action : true);
     }
 }
Beispiel #10
0
 function setUp()
 {
     // This test assumes that MemberAuthenticator is present and the default
     $this->priorAuthenticators = Authenticator::get_authenticators();
     $this->priorDefaultAuthenticator = Authenticator::get_default_authenticator();
     Authenticator::register('MemberAuthenticator');
     Authenticator::set_default_authenticator('MemberAuthenticator');
     // And that the unique identified field is 'Email'
     $this->priorUniqueIdentifierField = Member::get_unique_identifier_field();
     Member::set_unique_identifier_field('Email');
     parent::setUp();
 }
 public function doProcess($data, $form, $request)
 {
     $order = new Order();
     $items = $order->Items();
     $member = Member::currentUserID() ? Member::currentUser() : new Member();
     $paymentClass = isset($data['PaymentMethod']) ? $data['PaymentMethod'] : null;
     $payment = class_exists($paymentClass) ? new $paymentClass() : null;
     $requirePayment = $order->Subtotal() > 0 ? true : false;
     if (!($items && $items->Count() > 0)) {
         $form->sessionMessage(_t('OrderForm.NOITEMS', 'Error placing order: You have no items in your cart.'), 'bad');
         return Director::redirectBack();
     }
     if ($requirePayment) {
         if (!($payment && $payment instanceof Payment)) {
             user_error("OrderForm::doProcess(): '{$paymentClass}' is not a valid payment class!", E_USER_ERROR);
         }
     }
     // Ensure existing members don't get their record hijacked (IMPORTANT!)
     if (!$member->checkUniqueFieldValue($data)) {
         $uniqueField = Member::get_unique_identifier_field();
         $uniqueValue = $data[$uniqueField];
         $uniqueError = "Error placing order: The %s \"%d\" is\n\t\t\t\talready taken by another member. If this belongs to you, please\n\t\t\t\tlog in first before placing your order.";
         $form->sessionMessage(_t('EcommerceMemberExtension.ALREADYEXISTS', printf($uniqueError, strtolower($uniqueField), $uniqueValue), PR_MEDIUM, 'Let the user know that member already exists (e.g. %s could be "Email", %d could be "joe@somewhere.com)'), 'bad');
         return Director::redirectBack();
     }
     $form->saveInto($member);
     if (!$member->Password) {
         $member->setField('Password', Member::create_new_password());
     }
     $member->write();
     $form->saveInto($order);
     try {
         $result = $order->process($member->ID);
     } catch (Exception $e) {
         $form->sessionMessage(_t('OrderForm.PROCESSERROR', "An error occurred while placing your order: {$e->getMessage()}.<br>\n\t\t\t\t\tPlease contact the website administrator."), 'bad');
         // Send an email to site admin with $e->getMessage() error
         return Director::redirectBack();
     }
     if ($requirePayment) {
         $form->saveInto($payment);
         $payment->write();
         $result = $payment->processPayment($data, $form);
         if ($result->isSuccess()) {
             $order->sendReceipt();
         }
         // Long payment process. e.g. user goes to external site to pay (PayPal, WorldPay)
         if ($result->isProcessing()) {
             return $result->getValue();
         }
     }
     Director::redirect($order->Link());
 }
Beispiel #12
0
 /**
  * Ensures member unique id stays unique.
  */
 public function php($data)
 {
     $valid = parent::php($data);
     $field = Member::get_unique_identifier_field();
     if (isset($data[$field])) {
         $uid = $data[Member::get_unique_identifier_field()];
         $currentmember = Member::currentUser();
         //can't be taken
         if (DataObject::get_one('Member', "{$field} = '{$uid}' AND ID != " . $currentmember->ID)) {
             $this->validationError($field, "\"{$uid}\" is already taken by another member. Try another.", "required");
             $valid = false;
         }
     }
     return $valid;
 }
 /**
  * Change the password.
  *
  * @param string $username
  *   The username to find.
  * @param string $password
  *   The new password, plain text.
  */
 public function changePassword($username = null, $password = null)
 {
     // Validate the input.
     if (!$username || !$password) {
         return 'Unable to change password. Invalid username or password';
     }
     // Find the user.
     $member = Member::get_one('Member', sprintf('"%s" = \'%s\'', Member::get_unique_identifier_field(), Convert::raw2sql($username)));
     if (!$member) {
         return "Unable to find user '{$username}'.";
     }
     // Modify the user.
     $member->Password = $password;
     $member->write();
 }
 function __construct($controller, $name = "MemberRegistrationForm", $fields = null)
 {
     if (!$fields) {
         $restrictfields = array(Member::get_unique_identifier_field(), 'FirstName', 'Surname');
         $fields = singleton('Member')->scaffoldFormFields(array('restrictFields' => $restrictfields, 'fieldClasses' => array('Email' => 'EmailField')));
     }
     $fields->push(new ConfirmedPasswordField("Password"));
     $actions = new FieldList($register = new FormAction('register', "Register"));
     $validator = new MemberRegistration_Validator(Member::get_unique_identifier_field(), 'FirstName', 'Surname');
     parent::__construct($controller, $name, $fields, $actions, $validator);
     if (class_exists('SpamProtectorManager')) {
         $this->enableSpamProtection();
     }
     $this->extend('updateMemberRegistrationForm');
 }
 /**
  * Constructor
  *
  * @param Controller $controller The parent controller, necessary to
  *                               create the appropriate form action tag.
  * @param string $name The method on the controller that will return this
  *                     form object.
  * @param FieldList|FormField $fields All of the fields in the form - a
  *                                   {@link FieldList} of {@link FormField}
  *                                   objects.
  * @param FieldList|FormAction $actions All of the action buttons in the
  *                                     form - a {@link FieldList} of
  *                                     {@link FormAction} objects
  * @param bool $checkCurrentUser If set to TRUE, it will be checked if a
  *                               the user is currently logged in, and if
  *                               so, only a logout button will be rendered
  * @param string $authenticatorClassName Name of the authenticator class that this form uses.
  */
 function __construct($controller, $name, $fields = null, $actions = null, $checkCurrentUser = true)
 {
     // This is now set on the class directly to make it easier to create subclasses
     // $this->authenticator_class = $authenticatorClassName;
     $customCSS = project() . '/css/member_login.css';
     if (Director::fileExists($customCSS)) {
         Requirements::css($customCSS);
     }
     if (isset($_REQUEST['BackURL'])) {
         $_REQUEST['BackURL'] = str_replace("/RegistrationForm", "", $_REQUEST['BackURL']);
         $backURL = $_REQUEST['BackURL'];
     } else {
         if (strpos(Session::get('BackURL'), "/RegistrationForm") > 0) {
             Session::set('BackURL', str_replace("/RegistrationForm", "", Session::get('BackURL')));
         }
         $backURL = str_replace("/RegistrationForm", "", Session::get('BackURL'));
     }
     if ($checkCurrentUser && Member::currentUser() && Member::logged_in_session_exists()) {
         $fields = new FieldList(new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this));
         $actions = new FieldList(new FormAction("logout", _t('Member.BUTTONLOGINOTHER', "Log in as someone else")));
     } else {
         if (!$fields) {
             $label = singleton('Member')->fieldLabel(Member::get_unique_identifier_field());
             $fields = new FieldList(new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this), new TextField("Email", $label, Session::get('SessionForms.MemberLoginForm.Email'), null, $this), new PasswordField("Password", _t('Member.PASSWORD', 'Password')));
             if (Security::$autologin_enabled) {
                 $fields->push(new CheckboxField("Remember", _t('Member.REMEMBERME', "Remember me next time?")));
             }
         }
         if (!$actions) {
             $actions = new FieldList(new FormAction('dologin', _t('Member.BUTTONLOGIN', "Log in")), new LiteralField('forgotPassword', '<p id="ForgotPassword"><a href="Security/lostpassword">' . _t('Member.BUTTONLOSTPASSWORD', "I've lost my password") . '</a></p>'), new LiteralField('resendEmail', '<p id="ResendEmail"><a href="Security/verifyemail">' . _t('EmailVerifiedMember.BUTTONRESENDEMAIL', "I've lost my verification email") . '</a></p>'));
         }
     }
     if (isset($backURL)) {
         $fields->push(new HiddenField('BackURL', 'BackURL', $backURL));
     }
     parent::__construct($controller, $name, $fields, $actions);
     // Focus on the email input when the page is loaded
     // Only include this if other form JS validation is enabled
     /*		if($this->getValidator()->getJavascriptValidationHandler() != 'none') {
     			Requirements::customScript(<<<JS
     				(function() {
     					var el = document.getElementById("MemberLoginForm_LoginForm_Email");
     					if(el && el.focus) el.focus();
     				})();
     JS
     			);
     		}*/
 }
 /**
  * Check that no existing members have the same value
  * for their unique field. This is useful for checking
  * if a member already exists with a certain email address.
  * 
  * If the member is logged in, and the existing member found
  * has the same ID (it's them), return TRUE because this is
  * their own member account.
  * 
  * @param array $data Raw data to check from a form request
  * @return boolean TRUE is unique | FALSE not unique
  */
 public function checkUniqueFieldValue($data)
 {
     $field = Member::get_unique_identifier_field();
     $value = isset($data[$field]) ? $data[$field] : null;
     if (!$value) {
         return true;
     }
     $SQL_value = Convert::raw2sql($value);
     $existingMember = DataObject::get_one('Member', "{$field} = '{$SQL_value}'");
     if ($existingMember && $existingMember->exists()) {
         if ($this->owner->ID != $existingMember->ID) {
             return false;
         }
     }
     return true;
 }
 /**
  * Create a new member with given data for a new member,
  * or merge the data into the logged in member.
  * 
  * IMPORTANT: Before creating a new Member record, we first
  * check that the request email address doesn't already exist.
  * 
  * @param array $data Form request data to update the member with
  * @return boolean|object Member object or boolean FALSE
  */
 public static function createOrMerge($data)
 {
     // Because we are using a ConfirmedPasswordField, the password will
     // be an array of two fields
     if (isset($data['Password']) && is_array($data['Password'])) {
         $data['Password'] = $data['Password']['_Password'];
     }
     // We need to ensure that the unique field is never overwritten
     $uniqueField = Member::get_unique_identifier_field();
     if (isset($data[$uniqueField])) {
         $SQL_unique = Convert::raw2xml($data[$uniqueField]);
         $existingUniqueMember = DataObject::get_one('Member', "{$uniqueField} = '{$SQL_unique}'");
         if ($existingUniqueMember && $existingUniqueMember->exists()) {
             if (Member::currentUserID() != $existingUniqueMember->ID) {
                 return false;
             }
         }
     }
     if (!($member = Member::currentUser())) {
         $member = new Member();
     }
     $member->update($data);
     return $member;
 }
 public function handleUser($request)
 {
     $segment = $this->request->param('Segment');
     $identifier = $this->request->param('Identifier');
     try {
         $userId = (int) $identifier;
         if (!$userId) {
             $field = Member::get_unique_identifier_field();
             $member = DataList::create('Member')->filter(array($field => $identifier))->first();
             if ($member) {
                 $userId = $member->ID;
             }
         }
         if (!$segment) {
             $segment = 'main';
         }
         $board = $this->getDashboard($segment, $userId);
     } catch (PermissionDeniedException $pde) {
         return Security::permissionFailure($this, 'You do not have permission to view that');
     }
     if ($board) {
         // need this call to make sure the params are properly processed
         $this->request->allParams();
         $cls = get_class($this);
         $controller = $this->injector->create($cls, $this->dataRecord, $board);
         return $controller;
     }
     return $this->httpError(404, "Board {$segment} does not exist");
 }
 /**
  * Ensures member unique id stays unique and other basic stuff...
  * @param array $data = Form Data
  * @return Boolean
  */
 function php($data)
 {
     $this->form->saveDataToSession();
     if (Member::currentUserID()) {
         $allowExistingEmail = false;
     } else {
         $allowExistingEmail = true;
     }
     $valid = parent::php($data, $allowExistingEmail);
     if ($this->form->uniqueMemberFieldCanBeUsed($data)) {
         //do nothing
     } else {
         $uniqueFieldName = Member::get_unique_identifier_field();
         $this->validationError($uniqueFieldName, _t("OrderForm.EMAILFROMOTHERUSER", 'Sorry, an account with that email is already in use by another customer. If this is your email address then please log in first before placing your order.'), "required");
         $valid = false;
     }
     if (!$valid) {
         $this->form->sessionMessage(_t("OrderForm.ERRORINFORM", "We could not proceed with your order, please check your errors below."), "bad");
         $this->form->messageForForm("OrderForm", _t("OrderForm.ERRORINFORM", "We could not proceed with your order, please check your errors below."), "bad");
     }
     return $valid;
 }
 /**
  * Add existing member to group rather than creating a new member
  */
 function addtogroup()
 {
     // Protect against CSRF on destructive action
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($this->controller->getRequest())) {
         return $this->httpError(400);
     }
     $data = $_REQUEST;
     $groupID = isset($data['ctf']['ID']) ? $data['ctf']['ID'] : null;
     if (!is_numeric($groupID)) {
         FormResponse::status_messsage(_t('MemberTableField.ADDINGFIELD', 'Adding failed'), 'bad');
         return;
     }
     // Get existing record either by ID or unique identifier.
     $identifierField = Member::get_unique_identifier_field();
     $className = self::$data_class;
     $record = null;
     if (isset($data[$identifierField])) {
         $record = DataObject::get_one($className, sprintf('"%s" = \'%s\'', $identifierField, $data[$identifierField]));
         if ($record && !$record->canEdit()) {
             return $this->httpError('401');
         }
     }
     // Fall back to creating a new record
     if (!$record) {
         $record = new $className();
     }
     // Update an existing record, or populate a new one.
     // If values on an existing (autocompleted) record have been changed,
     // they will overwrite current data. We need to unset 'ID'
     // record as it points to the group rather than the member record, and would
     // cause the member to be written to a potentially existing record.
     unset($data['ID']);
     $record->update($data);
     // Validate record, mainly password restrictions.
     // Note: Doesn't use Member_Validator
     $valid = $record->validate();
     if ($valid->valid()) {
         $record->write();
         $record->Groups()->add($groupID);
         $this->sourceItems();
         // TODO add javascript to highlight added row (problem: might not show up due to sorting/filtering)
         FormResponse::update_dom_id($this->id(), $this->renderWith($this->template), true);
         FormResponse::status_message(_t('MemberTableField.ADDEDTOGROUP', 'Added member to group'), 'good');
     } else {
         $message = sprintf(_t('MemberTableField.ERRORADDINGUSER', 'There was an error adding the user to the group: %s'), Convert::raw2xml($valid->starredList()));
         FormResponse::status_message($message, 'bad');
     }
     return FormResponse::respond();
 }
Beispiel #21
0
	/**
	 * Constructor
	 *
	 * @param Controller $controller The parent controller, necessary to
	 *                               create the appropriate form action tag.
	 * @param string $name The method on the controller that will return this
	 *                     form object.
	 * @param FieldList|FormField $fields All of the fields in the form - a
	 *                                   {@link FieldList} of {@link FormField}
	 *                                   objects.
	 * @param FieldList|FormAction $actions All of the action buttons in the
	 *                                     form - a {@link FieldList} of
	 *                                     {@link FormAction} objects
	 * @param bool $checkCurrentUser If set to TRUE, it will be checked if a
	 *                               the user is currently logged in, and if
	 *                               so, only a logout button will be rendered
	 * @param string $authenticatorClassName Name of the authenticator class that this form uses.
	 */
	function __construct($controller, $name, $fields = null, $actions = null,
											 $checkCurrentUser = true) {

		// This is now set on the class directly to make it easier to create subclasses
		// $this->authenticator_class = $authenticatorClassName;

		$customCSS = project() . '/css/member_login.css';
		if(Director::fileExists($customCSS)) {
			Requirements::css($customCSS);
		}
		
		if(isset($_REQUEST['BackURL'])) {
			$backURL = $_REQUEST['BackURL'];
		} else {
			$backURL = Session::get('BackURL');
		}

		if($checkCurrentUser && Member::currentUser() && Member::logged_in_session_exists()) {
			$fields = new FieldList(
				new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this)
			);
			$actions = new FieldList(
				new FormAction("logout", _t('Member.BUTTONLOGINOTHER', "Log in as someone else"))
			);
		} else {
			if(!$fields) {
				$label=singleton('Member')->fieldLabel(Member::get_unique_identifier_field());
				$fields = new FieldList(
					new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this),
					//Regardless of what the unique identifer field is (usually 'Email'), it will be held in the 'Email' value, below:
					new TextField("Email", $label, Session::get('SessionForms.MemberLoginForm.Email'), null, $this),
					new PasswordField("Password", _t('Member.PASSWORD', 'Password'))
				);
				if(Security::$autologin_enabled) {
					$fields->push(new CheckboxField(
						"Remember", 
						_t('Member.REMEMBERME', "Remember me next time?")
					));
				}
			}
			if(!$actions) {
				$actions = new FieldList(
					new FormAction('dologin', _t('Member.BUTTONLOGIN', "Log in")),
					new LiteralField(
						'forgotPassword',
						'<p id="ForgotPassword"><a href="Security/lostpassword">' . _t('Member.BUTTONLOSTPASSWORD', "I've lost my password") . '</a></p>'
					)
				);
			}
		}

		if(isset($backURL)) {
			$fields->push(new HiddenField('BackURL', 'BackURL', $backURL));
		}

		parent::__construct($controller, $name, $fields, $actions);

		// Focus on the email input when the page is loaded
		Requirements::customScript(<<<JS
			(function() {
				var el = document.getElementById("MemberLoginForm_LoginForm_Email");
				if(el && el.focus) el.focus();
			})();
JS
		);
	}
Beispiel #22
0
 /**
  * Authenticate using the given email and password, returning the
  * appropriate member object if
  *
  * @return bool|Member Returns FALSE if authentication fails, otherwise
  *                     the member object
  * @see setDefaultAdmin()
  */
 public static function authenticate($RAW_email, $RAW_password)
 {
     $SQL_email = Convert::raw2sql($RAW_email);
     $SQL_password = Convert::raw2sql($RAW_password);
     // Default login (see {@setDetaultAdmin()})
     if ($RAW_email == self::$default_username && $RAW_password == self::$default_password && !empty(self::$default_username) && !empty(self::$default_password)) {
         $member = self::findAnAdministrator();
     } else {
         $member = DataObject::get_one("Member", "\"" . Member::get_unique_identifier_field() . "\" = '{$SQL_email}' AND \"Password\" IS NOT NULL");
         if ($member && $member->checkPassword($RAW_password) == false) {
             $member = null;
         }
     }
     return $member;
 }
 public function Link($action = '')
 {
     $identifier = Member::get_unique_identifier_field();
     $identifier = $this->Owner()->{$identifier};
     if ($this->controller) {
         return Controller::join_links($this->controller->Link(), 'user', $identifier, $this->URLSegment, $action);
     }
     return Controller::join_links(Director::baseURL(), 'dashboard', 'user', $identifier, $this->URLSegment, $action);
 }
 /**
  * Method to authenticate an user
  *
  * @param array $RAW_data Raw data to authenticate the user
  * @param Form $form Optional: If passed, better error messages can be
  *                             produced by using
  *                             {@link Form::sessionMessage()}
  * @return bool|Member Returns FALSE if authentication fails, otherwise
  *                     the member object
  * @see Security::setDefaultAdmin()
  */
 public static function authenticate($RAW_data, Form $form = null)
 {
     if (array_key_exists('Email', $RAW_data) && $RAW_data['Email']) {
         $SQL_user = Convert::raw2sql($RAW_data['Email']);
     } else {
         return false;
     }
     $isLockedOut = false;
     $result = null;
     // Default login (see Security::setDefaultAdmin())
     if (Security::check_default_admin($RAW_data['Email'], $RAW_data['Password'])) {
         $member = Security::findAnAdministrator();
     } else {
         $member = DataObject::get_one("Member", "\"" . Member::get_unique_identifier_field() . "\" = '{$SQL_user}' AND \"Password\" IS NOT NULL");
         if ($member) {
             $result = $member->checkPassword($RAW_data['Password']);
         } else {
             $result = new ValidationResult(false, _t('Member.ERRORWRONGCRED'));
         }
         if ($member && !$result->valid()) {
             $member->registerFailedLogin();
             $member = false;
         }
     }
     // Optionally record every login attempt as a {@link LoginAttempt} object
     /**
      * TODO We could handle this with an extension
      */
     if (Security::login_recording()) {
         $attempt = new LoginAttempt();
         if ($member) {
             // successful login (member is existing with matching password)
             $attempt->MemberID = $member->ID;
             $attempt->Status = 'Success';
             // Audit logging hook
             $member->extend('authenticated');
         } else {
             // failed login - we're trying to see if a user exists with this email (disregarding wrong passwords)
             $existingMember = DataObject::get_one("Member", "\"" . Member::get_unique_identifier_field() . "\" = '{$SQL_user}'");
             if ($existingMember) {
                 $attempt->MemberID = $existingMember->ID;
                 // Audit logging hook
                 $existingMember->extend('authenticationFailed');
             } else {
                 // Audit logging hook
                 singleton('Member')->extend('authenticationFailedUnknownUser', $RAW_data);
             }
             $attempt->Status = 'Failure';
         }
         if (is_array($RAW_data['Email'])) {
             user_error("Bad email passed to MemberAuthenticator::authenticate(): {$RAW_data['Email']}", E_USER_WARNING);
             return false;
         }
         $attempt->Email = $RAW_data['Email'];
         $attempt->IP = Controller::curr()->getRequest()->getIP();
         $attempt->write();
     }
     // Legacy migration to precision-safe password hashes.
     // A login-event with cleartext passwords is the only time
     // when we can rehash passwords to a different hashing algorithm,
     // bulk-migration doesn't work due to the nature of hashing.
     // See PasswordEncryptor_LegacyPHPHash class.
     if ($member && self::$migrate_legacy_hashes && array_key_exists($member->PasswordEncryption, self::$migrate_legacy_hashes)) {
         $member->Password = $RAW_data['Password'];
         $member->PasswordEncryption = self::$migrate_legacy_hashes[$member->PasswordEncryption];
         $member->write();
     }
     if ($member) {
         Session::clear('BackURL');
     } else {
         if ($form && $result) {
             $form->sessionMessage($result->message(), 'bad');
         }
     }
     return $member;
 }
 /**
  * Ensures member unique id stays unique and other basic stuff...
  * @param array $data = array Form Field Data
  * @param Boolean $allowExistingEmail - see comment below
  * @return Boolean
  **/
 function php($data, $allowExistingEmail = false)
 {
     $this->form->saveDataToSession();
     $valid = parent::php($data);
     $uniqueFieldName = Member::get_unique_identifier_field();
     $loggedInMember = Member::currentUser();
     $loggedInMemberID = 0;
     if (isset($data[$uniqueFieldName]) && $data[$uniqueFieldName]) {
         $isShopAdmin = false;
         if ($loggedInMember) {
             $loggedInMemberID = $loggedInMember->ID;
             if ($loggedInMember->IsShopAdmin()) {
                 $isShopAdmin = true;
             }
         }
         if ($isShopAdmin || $allowExistingEmail) {
             //do nothing
         } else {
             $uniqueFieldValue = Convert::raw2sql($data[$uniqueFieldName]);
             //can't be taken
             $otherMembersWithSameEmail = Member::get()->filter(array($uniqueFieldName => $uniqueFieldValue))->exclude(array("ID" => $loggedInMemberID));
             if ($otherMembersWithSameEmail->count()) {
                 //we allow existing email
                 // if we are currently NOT logged in
                 // in case we place an order!
                 if ($allowExistingEmail) {
                     //do nothing
                 } else {
                     $message = _t("Account.ALREADYTAKEN", "{uniqueFieldValue} is already taken by another member. Please log in or use another {uniqueFieldName}.", array("uniqueFieldValue" => $uniqueFieldValue, "uniqueFieldName" => $uniqueFieldName));
                     $this->validationError($uniqueFieldName, $message, "required");
                     $valid = false;
                 }
             }
         }
     }
     // check password fields are the same before saving
     if (isset($data["PasswordCheck1"]) && isset($data["PasswordCheck2"])) {
         if ($data["PasswordCheck1"] != $data["PasswordCheck2"]) {
             $this->validationError("PasswordCheck1", _t('Account.PASSWORDSERROR', 'Passwords do not match.'), "required");
             $valid = false;
         }
         //if you are not logged in, you have not provided a password and the settings require you to be logged in then
         //we have a problem
         if (!$loggedInMember && !$data["PasswordCheck1"] && EcommerceConfig::get("EcommerceRole", "must_have_account_to_purchase")) {
             $this->validationError("PasswordCheck1", _t('Account.SELECTPASSWORD', 'Please select a password.'), "required");
             $valid = false;
         }
         $letterCount = strlen($data["PasswordCheck1"]);
         $minLength = Config::inst()->get("ShopAccountForm_Validator", "minimum_password_length");
         if ($letterCount > 0 && $letterCount < $minLength) {
             $this->validationError("PasswordCheck1", _t('Account.PASSWORDMINIMUMLENGTH', 'Password does not meet minimum standards.'), "required");
             $valid = false;
         }
     }
     if (isset($data["FirstName"])) {
         if (strlen($data["FirstName"]) < 2) {
             $this->validationError("FirstName", _t('Account.NOFIRSTNAME', 'Please enter your first name.'), "required");
             $valid = false;
         }
     }
     if (isset($data["Surname"])) {
         if (strlen($data["Surname"]) < 2) {
             $this->validationError("Surname", _t('Account.NOSURNAME', 'Please enter your surname.'), "required");
             $valid = false;
         }
     }
     if (!$valid) {
         $this->form->sessionMessage(_t('Account.ERRORINFORM', 'We could not save your details, please check your errors below.'), "bad");
     }
     return $valid;
 }
 /**
  * Ensures member unique id stays unique and other basic stuff...
  * @param $data = array Form Field Data
  * @return Boolean
  **/
 function php($data)
 {
     $valid = parent::php($data);
     $uniqueFieldNameForMember = Member::get_unique_identifier_field();
     $uniqueFieldNameForForm = $uniqueFieldNameForMember . "Signup";
     $loggedInMember = Member::currentUser();
     if (isset($data[$uniqueFieldNameForForm]) && $loggedInMember && $data[$uniqueFieldNameForForm]) {
         if (!$loggedInMember->IsShopAdmin()) {
             $uniqueFieldValue = Convert::raw2sql($data[$uniqueFieldNameForForm]);
             $anotherMember = DataObject::get_one('Member', "\"{$uniqueFieldNameForMember}\" = '{$uniqueFieldValue}' AND \"Member\".\"ID\" <> " . $loggedInMember->ID);
             //can't be taken
             if ($anotherMember->Password) {
                 $message = sprintf(_t("Account.ALREADYTAKEN", '%1$s is already taken by another member. Please log in or use another %2$s'), $uniqueFieldValue, $uniqueFieldNameForForm);
                 $this->validationError($uniqueFieldNameForForm, $message, "required");
                 $valid = false;
             }
         }
     }
     /*
     		// check password fields are the same before saving
     		if(isset($data["Password"]["_Password"]) && isset($data["Password"]["_ConfirmPassword"])) {
     			if($data["Password"]["_Password"] != $data["Password"]["_ConfirmPassword"]) {
     				$this->validationError(
     					"Password",
     					_t('Account.PASSWORDSERROR', 'Passwords do not match.'),
     					"required"
     				);
     				$valid = false;
     			}
     			if(!$loggedInMember && !$data["Password"]["_Password"]) {
     				$this->validationError(
     					"Password",
     					_t('Account.SELECTPASSWORD', 'Please select a password.'),
     					"required"
     				);
     				$valid = false;
     			}
     		}
     		* */
     if (!$valid) {
         $this->form->sessionMessage(_t('Account.ERRORINFORM', 'We could not save your details, please check your errors below.'), "bad");
     }
     return $valid;
 }
 public static function ecommerce_create_or_merge($data)
 {
     // Because we are using a ConfirmedPasswordField, the password will
     // be an array of two fields
     if (isset($data['Password']) && is_array($data['Password'])) {
         $data['Password'] = $data['Password']['_Password'];
     }
     // We need to ensure that the unique field is never overwritten
     $uniqueField = Member::get_unique_identifier_field();
     if (isset($data[$uniqueField])) {
         $SQL_unique = Convert::raw2xml($data[$uniqueField]);
         // TODO review - should $uniqueField be quoted by Member::get_unique_identifier_field() already? (this would be sapphire bug)
         $existingUniqueMember = DataObject::get_one('Member', "\"{$uniqueField}\" = '{$SQL_unique}'");
         if ($existingUniqueMember && $existingUniqueMember->exists()) {
             if (Member::currentUserID() != $existingUniqueMember->ID) {
                 return false;
             }
         }
     }
     if (!($member = Member::currentUser())) {
         $member = new Member();
     }
     $member->update($data);
     return $member;
 }
 /**
  * Ajax autocompletion
  */
 public function autocomplete()
 {
     $fieldName = $this->urlParams['ID'];
     $fieldVal = $_REQUEST[$fieldName];
     $result = '';
     $uidField = Member::get_unique_identifier_field();
     // Make sure we only autocomplete on keys that actually exist, and that we don't autocomplete on password
     if (!singleton($this->stat('subitem_class'))->hasDatabaseField($fieldName) || $fieldName == 'Password') {
         return;
     }
     $matches = DataObject::get($this->stat('subitem_class'), "\"{$fieldName}\" LIKE '" . Convert::raw2sql($fieldVal) . "%'");
     if ($matches) {
         $result .= "<ul>";
         foreach ($matches as $match) {
             // If the current user doesnt have permissions on the target user,
             // he's not allowed to add it to a group either: Don't include it in the suggestions.
             if (!$match->canView() || !$match->canEdit()) {
                 continue;
             }
             $data = array();
             foreach ($match->summaryFields() as $k => $v) {
                 $data[$k] = $match->{$k};
             }
             $result .= sprintf('<li data-fields="%s">%s <span class="informal">(%s)</span></li>', Convert::raw2att(Convert::raw2json($data)), $match->{$fieldName}, implode(',', array_values($data)));
         }
         $result .= "</ul>";
         return $result;
     }
 }
Beispiel #29
0
 /**
  * Check if the submitted member data is valid (server-side)
  *
  * Check if a member with that email doesn't already exist, or if it does
  * that it is this member.
  *
  * @param array $data Submitted data
  * @return bool Returns TRUE if the submitted data is valid, otherwise
  *              FALSE.
  */
 function php($data)
 {
     $valid = parent::php($data);
     $identifierField = Member::get_unique_identifier_field();
     $SQL_identifierField = Convert::raw2sql($data[$identifierField]);
     $member = DataObject::get_one('Member', "\"{$identifierField}\" = '{$SQL_identifierField}'");
     // if we are in a complex table field popup, use ctf[childID], else use ID
     if (isset($_REQUEST['ctf']['childID'])) {
         $id = $_REQUEST['ctf']['childID'];
     } elseif (isset($_REQUEST['ID'])) {
         $id = $_REQUEST['ID'];
     } else {
         $id = null;
     }
     if ($id && is_object($member) && $member->ID != $id) {
         $uniqueField = $this->form->dataFieldByName($identifierField);
         $this->validationError($uniqueField->id(), sprintf(_t('Member.VALIDATIONMEMBEREXISTS', 'A member already exists with the same %s'), strtolower($identifierField)), 'required');
         $valid = false;
     }
     // Execute the validators on the extensions
     if ($this->extension_instances) {
         foreach ($this->extension_instances as $extension) {
             if (method_exists($extension, 'hasMethod') && $extension->hasMethod('updatePHP')) {
                 $valid &= $extension->updatePHP($data, $this->form);
             }
         }
     }
     return $valid;
 }
 /**
  * Ensures member unique id stays unique and other basic stuff...
  * @param array $data = Form Data
  * @return Boolean
  */
 function php($data)
 {
     $valid = parent::php($data);
     //Note the exclamation Mark - only applies if it return FALSE.
     if (!$this->form->uniqueMemberFieldCanBeUsed($data)) {
         $uniqueField = Member::get_unique_identifier_field();
         $this->validationError($uniqueField, _t("OrderForm.EMAILFROMOTHERUSER", 'Sorry, an account with that email is already in use by another customer. If this is your email address then please log in first before placing your order.'), "required");
         $valid = false;
     }
     if (!$valid) {
         $this->form->sessionMessage(_t("OrderForm.ERRORINFORM", "We could not proceed with your order, please check your errors below."), "bad");
         $this->form->messageForForm("OrderForm", _t("OrderForm.ERRORINFORM", "We could not proceed with your order, please check your errors below."), "bad");
     }
     return $valid;
 }