You are here

public function RedhenContact::save in RedHen CRM 7

Override parent::save() to manage user association.

Overrides Entity::save

1 call to RedhenContact::save()
RedhenContact::upsert in modules/redhen_contact/lib/redhen_contact.entity.inc
Saves a new contact unless a matching contact is found to update.

File

modules/redhen_contact/lib/redhen_contact.entity.inc, line 212
Redhen Contact entity classses.

Class

RedhenContact
The class used for contact entities.

Code

public function save() {
  $wrapper = entity_metadata_wrapper('redhen_contact', $this);
  $user = $wrapper->user
    ->value();
  $emails = $this
    ->allEmail();
  if (redhen_contact_user_email_setting(REDHEN_CONTACT_CONNECT_USERS, $this) && !$user) {
    foreach ($emails as $email) {

      // Ensure email value is not set to empty string because that matches
      // Drupal's anonymous user (uid=0). This can happen when creating a
      // contact programmatically where the email field is not guaranteed to
      // be populated.
      $user_by_mail = empty($email['value']) ? NULL : user_load_by_mail($email['value']);
      if ($user_by_mail) {
        $user = $user_by_mail;
        $wrapper->user
          ->set($user_by_mail);
        break;
      }
    }
  }

  // When there is only one email set, make sure it's marked 'default'.
  if (count($emails) === 1) {
    $this->{REDHEN_CONTACT_EMAIL_FIELD}[LANGUAGE_NONE][0]['default'] = 1;
  }
  $ret = parent::save();
  if ($ret && redhen_contact_user_email_setting(REDHEN_CONTACT_MIRROR_EMAIL, $this)) {
    $email = $wrapper->email
      ->value();

    // If we have a linked user and primary email, but they don't match, set
    // the user email.
    if ($user && $user->uid != 0 && !empty($email) && $email !== $user->mail) {
      user_save($user, array(
        'mail' => $email,
      ));
    }
  }
  return $ret;
}