public function save($FormPostValues, $UserModel, $Options = array())
{
$Session = Gdn::session();
$UserID = $Session->UserID;
$SendEmail = val('SendEmail', $Options, true);
$Resend = val('Resend', $Options, false);
// Define the primary key in this model's table.
$this->defineSchema();
// Add & apply any extra validation rules:
$this->Validation->applyRule('Email', 'Email');
// Make sure required db fields are present.
$this->AddInsertFields($FormPostValues);
if (!isset($FormPostValues['DateExpires'])) {
$Expires = strtotime(c('Garden.Registration.InviteExpiration'));
if ($Expires > time()) {
$FormPostValues['DateExpires'] = Gdn_Format::toDateTime($Expires);
}
}
$FormPostValues['Code'] = $this->GetInvitationCode();
// Validate the form posted values
if ($this->validate($FormPostValues, true) === true) {
$Fields = $this->Validation->ValidationFields();
// All fields on the form that need to be validated
$Email = val('Email', $Fields, '');
// Make sure this user has a spare invitation to send.
$InviteCount = $UserModel->GetInvitationCount($UserID);
if ($InviteCount == 0) {
$this->Validation->addValidationResult('Email', 'You do not have enough invitations left.');
return false;
}
// Make sure that the email does not already belong to an account in the application.
$TestData = $UserModel->getWhere(array('Email' => $Email));
if ($TestData->numRows() > 0) {
$this->Validation->addValidationResult('Email', 'The email you have entered is already related to an existing account.');
return false;
}
// Make sure that the email does not already belong to an invitation in the application.
$TestData = $this->getWhere(array('Email' => $Email));
$DeleteID = false;
if ($TestData->numRows() > 0) {
if (!$Resend) {
$this->Validation->addValidationResult('Email', 'An invitation has already been sent to the email you entered.');
return false;
} else {
// Mark the old invitation for deletion.
$DeleteID = val('InvitationID', $TestData->firstRow(DATASET_TYPE_ARRAY));
}
}
// Define the fields to be inserted
$Fields = $this->Validation->SchemaValidationFields();
// Call the base model for saving
$InvitationID = $this->insert($Fields);
// Delete an old invitation.
if ($InvitationID && $DeleteID) {
$this->delete($DeleteID);
}
// Now that saving has succeeded, update the user's invitation settings
if ($InviteCount > 0) {
$UserModel->ReduceInviteCount($UserID);
}
// And send the invitation email
if ($SendEmail) {
try {
$this->send($InvitationID);
} catch (Exception $ex) {
$this->Validation->addValidationResult('Email', sprintf(t('Although the invitation was created successfully, the email failed to send. The server reported the following error: %s'), strip_tags($ex->getMessage())));
return false;
}
}
return true;
}
return false;
}