public function authenticate(&$message, $mailbox)
 {
     $uid = 0;
     // Check and parse messageid for parameters.  URL will be encoded.
     $force_user_lookup = FALSE;
     $identifier = _mailcomment_get_signature(rawurldecode($message['body_html']));
     // Failed to find signature in body -- replicate mailhandler functionality to find node->threading
     if (!$identifier) {
         if (!empty($message['header']->references)) {
             // we want the final element in references header, watching out for white space
             $identifier = drupal_substr(strrchr($message['header']->references, '<'), 0);
         } elseif (!empty($message['header']->in_reply_to)) {
             // Some MUAs send more info in this header.
             $identifier = str_replace(strstr($message['header']->in_reply_to, '>'), '>', $message['header']->in_reply_to);
         }
         if (isset($identifier)) {
             $identifier = rtrim(ltrim($identifier, '<'), '>');
             $force_user_lookup = TRUE;
         }
     }
     $params = mailcomment_check_messageparams($identifier);
     if ($force_user_lookup) {
         // get uid from email address because we are using the header information to load the params
         // these contain the uid of the person who's post you are responding to
         $sender = $message['header']->from[0]->mailbox . '@' . $message['header']->from[0]->host;
         $params['uid'] = user_load_by_mail($sender)->uid;
     }
     if ($params['uid']) {
         $account = user_load($params['uid']);
         $uid = $account->uid;
     }
     return $uid;
 }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     $file = File::load($values['file'][0]);
     // Load File entity.
     $read_file = new \SplFileObject($file->url());
     // Create file handler.
     $lines = 1;
     $in_queue = 0;
     $queue = \Drupal::queue('eventninja');
     // Load queue
     while (!$read_file->eof()) {
         $data = $read_file->fgetcsv(';');
         if ($lines > 1) {
             // skip headers
             $user = user_load_by_mail($data[1]);
             if ($user === false) {
                 // Verify if user with specified email does not exist.
                 $queue->createItem($data);
                 $in_queue++;
             } else {
                 $this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]);
             }
         }
         $lines++;
     }
     if ($lines > 1) {
         drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success');
     } else {
         drupal_set_message($this->t('File contains only headers'), 'error');
     }
 }
Exemplo n.º 3
0
/**
 * Allow other modules to respond to the result of sending an email.
 *
 * @param array $result
 *   Associative array containing the send result, including the status.
 */
function hook_mandrill_mailsend_result($result)
{
    if ($result['status'] == 'rejected') {
        // Delete user.
        $user = user_load_by_mail($result['email']);
        user_delete($user->uid);
    }
}
 public function authenticate(&$message, $mailbox)
 {
     list($fromaddress, $fromname) = _mailhandler_get_fromaddress($message['header'], $mailbox);
     $uid = 0;
     if ($from_user = user_load_by_mail($fromaddress)) {
         $uid = $from_user->uid;
     }
     return $uid;
 }
 /**
  * Implements authenticate().
  */
 public function authenticate(&$message, $mailbox)
 {
     list($fromaddress, ) = _mailhandler_get_fromaddress($message['header'], $mailbox);
     $uid = 0;
     // If user with given email address exists and their token is in the toaddress, allow.
     if (($from_user = user_load_by_mail($fromaddress)) && strpos($header->to[0]->mailbox, tokenauth_get_token($from_user->uid)) !== FALSE) {
         $uid = $from_user->uid;
     }
     return $uid;
 }
Exemplo n.º 6
0
 public function postReset()
 {
     $drupal = new \erdiko\drupal\models\User();
     $account = \user_load_by_mail($_POST['mail']);
     $edit = array();
     if ($_POST['pass']['pass1'] == $_POST['pass']['pass2']) {
         $edit['pass'] = $_POST['pass']['pass1'];
         \user_save($account, $edit);
         $this->setContent('Your password was successfully changed.');
     } else {
         $this->setContent('The password and confirmation password do not match.');
     }
 }
 /**
  * {@inheritdoc}
  */
 public function processItem($data)
 {
     if (FALSE === user_load_by_mail($data->attendee->email)) {
         try {
             // build array of user data
             $user_data = ['mail' => $data->attendee->email, 'name' => $data->attendee->email, 'status' => 1, 'field_first_name' => ['value' => $data->attendee->first_name], 'field_last_name' => ['value' => $data->attendee->last_name]];
             // create User entity
             $user = entity_create('user', $user_data);
             $user->save();
             // notify user about new account
             _user_mail_notify('register_admin_created', $user);
             // create user profile
             $this->createUserProfile($user);
         } catch (\Exception $e) {
             \Drupal::logger('eventbrite')->log(RfcLogLevel::ERROR, 'User {mail} hasn\'t been created.', ['mail' => $data->attendee->email]);
         }
     }
 }
Exemplo n.º 8
0
function wyc_add_user($user_data)
{
    $joined = ($date = strtotime($user_data['JoinDate'])) && $date != false ? $date : null;
    $expires = ($date = strtotime($user_data['d_membership_expires'])) && $date != false ? date('Y-m-d H:i:s', $date) : null;
    $mail = strpos($user_data['Email'], '@') === false ? $user_data['WYCNumber'] . '@wyc_intranet.com' : $user_data['Email'];
    //set up the user fields
    $fields = array('name' => $user_data['WYCNumber'], 'mail' => $mail, 'pass' => user_password(8), 'status' => 1, 'init' => 'email address', 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'), 'field_full_name' => array(LANGUAGE_NONE => array(array('value' => $user_data['First'] . ' ' . $user_data['Last']))), 'field_wyc_number' => array(LANGUAGE_NONE => array(array('value' => $user_data['WYCNumber']))), 'field_phone_number' => array(LANGUAGE_NONE => array(array('value' => $user_data['Phone1']), array('value' => $user_data['Phone2']))), 'field_address' => array(LANGUAGE_NONE => array(array('thoroughfare' => $user_data['StreetAddress'], 'locality' => $user_data['City'], 'administrative_area' => $user_data['State'], 'postal_code' => $user_data['ZipCode']))), 'field_membership_expires' => array(LANGUAGE_NONE => array(array('value' => $expires))), 'created' => date('U', $joined));
    $old = user_load_by_mail($mail);
    if (empty($old->uid)) {
        $new = user_save('', $fields);
        wyc_log('wyc_user_created', $user_data);
        if (empty($new->uid)) {
            wyc_log('wyc_user_create_failed', $user_data);
        }
    } else {
        wyc_log('wyc_user_create_skipped', $user_data);
    }
}
Exemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function completeSaleAccount($order)
 {
     // Order already has a user ID, so the user was logged in during checkout.
     if ($order->getUserId()) {
         $order->data->complete_sale = 'logged_in';
         return;
     }
     // Email address matches an existing account.
     if ($account = user_load_by_mail($order->getEmail())) {
         $order->setUserId($account->id());
         $order->data->complete_sale = 'existing_user';
         return;
     }
     // Set up a new user.
     $cart_config = $this->config('uc_cart.settings');
     $fields = array('name' => uc_store_email_to_username($order->getEmail()), 'mail' => $order->getEmail(), 'init' => $order->getEmail(), 'pass' => user_password(), 'roles' => array(), 'status' => $cart_config->get('new_customer_status_active') ? 1 : 0);
     // Override the username, if specified.
     if (isset($order->data->new_user_name)) {
         $fields['name'] = $order->data->new_user_name;
     }
     // Create the account.
     $account = \Drupal\user\Entity\User::create($fields);
     $account->save();
     // Override the password, if specified.
     if (isset($order->data->new_user_hash)) {
         db_query('UPDATE {users_field_data} SET pass = :hash WHERE uid = :uid', [':hash' => $order->data->new_user_hash, ':uid' => $account->id()]);
         $account->password = t('Your password');
     } else {
         $account->password = $fields['pass'];
         $order->password = $fields['pass'];
     }
     // Send the customer their account details if enabled.
     if ($cart_config->get('new_customer_email')) {
         $type = $cart_config->get('new_customer_status_active') ? 'register_no_approval_required' : 'register_pending_approval';
         \Drupal::service('plugin.manager.mail')->mail('user', $type, $order->getEmail(), uc_store_mail_recipient_langcode($order->getEmail()), array('account' => $account), uc_store_email_from());
     }
     $order->setUserId($account->id());
     $order->data->new_user_name = $fields['name'];
     $order->data->complete_sale = 'new_user';
 }
function brukar_client_login($data)
{
    global $user;
    $edit = array('name' => t(variable_get('brukar_name', '!name'), array('!name' => $data['name'], '!sident' => substr($data['id'], 0, 4), '!ident' => $data['id'])), 'mail' => $data['mail'], 'status' => 1, 'data' => array('brukar' => $data));
    if ($user->uid != 0) {
        user_save($user, $edit);
        user_set_authmaps($user, array('authname_brukar' => $data['id']));
        drupal_goto('user');
    }
    $authmap_user = db_query('SELECT uid FROM {authmap} WHERE module = :module AND authname = :ident', array(':ident' => $data['id'], ':module' => 'brukar'))->fetch();
    if ($authmap_user === FALSE) {
        $provided = module_invoke_all('brukar_client_user', $edit);
        $user = !empty($provided) ? $provided[0] : user_save(user_load_by_mail($data['mail']), $edit);
        user_set_authmaps($user, array('authname_brukar' => $data['id']));
    } else {
        $user = user_save(user_load($authmap_user->uid), $edit);
    }
    $form_state = (array) $user;
    user_login_submit(array(), $form_state);
    // Better solution available?
    $query = $_GET;
    unset($query['q']);
    drupal_goto($_GET['q'] == variable_get('site_frontpage') ? '<front>' : url($_GET['q'], array('absolute' => TRUE, 'query' => $query)));
}
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $operation = $input->getArgument('operation');
     $user = $input->getArgument('user');
     $role = $input->getArgument('role');
     $systemRoles = $this->drupalApi->getRoles();
     if (is_numeric($user)) {
         $userObject = user_load($user);
     } else {
         $userObject = user_load_by_name($user);
     }
     if (!is_object($userObject)) {
         if (!filter_var($user, FILTER_VALIDATE_EMAIL) === false) {
             $userObject = user_load_by_mail($user);
         }
     }
     if (!is_object($userObject)) {
         $io->error(sprintf($this->trans('commands.user.role.messages.no-user-found'), $user));
         return 1;
     }
     if (!array_key_exists($role, $systemRoles)) {
         $io->error(sprintf($this->trans('commands.user.role.messages.no-role-found'), $role));
         return 1;
     }
     if ("add" == $operation) {
         $userObject->addRole($role);
         $userObject->save();
         $io->success(sprintf($this->trans('commands.user.role.messages.add-success'), $userObject->name->value . " (" . $userObject->mail->value . ") ", $role));
     }
     if ("remove" == $operation) {
         $userObject->removeRole($role);
         $userObject->save();
         $io->success(sprintf($this->trans('commands.user.role.messages.remove-success'), $userObject->name->value . " (" . $userObject->mail->value . ") ", $role));
     }
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 public function getUser()
 {
     $mail = $this->getMail();
     if (empty($mail)) {
         return NULL;
     }
     if ($user = User::load($this->getUserId())) {
         return $user;
     } else {
         return user_load_by_mail($this->getMail()) ?: NULL;
     }
 }
Exemplo n.º 13
0
 public function getUserDetails($username)
 {
     $account = user_load_by_name($username);
     if (!$account) {
         // An email address might have been supplied instead of the username.
         $account = user_load_by_mail($username);
     }
     if ($account) {
         return array('user_id' => $account->uid);
     }
     return FALSE;
 }
Exemplo n.º 14
0
 /**
  * Create new users with default field values.
  *
  * @param int $num
  *   Number of entities to create.
  * @param array $options
  *   Options array. This array can have "roles" key that provides an array of
  *   role names that the newly created user will need to be assigned.
  *
  * @return Response
  *   Response object.
  */
 public static function createRandom($num = 1, $options = array())
 {
     if (!is_numeric($num)) {
         return new Response(FALSE, NULL, 'Number of users to be created has to be an integer.');
     }
     $options += array('roles' => array(), 'required_fields_only' => TRUE);
     // First get the references that need to be created.
     //static::processBeforeCreateRandom($options);
     $output = array();
     for ($i = 0; $i < $num; $i++) {
         // Get a random username.
         do {
             $username = Utils::getRandomString(20);
         } while (!is_null(user_validate_name($username)) || user_load_by_name($username));
         // Get a random email address.
         do {
             $email = $username . '@' . Utils::getRandomString(20) . '.com';
         } while (!is_null(user_validate_mail($email)) || user_load_by_mail($email));
         // Get a random password.
         $password = Utils::getRandomString();
         $response = User::registerUser($username, $email, $password, $options);
         if (!$response->getSuccess()) {
             $response->setVar($output);
             return $response;
         }
         $output[] = $response->getVar();
     }
     return new Response(TRUE, Utils::normalize($output), "");
 }
 /**
  * {@inheritdoc}
  */
 public function subscribe($mail, $newsletter_id, $confirm = NULL, $source = 'unknown', $preferred_langcode = NULL)
 {
     // Get current subscriptions if any.
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     // If user is not subscribed to ANY newsletter, create a subscription account
     if (!$subscriber) {
         // To subscribe a user:
         //   - Fetch the users uid.
         //   - Determine the user preferred language.
         //   - Add the user to the database.
         //   - Get the full subscription object based on the mail address.
         // Note that step 3 gets subscription data based on mail address because the uid can be 0 (for anonymous users)
         $account = user_load_by_mail($mail);
         // If the site is multilingual:
         //  - Anonymous users are subscribed with their preferred language
         //    equal to the language of the current page.
         //  - Registered users will be subscribed with their default language as
         //    set in their account settings.
         // By default the preferred language is not set.
         if ($this->languageManager->isMultilingual()) {
             if ($account) {
                 $preferred_langcode = $account->getPreferredLangcode();
             } else {
                 $preferred_langcode = isset($preferred_langcode) ? $preferred_langcode : $this->languageManager->getCurrentLanguage();
             }
         } else {
             $preferred_langcode = '';
         }
         $subscriber = Subscriber::create(array());
         $subscriber->setMail($mail);
         if ($account) {
             $subscriber->setUserId($account->id());
         }
         $subscriber->setLangcode($preferred_langcode);
         $subscriber->setStatus(SubscriberInterface::ACTIVE);
         $subscriber->save();
     }
     $newsletter = simplenews_newsletter_load($newsletter_id);
     // If confirmation is not explicitly specified, use the newsletter
     // configuration.
     if ($confirm === NULL) {
         $confirm = $this->requiresConfirmation($newsletter, $subscriber->getUserId());
     }
     if ($confirm) {
         // Create an unconfirmed subscription object if it doesn't exist yet.
         if (!$subscriber->isSubscribed($newsletter_id)) {
             $subscriber->subscribe($newsletter_id, SIMPLENEWS_SUBSCRIPTION_STATUS_UNCONFIRMED, $source);
             $subscriber->save();
         }
         $this->addConfirmation('subscribe', $subscriber, $newsletter);
     } elseif (!$subscriber->isSubscribed($newsletter_id)) {
         // Subscribe the user if not already subscribed.
         $subscriber->subscribe($newsletter_id, SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $source);
         $subscriber->save();
     }
     return $this;
 }
Exemplo n.º 16
0
 /**
  * @param Request $request
  * @return JsonResponse
  */
 public function getCredentials(Request $request)
 {
     $data = json_decode($request->getContent(), TRUE);
     $fields = array('time' => 'is_numeric', 'nonce' => 'is_string', 'hash' => 'is_string');
     $result = $this->basicAuthenticator($fields, $data);
     if (!empty($result['error'])) {
         return new JsonResponse($result, self::ACQTEST_SUBSCRIPTION_SERVICE_UNAVAILABLE);
     }
     if (!empty($data['body']['email'])) {
         $account = user_load_by_mail($data['body']['email']);
         \Drupal::logger('getCredentials password')->debug($account->getPassword());
         if (empty($account) || $account->isAnonymous()) {
             return new JsonResponse($this->errorResponse(self::ACQTEST_SUBSCRIPTION_VALIDATION_ERROR, t('Account not found')), self::ACQTEST_SUBSCRIPTION_SERVICE_UNAVAILABLE);
         }
     } else {
         return new JsonResponse($this->errorResponse(self::ACQTEST_SUBSCRIPTION_VALIDATION_ERROR, t('Invalid arguments')), self::ACQTEST_SUBSCRIPTION_SERVICE_UNAVAILABLE);
     }
     $hash = CryptConnector::acquiaHash($account->getPassword(), $data['authenticator']['time'] . ':' . $data['authenticator']['nonce']);
     if ($hash === $data['authenticator']['hash']) {
         $result = array();
         $result['is_error'] = FALSE;
         $result['body']['subscription'][] = array('identifier' => self::ACQTEST_ID, 'key' => self::ACQTEST_KEY, 'name' => self::ACQTEST_ID);
         return new JsonResponse($result);
     } else {
         return new JsonResponse($this->errorResponse(self::ACQTEST_SUBSCRIPTION_VALIDATION_ERROR, t('Incorrect password.')), self::ACQTEST_SUBSCRIPTION_SERVICE_UNAVAILABLE);
     }
 }
Exemplo n.º 17
0
 /**
  * Attempt to load a user account.
  *
  * @param string $mail
  * @return mixed
  */
 public function load_by_mail($mail)
 {
     return user_load_by_mail($mail);
 }
 public function emailPopupSubmit()
 {
     if (isset($_SESSION['lrdata']) && !empty($_SESSION['lrdata'])) {
         $userprofile = $_SESSION['lrdata'];
         $userprofile->Email_value = trim($_POST['email']);
         if (!\Drupal::service('email.validator')->isValid($userprofile->Email_value)) {
             $popup_params = array('msg' => t('This email is invalid. Please choose another one.'), 'provider' => $userprofile->Provider, 'msgtype' => 'warning');
             $popup_params['message_title'] = $this->module_config->get('popup_title');
             return $form['email_popup'] = $this->getPopupForm($popup_params);
         } else {
             $check_mail = user_load_by_mail($userprofile->Email_value);
             if (!empty($check_mail)) {
                 $email_wrong = $this->module_config->get('popup_error');
                 $popup_params = array('msg' => t($email_wrong), 'provider' => $userprofile->Provider, 'msgtype' => 'warning');
                 $popup_params['message_title'] = $this->module_config->get('popup_title');
                 return $form['email_popup'] = $this->getPopupForm($popup_params);
             } else {
                 unset($_SESSION['lrdata']);
                 $_SESSION['user_verify'] = 1;
                 return $this->createUser($userprofile);
             }
         }
     }
     return new RedirectResponse(Url::fromRoute('<current>')->toString());
 }
Exemplo n.º 19
0
 /**
  * @param string $email
  *
  * @return static
  *
  * @throws InvalidArgumentException
  */
 public static function loadByEmail($email)
 {
     $account = user_load_by_mail($email);
     if ($account) {
         return new static($account);
     }
     throw new InvalidArgumentException(t('Unable to load user with email %email', ['%email' => $email]));
 }
Exemplo n.º 20
0
 /**
  * Create new users with default field values.
  *
  * @param int $num
  *   Number of entities to create.
  * @param array $options
  *   Options array. This array can have "roles" key that provides an array of
  *   role names that the newly created user will need to be assigned.
  *
  * @return Response
  *   Response object.
  */
 public static function createRandom($num = 1, $options = array())
 {
     $options += array('roles' => array(), 'required_fields_only' => TRUE);
     $output = array();
     for ($i = 0; $i < $num; $i++) {
         // Get a random username.
         do {
             $username = Utils::getRandomString(20);
         } while (!is_null(user_validate_name($username)) || user_load_by_name($username));
         // Get a random email address.
         do {
             $email = $username . '@' . Utils::getRandomString(20) . '.com';
         } while (!is_null(user_validate_mail($email)) || user_load_by_mail($email));
         // Get a random password.
         $password = Utils::getRandomString();
         $response = User::registerUser($username, $email, $password, $options['roles']);
         if (!$response->getSuccess()) {
             $response->setVar($output);
             return $response;
         }
         $output[] = $response->getVar();
     }
     return new Response(TRUE, Utils::normalize($output), "");
 }
Exemplo n.º 21
0
 /**
  * @Given /^I visit the profile of "([^"]*)"$/
  */
 public function iVisitTheProfileOf($email)
 {
     if ($user = user_load_by_mail($email)) {
         return new Step\When('I visit "user/' . $user->uid . '"');
     } else {
         throw new Exception('No profile found with the email address: ' . $email);
     }
 }
 /**
  * given a drupal account, query ldap and get all user fields and save user account
  * (note: parameters are in odd order to match synchDrupalAccount handle)
  *
  * @param array $account drupal account object or null
  * @param array $user_edit drupal edit array in form user_save($account, $user_edit) would take.
  * @param array $ldap_user as user's ldap entry.  passed to avoid requerying ldap in cases where already present
  * @param boolean $save indicating if drupal user should be saved.  generally depends on where function is called from and if the
  *
  * @return result of user_save() function is $save is true, otherwise return TRUE on success or FALSE on any problem
  *   $user_edit data returned by reference
  *
  */
 public function provisionDrupalAccount($account = FALSE, &$user_edit, $ldap_user = NULL, $save = TRUE)
 {
     $watchdog_tokens = array();
     /**
      * @todo
      * -- add error catching for conflicts, conflicts should be checked before calling this function.
      *
      */
     if (!$account) {
         $account = new stdClass();
     }
     $account->is_new = TRUE;
     if (!$ldap_user && !isset($user_edit['name'])) {
         return FALSE;
     }
     if (!$ldap_user) {
         $watchdog_tokens['%username'] = $user_edit['name'];
         if ($this->drupalAcctProvisionServer) {
             $ldap_user = ldap_servers_get_user_ldap_data($user_edit['name'], $this->drupalAcctProvisionServer, 'ldap_user_prov_to_drupal');
         }
         if (!$ldap_user) {
             if ($this->detailedWatchdog) {
                 watchdog('ldap_user', '%username : failed to find associated ldap entry for username in provision.', $watchdog_tokens, WATCHDOG_DEBUG);
             }
             return FALSE;
         }
     }
     // dpm('ldap_user 675');dpm($ldap_user);
     if (!isset($user_edit['name']) && isset($account->name)) {
         $user_edit['name'] = $account->name;
         $watchdog_tokens['%username'] = $user_edit['name'];
     }
     //When using the multi-domain last authentication option
     //$ldap_server breaks beacause $this->drupalAcctProvisionServer is set on LDAP_USER_AUTH_SERVER_SID
     //So we need to check it's not the case before using ldap_servers_get_servers
     if ($this->drupalAcctProvisionServer && $this->drupalAcctProvisionServer != LDAP_USER_AUTH_SERVER_SID) {
         $ldap_server = ldap_servers_get_servers($this->drupalAcctProvisionServer, 'enabled', TRUE);
         // $ldap_user['sid']
         $params = array('account' => $account, 'user_edit' => $user_edit, 'prov_event' => LDAP_USER_EVENT_CREATE_DRUPAL_USER, 'module' => 'ldap_user', 'function' => 'provisionDrupalAccount', 'direction' => LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER);
         drupal_alter('ldap_entry', $ldap_user, $params);
         // look for existing drupal account with same puid.  if so update username and attempt to synch in current context
         $puid = $ldap_server->userPuidFromLdapEntry($ldap_user['attr']);
         $account2 = $puid ? $ldap_server->userUserEntityFromPuid($puid) : FALSE;
         if ($account2) {
             // synch drupal account, since drupal account exists
             // 1. correct username and authmap
             $this->entryToUserEdit($ldap_user, $user_edit, $ldap_server, LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER, array(LDAP_USER_EVENT_SYNCH_TO_DRUPAL_USER));
             $account = user_save($account2, $user_edit, 'ldap_user');
             user_set_authmaps($account, array("authname_ldap_user" => $user_edit['name']));
             // 2. attempt synch if appropriate for current context
             if ($account) {
                 $account = $this->synchToDrupalAccount($account, $user_edit, LDAP_USER_EVENT_SYNCH_TO_DRUPAL_USER, $ldap_user, TRUE);
             }
             return $account;
         } else {
             // create drupal account
             $this->entryToUserEdit($ldap_user, $user_edit, $ldap_server, LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER, array(LDAP_USER_EVENT_CREATE_DRUPAL_USER));
             if ($save) {
                 $watchdog_tokens = array('%drupal_username' => $user_edit['name']);
                 if (empty($user_edit['name'])) {
                     drupal_set_message(t('User account creation failed because of invalid, empty derived Drupal username.'), 'error');
                     watchdog('ldap_user', 'Failed to create Drupal account %drupal_username because drupal username could not be derived.', $watchdog_tokens, WATCHDOG_ERROR);
                     return FALSE;
                 }
                 if (!isset($user_edit['mail']) || !$user_edit['mail']) {
                     drupal_set_message(t('User account creation failed because of invalid, empty derived email address.'), 'error');
                     watchdog('ldap_user', 'Failed to create Drupal account %drupal_username because email address could not be derived by LDAP User module', $watchdog_tokens, WATCHDOG_ERROR);
                     return FALSE;
                 }
                 if ($account_with_same_email = user_load_by_mail($user_edit['mail'])) {
                     $watchdog_tokens['%email'] = $user_edit['mail'];
                     $watchdog_tokens['%duplicate_name'] = $account_with_same_email->name;
                     watchdog('ldap_user', 'LDAP user %drupal_username has email address
           (%email) conflict with a drupal user %duplicate_name', $watchdog_tokens, WATCHDOG_ERROR);
                     drupal_set_message(t('Another user already exists in the system with the same email address. You should contact the system administrator in order to solve this conflict.'), 'error');
                     return FALSE;
                 }
                 $account = user_save(NULL, $user_edit, 'ldap_user');
                 if (!$account) {
                     drupal_set_message(t('User account creation failed because of system problems.'), 'error');
                 } else {
                     user_set_authmaps($account, array('authname_ldap_user' => $account->name));
                     ldap_user_ldap_provision_semaphore('drupal_created', 'set', $account->name);
                 }
                 return $account;
             }
             return TRUE;
         }
     }
 }
 /**
  * testSubscribeAnonymous
  *
  * Steps performed:
  *   0. Preparation
  *   1. Subscribe anonymous via block
  *   2. Subscribe anonymous via subscription page
  *   3. Subscribe anonymous via multi block
  */
 function testSubscribeAnonymous()
 {
     // 0. Preparation
     // Login admin
     // Set permission for anonymous to subscribe
     // Enable newsletter block
     // Logout admin
     $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer content types', 'administer nodes', 'access administration pages', 'administer newsletters', 'administer permissions'));
     $this->drupalLogin($admin_user);
     // Create some newsletters for multi-sign up block.
     $this->drupalGet('admin/config/services/simplenews');
     for ($i = 0; $i < 5; $i++) {
         $this->clickLink(t('Add newsletter'));
         $name = $this->randomMachineName();
         $edit = array('name' => $name, 'id' => strtolower($name), 'description' => $this->randomString(20), 'opt_inout' => 'double');
         $this->drupalPostForm(NULL, $edit, t('Save'));
     }
     $newsletter_id = $this->getRandomNewsletter();
     $this->drupalLogout();
     //file_put_contents('output.html', $this->drupalGetContent());
     // 1. Subscribe anonymous via block
     // Subscribe + submit
     // Assert confirmation message
     // Assert outgoing email
     //
     // Confirm using mail link
     // Confirm using mail link
     // Assert confirmation message
     // Setup subscription block with subscription form.
     $block_settings = array('newsletters' => array($newsletter_id), 'message' => $this->randomMachineName(4));
     $single_block = $this->setupSubscriptionBlock($block_settings);
     // Testing invalid email error message.
     $mail = '@example.com';
     $edit = array('mail[0][value]' => $mail);
     $this->drupalPostForm('', $edit, t('Subscribe'));
     $this->assertText(t("The email address {$mail} is not valid"), t("Invalid email shows error."));
     // Now with valid email.
     $mail = $this->randomEmail(8);
     $edit = array('mail[0][value]' => $mail);
     $this->drupalPostForm('', $edit, t('Subscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $this->assertNotNull($subscriber, 'New subscriber entity successfully loaded.');
     $subscription = $subscriber->getSubscription($newsletter_id);
     $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_UNCONFIRMED, $subscription->status, t('Subscription is unconfirmed'));
     $confirm_url = $this->extractConfirmationLink($this->getMail(0));
     $this->drupalGet($confirm_url);
     $newsletter = simplenews_newsletter_load($newsletter_id);
     $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
     $this->drupalPostForm(NULL, array(), t('Subscribe'));
     $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
     // Test that it is possible to register with a mail address that is already
     // a subscriber.
     $site_config = $this->config('user.settings');
     $site_config->set('register', 'visitors');
     $site_config->set('verify_mail', false);
     $site_config->save();
     $edit = array('name' => $this->randomMachineName(), 'mail' => $mail, 'pass[pass1]' => $pass = $this->randomMachineName(), 'pass[pass2]' => $pass);
     $this->drupalPostForm('user/register', $edit, t('Create new account'));
     // Verify confirmation messages.
     $this->assertText(t('Registration successful. You are now logged in.'));
     // Verify that the subscriber has been updated and references to the correct
     // user.
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $account = user_load_by_mail($mail);
     $this->assertEqual($subscriber->getUserId(), $account->id());
     $this->assertEqual($account->getUsername(), $edit['name']);
     $this->drupalLogout();
     // Disable the newsletter block.
     $single_block->delete();
     // 2. Subscribe anonymous via subscription page
     // Subscribe + submit
     // Assert confirmation message
     // Assert outgoing email
     //
     // Confirm using mail link
     // Confirm using mail link
     // Assert confirmation message
     $mail = $this->randomEmail(8);
     $edit = array("subscriptions[{$newsletter_id}]" => '1', 'mail[0][value]' => $mail);
     $this->drupalPostForm('newsletter/subscriptions', $edit, t('Subscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
     $confirm_url = $this->extractConfirmationLink($this->getMail(2));
     $this->drupalGet($confirm_url);
     $newsletter = simplenews_newsletter_load($newsletter_id);
     $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
     $this->drupalPostForm($confirm_url, array(), t('Subscribe'));
     $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
     // 3. Subscribe anonymous via multi block
     // Setup subscription block with subscription form.
     $block_settings = array('newsletters' => array_keys(simplenews_newsletter_get_all()), 'message' => $this->randomMachineName(4));
     $multi_block = $this->setupSubscriptionBlock($block_settings);
     // Try to submit multi-signup form without selecting a newsletter.
     $mail = $this->randomEmail(8);
     $edit = array('mail[0][value]' => $mail);
     $this->drupalPostForm('', $edit, t('Subscribe'));
     $this->assertText(t('You must select at least one newsletter.'));
     // Now fill out the form and try again. The e-mail should still be listed.
     $edit = array('subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Subscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
     $confirm_url = $this->extractConfirmationLink($this->getMail(3));
     $this->drupalGet($confirm_url);
     $newsletter = simplenews_newsletter_load($newsletter_id);
     $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
     $this->drupalPostForm($confirm_url, array(), t('Subscribe'));
     $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
     // Try to subscribe again, this should not re-set the status to unconfirmed.
     $edit = array('mail[0][value]' => $mail, 'subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Subscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $this->assertNotEqual($subscriber, FALSE, 'New subscriber entity successfully loaded.');
     $subscription = $subscriber->getSubscription($newsletter_id);
     $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $subscription->status);
     // Now the same with the newsletter/subscriptions page.
     $mail = $this->randomEmail(8);
     $edit = array('mail[0][value]' => $mail);
     $this->drupalPostForm('newsletter/subscriptions', $edit, t('Subscribe'));
     $this->assertText(t('You must select at least one newsletter.'));
     // Now fill out the form and try again.
     $edit = array('subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Subscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
     $confirm_url = $this->extractConfirmationLink($this->getMail(5));
     $this->drupalGet($confirm_url);
     $newsletter = simplenews_newsletter_load($newsletter_id);
     $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
     $this->drupalPostForm($confirm_url, array(), t('Subscribe'));
     $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
     // Test unsubscribe on newsletter/subscriptions page.
     $edit = array('mail[0][value]' => $mail);
     $this->drupalPostForm('newsletter/subscriptions', $edit, t('Unsubscribe'));
     $this->assertText(t('You must select at least one newsletter.'));
     // Now fill out the form and try again.
     $edit = array('subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Unsubscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to cancel your subscription.'));
     $this->assertMailText(t('We have received a request to remove the @mail', array('@mail' => $mail)), 6);
     $confirm_url = $this->extractConfirmationLink($this->getMail(6));
     $mails = $this->drupalGetMails();
     $this->assertEqual($mails[0]['from'], '*****@*****.**');
     $this->assertEqual($mails[0]['headers']['From'], '"Drupal" <*****@*****.**>');
     $this->drupalGet($confirm_url);
     $newsletter = simplenews_newsletter_load($newsletter_id);
     $this->assertRaw(t('Are you sure you want to remove %user from the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
     $this->drupalPostForm($confirm_url, array(), t('Unsubscribe'));
     $this->assertRaw(t('%user was unsubscribed from the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber removed from newsletter'));
     // Visit the newsletter/subscriptions page with the hash.
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $hash = simplenews_generate_hash($subscriber->getMail(), 'manage');
     $this->drupalGet('newsletter/subscriptions/' . $subscriber->id() . '/' . REQUEST_TIME . '/' . $hash);
     $this->assertText(t('Subscriptions for @mail', array('@mail' => $mail)));
     $edit = array('subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Update'));
     $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $mail)));
     // Make sure the subscription is confirmed.
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $this->assertTrue($subscriber->isSubscribed($newsletter_id));
     $subscription = $subscriber->getSubscription($newsletter_id);
     $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $subscription->status);
     // Attempt to fetch the page using a wrong hash but correct format.
     $hash = simplenews_generate_hash($subscriber->getMail() . 'a', 'manage');
     $this->drupalGet('newsletter/subscriptions/' . $subscriber->id() . '/' . REQUEST_TIME . '/' . $hash);
     $this->assertResponse(404);
     // Attempt to unsubscribe a non-existing subscriber.
     $mail = $this->randomEmail();
     $edit = array('mail[0][value]' => $mail, 'subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm('newsletter/subscriptions', $edit, t('Unsubscribe'));
     $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to cancel your subscription.'));
     $this->assertMailText('is not subscribed to this mailing list', 7);
     // Test expired confirmation links.
     $edit = array('mail[0][value]' => $mail, 'subscriptions[' . $newsletter_id . ']' => TRUE);
     $this->drupalPostForm('newsletter/subscriptions', $edit, t('Subscribe'));
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $expired_timestamp = REQUEST_TIME - 86401;
     $hash = simplenews_generate_hash($subscriber->getMail(), 'add', $expired_timestamp);
     $url = 'newsletter/confirm/add/' . $subscriber->id() . '/' . $newsletter_id . '/' . $expired_timestamp . '/' . $hash;
     $this->drupalGet($url);
     $this->assertText(t('This link has expired.'));
     $this->drupalPostForm(NULL, array(), t('Request new confirmation mail'));
     $confirm_url = $this->extractConfirmationLink($this->getMail(9));
     $this->drupalGet($confirm_url);
     $newsletter = simplenews_newsletter_load($newsletter_id);
     $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
     $this->drupalPostForm($confirm_url, array(), t('Subscribe'));
     $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
     // Make sure the subscription is confirmed now.
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscriber = simplenews_subscriber_load_by_mail($mail);
     $this->assertTrue($subscriber->isSubscribed($newsletter_id));
     $subscription = $subscriber->getSubscription($newsletter_id);
     $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $subscription->status);
 }
Exemplo n.º 24
0
 public function getUserDetails($username)
 {
     $account = user_load_by_name($username);
     if (!$account) {
         // An email address might have been supplied instead of the username.
         $account = user_load_by_mail($username);
     }
     if ($account) {
         // The default library behavior is to use the username as the user_id.
         return array('user_id' => $account->name);
     }
     return FALSE;
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $mail = $form_state->getValue(array('mail', 0, 'value'));
     // Users should login to manage their subscriptions.
     if (\Drupal::currentUser()->isAnonymous() && ($user = user_load_by_mail($mail))) {
         $message = $user->isBlocked() ? $this->t('The email address %mail belongs to a blocked user.', array('%mail' => $mail)) : $this->t('There is an account registered for the e-mail address %mail. Please log in to manage your newsletter subscriptions.', array('%mail' => $mail));
         $form_state->setErrorByName('mail', $message);
     }
     // Unless the submit handler is 'update', if the newsletter checkboxes are
     // available, at least one must be checked.
     $update = in_array('::submitUpdate', $form_state->getSubmitHandlers());
     if (!$update && !$this->getSubscriptionWidget($form_state)->isHidden() && !count($form_state->getValue('subscriptions'))) {
         $form_state->setErrorByName('subscriptions', t('You must select at least one newsletter.'));
     }
     parent::validateForm($form, $form_state);
 }
function hook_brukar_client_user($edit)
{
    return user_load_by_mail($edit['mail']);
}
/**
 * Implementation of hook_civicrm_post
 * 
 * Add, update or delete drupal user account
 */
function leaveregistration_civicrm_post($op, $objectName, $objectId, &$objectRef)
{
    switch ($objectName) {
        case 'Email':
            switch ($op) {
                case 'create':
                case 'edit':
                    $contacts = civicrm_api("Contact", "get", array('version' => '3', 'sequential' => '1', 'id' => $objectRef->contact_id));
                    $contact = $contacts['values'][0];
                    $contact_sub_type = array();
                    if (is_array($contact['contact_sub_type'])) {
                        $contact_sub_type = $contact['contact_sub_type'];
                    } else {
                        $contact_sub_type[] = $contact['contact_sub_type'];
                    }
                    if (in_array('Employee', $contact_sub_type)) {
                        // if it`s a employee
                        $user = user_load_by_mail($contact['email']);
                        $roles = $user->roles;
                        if (isset($contact['contact_sub_type']) and in_array('Employee', $contact['contact_sub_type'])) {
                            $rid = array_search('employee', user_roles());
                            $roles[$rid] = 'employee';
                        }
                        // department head
                        $relationshiptypes = civicrm_api("RelationshipType", "get", array('version' => '3', 'sequential' => '1', 'name_a_b' => 'Department head'));
                        $relationshiptype = $relationshiptypes['values'][0];
                        $relationship_type_id = $relationshiptype['id'];
                        $relationships = civicrm_api("Relationship", "get", array('version' => '3', 'sequential' => '1', 'relationship_type_id' => $relationship_type_id, 'contact_id_b' => $contact['contact_id']));
                        if (!empty($relationships['values'][0])) {
                            $rid = array_search('department head', user_roles());
                            $roles[$rid] = 'department head';
                        }
                        // finance
                        $relationshiptypes = civicrm_api("RelationshipType", "get", array('version' => '3', 'sequential' => '1', 'name_a_b' => 'Finance of'));
                        $relationshiptype = $relationshiptypes['values'][0];
                        $relationship_type_id = $relationshiptype['id'];
                        $relationships = civicrm_api("Relationship", "get", array('version' => '3', 'sequential' => '1', 'relationship_type_id' => $relationship_type_id, 'contact_id_a' => $contact['contact_id']));
                        if (!empty($relationships['values'][0])) {
                            $rid = array_search('finance', user_roles());
                            $roles[$rid] = 'finance';
                        }
                        $username = '';
                        if ('' != $contact['first_name'] and '' != $contact['last_name']) {
                            // first_name
                            $contact['first_name'] = strtolower(trim($contact['first_name']));
                            $username = substr(strtolower($contact['first_name']), 0, 1);
                            // middle_name
                            if ('' != $contact['middle_name']) {
                                $contact['middle_name'] = strtolower(trim($contact['middle_name']));
                                if (false !== strpos($contact['middle_name'], ' ')) {
                                    $middle_names = explode(' ', $contact['middle_name']);
                                } else {
                                    $middle_names[] = $contact['middle_name'];
                                }
                                $username .= '.';
                                foreach ($middle_names as $key => $middle_name) {
                                    $username .= substr($middle_name, 0, 1);
                                }
                            }
                            // last_name
                            $contact['last_name'] = strtolower(trim($contact['last_name']));
                            $username .= '.' . $contact['last_name'];
                        } else {
                            $contact['email'] = strtolower(trim($contact['email']));
                            $username = substr($contact['email'], 0, strpos($contact['email'], '@'));
                        }
                        if (0 != $user->uid and $contact['email'] == $user->mail) {
                            // edit
                            $edit = array('mail' => $contact['email'], 'init' => $contact['email'], 'status' => 1, 'roles' => $roles);
                            $account = user_save($user, $edit);
                        } else {
                            // add
                            $edit = array('name' => $username, 'pass' => 'Welkom01', 'mail' => $contact['email'], 'init' => $contact['email'], 'status' => 1, 'roles' => $roles);
                            $account = user_save('', $edit);
                        }
                        if (!$account) {
                            CRM_Core_Session::setStatus(ts('A error occure on add/edit drupal account !'), ts('Add/edit drupal account'), 'error');
                        } else {
                            CRM_Core_Session::setStatus(ts('Drupal account added/updated !'), ts('Add/edit drupal account'), 'success');
                        }
                    }
                    break;
            }
            break;
        case 'Individual':
            switch ($op) {
                case 'trash':
                    $contacts = civicrm_api("Contact", "get", array('version' => '3', 'sequential' => '1', 'id' => $objectRef->id));
                    $contact = $contacts['values'][0];
                    $user = user_load_by_mail($contact['email']);
                    if (0 != $user->uid and $contact['email'] == $user->mail) {
                        user_delete($user->uid);
                        CRM_Core_Session::setStatus(ts('Drupal account deleted !'), ts('Delete drupal account'), 'success');
                    }
                    break;
            }
            break;
        case 'Relationship':
            switch ($op) {
                case 'create':
                case 'edit':
                    // department head
                    $contacts = civicrm_api("Contact", "get", array('version' => '3', 'sequential' => '1', 'id' => $objectRef->contact_id_b, 'contact_sub_type' => 'Employee'));
                    if (!empty($contacts['values'][0])) {
                        $contact = $contacts['values'][0];
                        $user = user_load_by_mail($contact['email']);
                        if (0 != $user->uid and $contact['email'] == $user->mail) {
                            $roles = $user->roles;
                            $relationshiptypes = civicrm_api("RelationshipType", "get", array('version' => '3', 'sequential' => '1', 'name_a_b' => 'Department head'));
                            $relationshiptype = $relationshiptypes['values'][0];
                            $relationship_type_id = $relationshiptype['id'];
                            if ($objectRef->relationship_type_id == $relationship_type_id and $objectRef->contact_id_b == $contact['contact_id']) {
                                $rid = array_search('department head', user_roles());
                                $roles[$rid] = 'department head';
                                $edit = array('roles' => $roles);
                                $account = user_save($user, $edit);
                                if (!$account) {
                                    CRM_Core_Session::setStatus(ts('A error occure on edit drupal contact, when add/edit relationship !'), ts('Add/edit relationship'), 'error');
                                } else {
                                    CRM_Core_Session::setStatus(ts('Drupal account updated, when add/edit relationship !'), ts('Add/edit relationship'), 'success');
                                }
                            }
                        }
                    }
                    // administration
                    $contacts = civicrm_api("Contact", "get", array('version' => '3', 'sequential' => '1', 'id' => $objectRef->contact_id_a, 'contact_sub_type' => 'Employee'));
                    if (!empty($contacts['values'][0])) {
                        $contact = $contacts['values'][0];
                        $user = user_load_by_mail($contact['email']);
                        if (0 != $user->uid and $contact['email'] == $user->mail) {
                            $roles = $user->roles;
                            // department head
                            $relationshiptypes = civicrm_api("RelationshipType", "get", array('version' => '3', 'sequential' => '1', 'name_a_b' => 'Administration of'));
                            $relationshiptype = $relationshiptypes['values'][0];
                            $relationship_type_id = $relationshiptype['id'];
                            if ($objectRef->relationship_type_id == $relationship_type_id and $objectRef->contact_id_a == $contact['contact_id']) {
                                $rid = array_search('administration', user_roles());
                                $roles[$rid] = 'administration';
                                $edit = array('roles' => $roles);
                                $account = user_save($user, $edit);
                                if (!$account) {
                                    CRM_Core_Session::setStatus(ts('A error occure on edit drupal contact, when add/edit relationship !'), ts('Add/edit relationship'), 'error');
                                } else {
                                    CRM_Core_Session::setStatus(ts('Drupal account updated, when add/edit relationship !'), ts('Add/edit relationship'), 'success');
                                }
                            }
                        }
                    }
                    break;
                case 'delete':
                    // department head
                    $contacts = civicrm_api("Contact", "get", array('version' => '3', 'sequential' => '1', 'id' => $objectRef->contact_id_b, 'contact_sub_type' => 'Employee'));
                    if (!empty($contacts['values'][0])) {
                        $contact = $contacts['values'][0];
                        $user = user_load_by_mail($contact['email']);
                        if (0 != $user->uid and $contact['email'] == $user->mail) {
                            $roles = $user->roles;
                            $relationshiptypes = civicrm_api("RelationshipType", "get", array('version' => '3', 'sequential' => '1', 'name_a_b' => 'Department head'));
                            $relationshiptype = $relationshiptypes['values'][0];
                            $relationship_type_id = $relationshiptype['id'];
                            if ($objectRef->relationship_type_id == $relationship_type_id and $objectRef->contact_id_b == $contact['contact_id']) {
                                $rid = array_search('department head', user_roles());
                                unset($roles[$rid]);
                                $edit = array('roles' => $roles);
                                $account = user_save($user, $edit);
                                if (!$account) {
                                    CRM_Core_Session::setStatus(ts('A error occure on edit drupal contact, when delete relationship !'), ts('Delete relationship'), 'error');
                                } else {
                                    CRM_Core_Session::setStatus(ts('Drupal account updated, when delete relationship !'), ts('Delete relationship'), 'success');
                                }
                            }
                        }
                    }
                    // administration
                    $contacts = civicrm_api("Contact", "get", array('version' => '3', 'sequential' => '1', 'id' => $objectRef->contact_id_a, 'contact_sub_type' => 'Employee'));
                    if (!empty($contacts['values'][0])) {
                        $contact = $contacts['values'][0];
                        $user = user_load_by_mail($contact['email']);
                        if (0 != $user->uid and $contact['email'] == $user->mail) {
                            $roles = $user->roles;
                            // department head
                            $relationshiptypes = civicrm_api("RelationshipType", "get", array('version' => '3', 'sequential' => '1', 'name_a_b' => 'Administration of'));
                            $relationshiptype = $relationshiptypes['values'][0];
                            $relationship_type_id = $relationshiptype['id'];
                            if ($objectRef->relationship_type_id == $relationship_type_id and $objectRef->contact_id_a == $contact['contact_id']) {
                                $rid = array_search('administration', user_roles());
                                unset($roles[$rid]);
                                $edit = array('roles' => $roles);
                                $account = user_save($user, $edit);
                                if (!$account) {
                                    CRM_Core_Session::setStatus(ts('A error occure on edit drupal contact, when add/edit relationship !'), ts('Add/edit relationship'), 'error');
                                } else {
                                    CRM_Core_Session::setStatus(ts('Drupal account updated, when add/edit relationship !'), ts('Add/edit relationship'), 'success');
                                }
                            }
                        }
                    }
                    break;
            }
            break;
    }
}
Exemplo n.º 28
0
function devis_user_profile_form_validate($form, &$form_state)
{
    // This is a check in case the javascript is disabled for whatever reason.
    if (isset($form['profile_budget_profile']['field_active_regions_belgium'])) {
        $belgium = FALSE;
        $count = 0;
        // Check if Belgium is selected among the choices.
        $lang = $form['profile_budget_profile']['field_active_regions_belgium']['#language'];
        foreach ($form_state['values']['profile_budget_profile']['field_active_regions_belgium'][$lang] as $k => $val) {
            $count++;
            if ($val['value'] == 'BEL') {
                $belgium = TRUE;
            }
        }
        // If Belgium is selected, then asign only Belgium as the value.
        if ($belgium && $count > 1) {
            $new_value = array($lang => array(0 => array('value' => 'BEL')));
            $value['#parents'] = array('profile_budget_profile', 'field_active_regions_belgium');
            form_set_value($value, $new_value, $form_state);
        }
    }
    if (isset($form_state['values']['mail'])) {
        // E-mail check for duplicate user.
        $user_check = user_load_by_mail($form_state['values']['mail']);
        if ($user_check && $form['#user']->uid != $user_check->uid) {
            $site_name = variable_get('site_name', '3devis.be');
            form_set_error('mail', t('The specified email is already registered in !site_name.', array('!site_name' => $site_name)));
        }
        // E-mail check.
        if (!valid_email_address($form_state['values']['mail'])) {
            form_set_error('mail', t('The specified email is not a valid email.'));
        }
    }
    devis_field_phone_belgium_validate($form, $form_state);
    devis_field_tva_validate($form, $form_state);
}
 /**
  * Prepares the message for sending.
  *
  * @param array $message
  *   An array containing the message data. The optional parameters are:
  *   - plain: Whether to send the message as plaintext only or HTML. If evaluates to TRUE,
  *     then the message will be sent as plaintext.
  *   - plaintext: Optional plaintext portion of a multipart email.
  *   - attachments: An array of arrays which describe one or more attachments.
  *     Existing files can be added by path, dinamically-generated files
  *     can be added by content. The internal array contains the following elements:
  *      - filepath: Relative Drupal path to an existing file (filecontent is NULL).
  *      - filecontent: The actual content of the file (filepath is NULL).
  *      - filename: The filename of the file.
  *      - filemime: The MIME type of the file.
  *      The array of arrays looks something like this:
  *      Array
  *      (
  *        [0] => Array
  *        (
  *         [filepath] => '/sites/default/files/attachment.txt'
  *         [filecontent] => 'My attachment.'
  *         [filename] => 'attachment.txt'
  *         [filemime] => 'text/plain'
  *        )
  *      )
  *
  * @return array
  *   All details of the message.
  */
 public function prepareMessage(array $message)
 {
     $module = $message['module'];
     $key = $message['key'];
     $to = $message['to'];
     $from = $message['from'];
     $subject = $message['subject'];
     $body = $message['body'];
     $headers = isset($message['params']['headers']) ? $message['params']['headers'] : array();
     $plain = isset($message['params']['plain']) ? $message['params']['plain'] : NULL;
     $plaintext = isset($message['params']['plaintext']) ? $message['params']['plaintext'] : NULL;
     $attachments = isset($message['params']['attachments']) ? $message['params']['attachments'] : array();
     $site_name = \Drupal::config('system.site')->get('name');
     //$site_mail = variable_get('site_mail', ini_get('sendmail_from'));
     $site_mail = \Drupal::config('system.site')->get('mail');
     /*$simple_address = variable_get('mimemail_simple_address', 0);*/
     // Override site mails default sender when using default engine.
     /*if ((empty($from) || $from == $site_mail)
         && variable_get('mimemail_engine', 'mimemail') == 'mimemail') {
         $mimemail_name = variable_get('mimemail_name', $site_name);
         $mimemail_mail = variable_get('mimemail_mail', $site_mail);
         $from = array(
           'name' => !empty($mimemail_name) ? $mimemail_name : $site_name,
           'mail' => !empty($mimemail_mail) ? $mimemail_mail : $site_mail,
         );
       }*/
     // Override site mails default sender when using default engine.
     if (empty($from) || $from == $site_mail) {
         $mimemail_name = \Drupal::config('mimemail.settings')->get('name');
         $mimemail_mail = \Drupal::config('mimemail.settings')->get('mail');
         $from = array('name' => !empty($mimemail_name) ? $mimemail_name : $site_name, 'mail' => !empty($mimemail_mail) ? $mimemail_mail : $site_mail);
     }
     // Body is empty, this is a plaintext message.
     if (empty($body)) {
         $plain = TRUE;
     } elseif (is_null($plain)) {
         if (is_object($to) && isset($to->data['mimemail_textonly'])) {
             $plain = $to->data['mimemail_textonly'];
         } elseif (is_string($to) && \Drupal::service('email.validator')->isValid($to)) {
             if (is_object($account = user_load_by_mail($to)) && isset($account->data['mimemail_textonly'])) {
                 $plain = $account->data['mimemail_textonly'];
                 // Might as well pass the user object to the address function.
                 $to = $account;
             }
         }
     }
     // Removing newline character introduced by _drupal_wrap_mail_line();
     $subject = str_replace(array("\n"), '', trim(MailFormatHelper::htmlToText($subject)));
     $hook = array('mimemail_message__' . $key, 'mimemail_message__' . $module . '__' . $key);
     $body = ['#theme' => 'mimemail_messages', '#module' => $module, '#key' => $key, '#recipient' => $to, '#subject' => $subject, '#body' => $body];
     $body = \Drupal::service('renderer')->render($body);
     /*foreach (module_implements('mail_post_process') as $module) {
         $function = $module . '_mail_post_process';
         $function($body, $key);
       }*/
     //$plain = $plain || variable_get('mimemail_textonly', 0);
     $from = MimeMailFormatHelper::mimeMailAddress($from);
     $mail = MimeMailFormatHelper::mimeMailHtmlBody($body, $subject, $plain, $plaintext, $attachments);
     $headers = array_merge($message['headers'], $headers, $mail['headers']);
     //$message['to'] = MimeMailFormatHelper::mimeMailAddress($to, $simple_address);
     $message['to'] = MimeMailFormatHelper::mimeMailAddress($to);
     $message['from'] = $from;
     $message['subject'] = $subject;
     $message['body'] = $mail['body'];
     $message['headers'] = MimeMailFormatHelper::mimeMailHeaders($headers, $from);
     return $message;
 }