Manage a user's email address

@throws \Nails\Common\Exception\FactoryException
501586
public function email(): void
    {
        $oInput     = Factory::service('Input');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $action     = $oInput->post('action');
        $sEmail     = trim($oInput->post('email'));
        $iId        = (int) $oInput->post('id') ?: null;

        switch ($action) {

            case 'add':
                $bIsPrimary  = (bool) $oInput->post('isPrimary');
                $bIsVerified = (bool) $oInput->post('isVerified');

                if ($oUserModel->emailAdd($sEmail, $iId, $bIsPrimary, $bIsVerified)) {
                    $sStatus  = 'success';
                    $sMessage = '"' . $sEmail . '" was added successfully. ';
                } else {
                    $sStatus  = 'error';
                    $sMessage = 'Failed to add email. ';
                    $sMessage .= $oUserModel->lastError();
                }
                break;

            case 'delete':
                if ($oUserModel->emailDelete($sEmail, $iId)) {
                    $sStatus  = 'success';
                    $sMessage = '"' . $sEmail . '" was deleted successfully. ';
                } else {
                    $sStatus  = 'error';
                    $sMessage = 'Failed to delete email "' . $sEmail . '". ';
                    $sMessage .= $oUserModel->lastError();
                }
                break;

            case 'makePrimary':
                if ($oUserModel->emailMakePrimary($sEmail, $iId)) {
                    $sStatus  = 'success';
                    $sMessage = '"' . $sEmail . '" was set as the primary email.';
                } else {
                    $sStatus  = 'error';
                    $sMessage = 'Failed to mark "' . $sEmail . '" as the primary address. ';
                    $sMessage .= $oUserModel->lastError();
                }
                break;

            case 'verify':
                //  Get the code for this email
                $aUserEmails = $oUserModel->getEmailsForUser($iId);
                $sCode       = '';

                foreach ($aUserEmails as $oUserEmail) {
                    if ($oUserEmail->email == $sEmail) {
                        $sCode = $oUserEmail->code;
                    }
                }

                if (!empty($sCode) && $oUserModel->emailVerify($iId, $sCode)) {
                    $sStatus  = 'success';
                    $sMessage = '"' . $sEmail . '" was verified successfully.';
                } elseif (empty($sCode)) {
                    $sStatus  = 'error';
                    $sMessage = 'Failed to mark "' . $sEmail . '" as verified. ';
                    $sMessage .= 'Could not determine email\'s security code.';
                } else {
                    $sStatus  = 'error';
                    $sMessage = 'Failed to mark "' . $sEmail . '" as verified. ';
                    $sMessage .= $oUserModel->lastError();
                }
                break;

            default:
                $sStatus  = 'error';
                $sMessage = 'Unknown action: "' . $action . '"';
                break;
        }

        $oSession = Factory::service('Session', 'nails/module-auth');
        $oSession->setFlashData($sStatus, $sMessage);
        redirect($oInput->post('return'));
    }
702439
public function setEmail(string $value) : User
    {

        if ($this->data['email'] !== $value) {
            $this->data['email'] = $value;
            $this->setModified('email');
        }

        return $this;
    }
660517
private function setEmailAddress(?string $emailAddress): self
    {
        $this->updatePropertyValue(
            EmailAddressFieldInterface::PROP_EMAIL_ADDRESS,
            $emailAddress
        );

        return $this;
    }
918102
public function setAddress($address)
    {
        if (preg_match(self::ADDRESS_REGEXP, $address)) {
            $this->address = $address;
        } else {
            throw new Exception("Malformed e-mail address: $address");
        }
    }
267413
public function setEmail($v)
    {
        if ($v !== null) {
            $v = (string) $v;
        }

        if ($this->email !== $v) {
            $this->email = $v;
            $this->modifiedColumns[] = UserPeer::EMAIL;
        }


        return $this;
    }
898881
protected function defaultEmailChange()
    {
        $this->user->unconfirmed_email = $this->email;
        /** @var Token $token */
        $token = new Token(['user_id' => $this->user->id, 'type' => Token::TYPE_CONFIRM_NEW_EMAIL]);
        $token->save(false);
        $this->module->sendMessage($this->user->unconfirmed_email,Yii::t('user', 'Confirm email change on {0}', Yii::$app->name),'reconfirmation',['user' => $this->user, 'token' => $token]);
        Yii::$app->session->setFlash('info', Yii::t('user', 'A confirmation message has been sent to your new email address'));
    }
1151789
public function setEmail($email)
	{
		if ( $email == $this->getEmail() ) { return; }

		if( $email !== '' && preg_match('/^.+@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*$/', $email) !== 1 ) {
			throw new MShop_Exception( sprintf( 'Invalid characters in email address: "%1$s"', $email ) );
		}

		$this->_values['email'] = (string) $email;
		$this->setModified();
	}
405487
public function email($email = null) {
		$this->out('Email:');
		while (empty($email) || !Validation::email($email)) {
			$email = $this->in('New email address (must have a valid form at least)');
		}

		/** @var \App\Model\Table\UsersTable $Users */
		$Users = TableRegistry::get(CLASS_USERS);
		$this->Users = $Users;
		if (!$this->Users->hasField('email')) {
			$this->abort(CLASS_USERS . ' table doesnt have an email field!');
		}

		$this->hr();
		$this->out('Resetting...');

		if (empty($this->params['dry-run'])) {
			$count = $this->Users->updateAll(['email' => $email . ''], ['email !=' => $email]);
		} else {
			$count = $this->Users->find('all', ['conditions' => [CLASS_USERS . '.email !=' => $email]])->count();
		}
		$this->out($count . ' emails resetted - DONE');
	}
499464
protected function emailFactory()
    {
        if (!isset($this->emailFactory)) {
            throw new RuntimeException(sprintf(
                'Email Factory is not defined for [%s]',
                get_class($this)
            ));
        }

        return $this->emailFactory;
    }
311580
protected function actionAccountAddress()
    {
        $key = 'delete';
        $this->controlToken($key);
        $address_id = $this->getQuery($key);

        if (!empty($address_id)) {

            if ($this->address->delete($address_id)) {
                $this->redirect('', $this->text('Address has been deleted'), 'success');
            }

            $this->redirect('', $this->text('Address has not been deleted'), 'warning');
        }
    }
372214
public function setEmail($email)
    {
        /**
         * @see Zend_Validate_EmailAddress
         */
        require_once 'Zend/Validate/EmailAddress.php';
        $validate = new Zend_Validate_EmailAddress();
        if (!$validate->isValid($email)) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set a valid email address into the email property");
        }
        $this->offsetSet('email', $email);
        return $this;
    }
1092730
public function getUserEmail()
    {
        return strlen($this->kontakt->getDataValue($this->mailColumn)) ? $this->kontakt->getDataValue($this->mailColumn)
                : $this->adresar->getDataValue($this->mailColumn);
    }
720053
public function AddressForm()
    {
        $location = Injector::inst()->get(ContactLocation::class);

        $fields = FieldList::create(
            HiddenField::create("ID")
        );

        $fields->merge($location->getFrontEndFields());

        // Remove the version field
        $fields->removeByName("Version");

        $fields->replaceField(
            "Country",
            DropdownField::create(
                'Country',
                $location->fieldLabel("Country"),
                i18n::getData()->getCountries()
            )->setEmptyString("")
        );

        if (class_exists(RegionSelectionField::class)) {
            $fields->replaceField(
                "County",
                RegionSelectionField::create(
                    "County",
                    $location->fieldLabel("County"),
                    "Country"
                )
            );
        }

        $fields->replaceField(
            "ContactID",
            HiddenField::create('ContactID')
        );

        $back_btn = '<a href="';
        $back_btn .= $this->getOwner()->Link('addresses');
        $back_btn .= '" class="btn btn-link">';
        $back_btn .= _t('SilverCommerce\ContactAdmin.Cancel', 'Cancel');
        $back_btn .= '</a>';

        $form = Form::create(
            $this->getOwner(),
            "AddressForm",
            $fields,
            FieldList::create(
                LiteralField::create(
                    'BackButton',
                    $back_btn
                ),
                FormAction::create(
                    'doSaveAddress',
                    _t('SilverCommerce\ContactAdmin.Add', 'Add')
                )->addExtraClass('btn btn-success')
            ),
            RequiredFields::create(
                [
                    'FirstName',
                    'Surname',
                    'Address1',
                    'City',
                    'PostCode',
                    'Country',
                ]
            )
        );

        $this->getOwner()->extend("updateAddressForm", $form);

        return $form;
    }
1025166
public function addAddress($email, $name = '')
    {
        if (empty($email)) {
            throw new MailerException('email is required for addAddress!');
        }

        $this->_mailer->addAddress($email, $name);

        return $this;
    }
335151
private function AddMailFromEMailField()
    {
        $name = 'MailFromEMail';
        $field = Input::Text($name, $this->settings->GetMailFromEMail());
        $this->AddField($field);
        $this->AddValidator($name, PhpFilter::EMail());
    }
897477
public function delAddress()
    {
        $this->_blDelete = false;
        if ($this->_allowAdminEdit($this->getEditObjectId())) {
            $aParams = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("editval");
            if (isset($aParams['oxaddress__oxid']) && $aParams['oxaddress__oxid'] != "-1") {
                $oAdress = oxNew(\OxidEsales\Eshop\Application\Model\Address::class);
                $this->_blDelete = $oAdress->delete($aParams['oxaddress__oxid']);
            }
        }
    }
479910
public static function boot()
	{
		parent::boot();

		User::creating(function($user)
		{
			if (!$user->email) throw new \Exception('User model must contain a not-null email attribute');
			if (!$user->username) $user->username = $user->email;
		});
	}