コード例 #1
0
 /**
  * Tests mails are not sent when notify.$op is FALSE.
  *
  * @param string $op
  *   The operation being performed on the account.
  * @param array $mail_keys
  *   The mail keys to test for. Ignored by this test because we assert that no
  *   mails at all are sent.
  *
  * @dataProvider userMailsProvider
  */
 public function testUserMailsNotSent($op, array $mail_keys)
 {
     $this->config('user.settings')->set('notify.' . $op, FALSE)->save();
     $return = _user_mail_notify($op, $this->createUser());
     $this->assertFalse($return, '_user_mail_notify() returns FALSE.');
     $this->assertEmpty($this->getMails(), 'No emails sent by _user_mail_notify().');
 }
コード例 #2
0
 /**
  * Tests the action execution.
  *
  * @covers ::execute
  */
 public function testActionExecution()
 {
     $account = $this->prophesizeEntity(UserInterface::class);
     $mail_type = 'test_mail_type';
     $this->action->setContextValue('user', $account->reveal())->setContextValue('email_type', $mail_type);
     $this->action->execute();
     // To ge the notifications that were sent, we call the _user_mail_notify()
     // with no parameters.
     $notifications = _user_mail_notify();
     $this->assertSame([$mail_type => 1], $notifications);
 }
コード例 #3
0
ファイル: redhen.api.php プロジェクト: petergiesin/asfitness
/**
 * Act on the contact when the link to a drupal user account is modified
 *
 * @param string $op ( insert | update | delete )
 * @param $contact
 *  The RedhenContact object with the new user drupal user info
 * @param $old_contact
 *  The RedhenContact object with the old user info
 *
 * @return void
 */
function hook_redhen_contact_user_update($op, RedhenContact $contact, $old_contact = NULL)
{
    // Send "Welcome (no approval required)" email to new user.
    if ($op == 'insert') {
        $wrapper = entity_metadata_wrapper('redhen_contact', $contact);
        // Set _user_mail_notify specific operation.
        $op = 'register_no_approval_required';
        // Send an email.
        _user_mail_notify($op, $wrapper->user->value());
    }
}
コード例 #4
0
 /**
  * {@inheritdoc}
  */
 public function processItem($data)
 {
     try {
         $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]];
         $user = entity_create('user', $user_data);
         $user->save();
         _user_mail_notify('register_admin_created', $user);
         if ($data->attendee->amount_paid == $this->personalSponsorshipPrice) {
             $this->createUserProfile($user, TRUE);
         } else {
             $this->createUserProfile($user);
         }
     } catch (\Exception $e) {
         \Drupal::logger('eventbrite cron')->log(RfcLogLevel::ERROR, 'User {mail} hasn\'t been created.', ['mail' => $data->attendee->email]);
     }
 }
コード例 #5
0
 /**
  * {@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]);
         }
     }
 }
コード例 #6
0
 /**
  * {@inheritdoc}
  */
 public function processItem($data)
 {
     if (is_array($data)) {
         $name = explode(' ', $data[0]);
         $email = $data[1];
         $username = explode('@', $email);
         try {
             // build array of user data
             $user_data = ['mail' => $email, 'name' => $username[0], 'status' => 1, 'field_first_name' => ['value' => $name[0]], 'field_last_name' => ['value' => $name[1]]];
             // 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('eventninja queue')->log(RfcLogLevel::ERROR, 'User {mail} hasn\'t been created.', ['mail' => $email]);
         }
     }
 }
コード例 #7
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, FormStateInterface $form_state)
 {
     $account = $this->entity;
     $pass = $account->getPassword();
     $admin = $form_state->getValue('administer_users');
     $notify = !$form_state->isValueEmpty('notify');
     // Save has no return value so this cannot be tested.
     // Assume save has gone through correctly.
     $account->save();
     $form_state->set('user', $account);
     $form_state->setValue('uid', $account->id());
     $this->logger('user')->notice('New user: %name %email.', array('%name' => $form_state->getValue('name'), '%email' => '<' . $form_state->getValue('mail') . '>', 'type' => $account->link($this->t('Edit'), 'edit-form')));
     // Add plain text password into user account to generate mail tokens.
     $account->password = $pass;
     // New administrative account without notification.
     if ($admin && !$notify) {
         drupal_set_message($this->t('Created a new user account for <a href="@url">%name</a>. No email has been sent.', array('@url' => $account->url(), '%name' => $account->getUsername())));
     } elseif (!$admin && !\Drupal::config('user.settings')->get('verify_mail') && $account->isActive()) {
         _user_mail_notify('register_no_approval_required', $account);
         user_login_finalize($account);
         drupal_set_message($this->t('Registration successful. You are now logged in.'));
         $form_state->setRedirect('<front>');
     } elseif ($account->isActive() || $notify) {
         if (!$account->getEmail() && $notify) {
             drupal_set_message($this->t('The new user <a href="@url">%name</a> was created without an email address, so no welcome message was sent.', array('@url' => $account->url(), '%name' => $account->getUsername())));
         } else {
             $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
             if (_user_mail_notify($op, $account)) {
                 if ($notify) {
                     drupal_set_message($this->t('A welcome message with further instructions has been emailed to the new user <a href="@url">%name</a>.', array('@url' => $account->url(), '%name' => $account->getUsername())));
                 } else {
                     drupal_set_message($this->t('A welcome message with further instructions has been sent to your email address.'));
                     $form_state->setRedirect('<front>');
                 }
             }
         }
     } else {
         _user_mail_notify('register_pending_approval', $account);
         drupal_set_message($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your email address.'));
         $form_state->setRedirect('<front>');
     }
 }
コード例 #8
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $langcode = $this->languageManager->getCurrentLanguage()->getId();
     $account = $form_state->getValue('account');
     // Mail one time login URL and instructions using current language.
     $mail = _user_mail_notify('password_reset', $account, $langcode);
     if (!empty($mail)) {
         $this->logger('user')->notice('Password reset instructions mailed to %name at %email.', array('%name' => $account->getUsername(), '%email' => $account->getEmail()));
         drupal_set_message($this->t('Further instructions have been sent to your email address.'));
     }
     $form_state->setRedirect('user.page');
 }
コード例 #9
0
ファイル: Drupal8.php プロジェクト: kcristiano/civicrm-core
 /**
  * @inheritDoc
  */
 public function createUser(&$params, $mail)
 {
     $user = \Drupal::currentUser();
     $user_register_conf = \Drupal::config('user.settings')->get('register');
     $verify_mail_conf = \Drupal::config('user.settings')->get('verify_mail');
     // Don't create user if we don't have permission to.
     if (!$user->hasPermission('administer users') && $user_register_conf == 'admin_only') {
         return FALSE;
     }
     $account = entity_create('user');
     $account->setUsername($params['cms_name'])->setEmail($params[$mail]);
     // Allow user to set password only if they are an admin or if
     // the site settings don't require email verification.
     if (!$verify_mail_conf || $user->hasPermission('administer users')) {
         // @Todo: do we need to check that passwords match or assume this has already been done for us?
         $account->setPassword($params['cms_pass']);
     }
     // Only activate account if we're admin or if anonymous users don't require
     // approval to create accounts.
     if ($user_register_conf != 'visitors' && !$user->hasPermission('administer users')) {
         $account->block();
     }
     // Validate the user object
     $violations = $account->validate();
     if (count($violations)) {
         return FALSE;
     }
     try {
         $account->save();
     } catch (\Drupal\Core\Entity\EntityStorageException $e) {
         return FALSE;
     }
     // Send off any emails as required.
     // Possible values for $op:
     //    - 'register_admin_created': Welcome message for user created by the admin.
     //    - 'register_no_approval_required': Welcome message when user
     //      self-registers.
     //    - 'register_pending_approval': Welcome message, user pending admin
     //      approval.
     // @Todo: Should we only send off emails if $params['notify'] is set?
     switch (TRUE) {
         case $user_register_conf == 'admin_only' || $user->isAuthenticated():
             _user_mail_notify('register_admin_created', $account);
             break;
         case $user_register_conf == 'visitors':
             _user_mail_notify('register_no_approval_required', $account);
             break;
         case 'visitors_admin_approval':
             _user_mail_notify('register_pending_approval', $account);
             break;
     }
     return $account->id();
 }
コード例 #10
0
 /**
  * {@inheritdoc}
  */
 public function submit(array $form, FormStateInterface $form_state)
 {
     // Cancel account immediately, if the current user has administrative
     // privileges, no confirmation mail shall be sent, and the user does not
     // attempt to cancel the own account.
     if ($this->currentUser()->hasPermission('administer users') && empty($form_state['values']['user_cancel_confirm']) && $this->entity->id() != $this->currentUser()->id()) {
         user_cancel($form_state['values'], $this->entity->id(), $form_state['values']['user_cancel_method']);
         $form_state->setRedirect('user.admin_account');
     } else {
         // Store cancelling method and whether to notify the user in
         // $this->entity for user_cancel_confirm().
         $this->entity->user_cancel_method = $form_state['values']['user_cancel_method'];
         $this->entity->user_cancel_notify = $form_state['values']['user_cancel_notify'];
         $this->entity->save();
         _user_mail_notify('cancel_confirm', $this->entity);
         drupal_set_message($this->t('A confirmation request to cancel your account has been sent to your email address.'));
         $this->logger('user')->notice('Sent account cancellation request to %name %email.', array('%name' => $this->entity->label(), '%email' => '<' . $this->entity->getEmail() . '>'));
         $form_state->setRedirect('user.view', array('user' => $this->entity->id()));
     }
 }
コード例 #11
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $langcode = $this->languageManager->getCurrentLanguage()->id;
     $account = $form_state['values']['account'];
     // Mail one time login URL and instructions using current language.
     $mail = _user_mail_notify('password_reset', $account, $langcode);
     if (!empty($mail)) {
         watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->getUsername(), '%email' => $account->getEmail()));
         drupal_set_message($this->t('Further instructions have been sent to your email address.'));
     }
     $form_state['redirect_route']['route_name'] = 'user.page';
 }
コード例 #12
0
ファイル: User.php プロジェクト: nayanseth/meetups
 public function resetPassword($email)
 {
     $users = \user_load_multiple(array(), array('mail' => $email, 'status' => '1'));
     $account = \reset($users);
     if (isset($account->uid)) {
         $mail = \_user_mail_notify('password_reset', $account, null);
         if (!empty($mail)) {
             return true;
         }
     }
     return false;
 }
コード例 #13
0
ファイル: UserCancelForm.php プロジェクト: ddrozdik/dmaps
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Cancel account immediately, if the current user has administrative
     // privileges, no confirmation mail shall be sent, and the user does not
     // attempt to cancel the own account.
     if (!$form_state->isValueEmpty('access') && $form_state->isValueEmpty('user_cancel_confirm') && $this->entity->id() != $this->currentUser()->id()) {
         user_cancel($form_state->getValues(), $this->entity->id(), $form_state->getValue('user_cancel_method'));
         $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
     } else {
         // Store cancelling method and whether to notify the user in
         // $this->entity for
         // \Drupal\user\Controller\UserController::confirmCancel().
         $this->entity->user_cancel_method = $form_state->getValue('user_cancel_method');
         $this->entity->user_cancel_notify = $form_state->getValue('user_cancel_notify');
         $this->entity->save();
         _user_mail_notify('cancel_confirm', $this->entity);
         drupal_set_message($this->t('A confirmation request to cancel your account has been sent to your email address.'));
         $this->logger('user')->notice('Sent account cancellation request to %name %email.', array('%name' => $this->entity->label(), '%email' => '<' . $this->entity->getEmail() . '>'));
         $form_state->setRedirect('entity.user.canonical', array('user' => $this->entity->id()));
     }
 }
コード例 #14
0
 /**
  * {@inheritdoc}
  */
 public function execute()
 {
     $account = $this->getContextValue('user');
     $mail_type = $this->getContextValue('email_type');
     _user_mail_notify($mail_type, $account);
 }
コード例 #15
0
	/**
	 * This is the callback handler (referenced by routing.yml).
	 */
	public function callback_handler() {

		// Read Settings.
		$settings = \social_login_get_settings();

		// No need to do anything if we haven't received these arguments.
		if (isset($_POST) && !empty($_POST['connection_token']) && !empty($_POST['oa_action']) && in_array($_POST['oa_action'], array('social_login', 'social_link'))) {

			// Clear session.
			\social_login_clear_session();
			
			// API Connection Credentials.
			$api_subdomain = (!empty($settings['api_subdomain']) ? $settings['api_subdomain'] : '');
			$api_key = (!empty($settings['api_key']) ? $settings['api_key'] : '');
			$api_secret = (!empty($settings['api_secret']) ? $settings['api_secret'] : '');

			// API Connection Handler.
			$handler = (!empty($settings['http_handler']) ? $settings['http_handler'] : 'curl');
			$handler = ($handler == 'fsockopen' ? 'fsockopen' : 'curl');

			// API Connection Protocol.
			$protocol = (!empty($settings['http_protocol']) ? $settings['http_protocol'] : 'https');
			$protocol = ($protocol == 'http' ? 'http' : 'https');

			// Automatic or manual registration?
			$registration_method = (!empty($settings['registration_method']) ? $settings['registration_method'] : '');
			$registration_method = (in_array($registration_method, array(
					'manual',
					'auto_random_email',
					'auto_manual_email',
			)) ? $registration_method : 'manual');

			// Require approval?
			$registration_approval = (!empty($settings['registration_approval']) ? $settings['registration_approval'] : '');
			$registration_approval = (in_array($registration_approval, array(
					'inherit',
					'disable',
					'enable',
			)) ? $registration_approval : 'inherit');

			// Retrieved connection_token.
			$token = trim($_POST['connection_token']);

			// Settings missing.
			if (empty($api_subdomain) || empty($api_key) || empty($api_secret)) {
				drupal_set_message(t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
				\Drupal::logger('social_login')->notice('The API Settings are not filled out correctly', array());
			}
			// Settings filled out.
			else {

				// Request identity details API.
				$data = \social_login_do_api_request($handler, $protocol . '://' . $api_subdomain . '.api.oneall.com/connections/' . $token . '.json', array(
						'api_key' => $api_key,
						'api_secret' => $api_secret,
				));

				if (is_array($data) && !empty($data['http_data'])) {
					$social_data = @\Drupal\Component\Serialization\Json::decode($data['http_data']);

					// Everything seems to be ok.
					if (is_array($social_data) && isset($social_data['response']) && isset($social_data['response']['request']['status']['code']) && $social_data['response']['request']['status']['code'] == 200) {

						// The plugin that has been uses social_login/social_link.
						$data = $social_data['response']['result']['data'];

						// Save the social network data in a session.
						$_SESSION['social_login_session_open'] = 1;
						$_SESSION['social_login_session_time'] = time();
						$_SESSION['social_login_social_data'] = serialize($social_data);
						$_SESSION['social_login_origin'] = (!empty($_GET['origin']) ? $_GET['origin'] : '');

						// Unique user_token.
						$user_token = $data['user']['user_token'];

						// Extract identity.
						$identity = $data['user']['identity'];

						// Unique identity_token.
						$identity_token = $identity['identity_token'];

						// Social Network that has been used to connect.
						$provider_name = (!empty($identity['source']['name']) ? $identity['source']['name'] : t('Unkown'));

						// Try restoring the user for the token.
						$user_for_token = \social_login_get_user_for_user_token($user_token);
						
						// Existing user.
						if (is_object($user_for_token) && !empty($user_for_token->id())) {
							
							// Social Login Plugin used?
							if ($data['plugin']['key'] == 'social_login') {
								// Make sure that the user has not been blocked.
								$name = $user_for_token->get('name')->value;
								// $user_for_token->getAccountName();
								if (!user_is_blocked($name)) {
									user_login_finalize($user_for_token);
								} 
								else {
									drupal_set_message(t('Your account is blocked.'), 'error');
									// Clear session.
									\social_login_clear_session();
								}
							}
							// Social Link Plugin used?
							elseif ($data['plugin']['key'] == 'social_link') {

								// The user should be logged in.
								$user = \Drupal::currentUser();

								// User is logged in.
								if (is_object($user) && $user->isAuthenticated()) {

									// The existing token does not match the current user!
									if ($user_for_token->id() <> $user->id()) {
										drupal_set_message(t('This @social_network account is already linked to another user.', array(
												'@social_network' => $provider_name,
										)), 'error');
									}
									// The existing token matches the current user!
									else {
										// Link identity.
										if ($data['plugin']['data']['action'] == 'link_identity') {
											\social_login_map_identity_token_to_user_token($user, $identity_token, $user_token, $provider_name);
											drupal_set_message(t('The @social_network account has been linked to your account.', array(
													'@social_network' => $provider_name,
											)), 'status');
										}
										// Unlink identity.
										else {
											\social_login_unmap_identity_token($identity_token);
											drupal_set_message(t('The social network account has been unlinked from your account.'), 'status');
										}

										// Clear session.
										\social_login_clear_session();

										// Redirect to profile.
										\Drupal::logger('social_login')->notice('- '. __FUNCTION__ .'@'. __LINE__ .' redirecting to '. \Drupal::url('user.page'));
										return new RedirectResponse(\Drupal::url('user.page'));
									}
								}
								// User is not logged in.
								else {
									drupal_set_message(t('You must be logged in to perform this action.'), 'error');

									// Clear session.
									\social_login_clear_session();

									// Redirect to home.
									return new RedirectResponse(\Drupal::url('<front>'));
								}
							}
						}
						// New user.
						else {
							
							\Drupal::logger('social_login')->notice('- '. __FUNCTION__ .'@'. __LINE__ .' new user');
							
							// New users may register.
							if (\Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
								// Extract the user's email address.
								$user_email = '';
								$user_email_is_verified = NULL;
								$user_email_is_random = NULL;

								if (isset($identity['emails']) && is_array($identity['emails'])) {
									while (!$user_email_is_verified && (list(, $email) = each($identity['emails']))) {
										$user_email = $email['value'];
										$user_email_is_verified = (!empty($email['is_verified']));
									}
								}

								// The admin has chosen the automatic registration.
								if ($registration_method <> 'manual') {

									// No email address / Email address already exists.
									if (empty($user_email) || \social_login_get_uid_for_email($user_email) !== FALSE) {

										// The admin wants users to fill out their email manually.
										if ($registration_method == 'auto_manual_email') {

											// We have to fall back to the default registration.
											$registration_method = 'manual';
										}
										// The admin has enabled the usage of random email addresses.
										else {

											// Create a bogus email.
											$user_email = \social_login_create_random_email();

											// Flag - is used further down.
											$user_email_is_random = TRUE;
										}
									}
								}

								// Automatic registration is still enabled.
								if ($registration_method <> 'manual') {

									// If something goes wrong fall back to manual registration.
									$registration_method = 'manual';

									// Extract User Firstname.
									$user_first_name = (!empty($identity['name']['givenName']) ? $identity['name']['givenName'] : '');

									// Extract User Lastname.
									$user_last_name = (!empty($identity['name']['familyName']) ? $identity['name']['familyName'] : '');

									// Forge User Login.
									$user_login = '';
									if (!empty($identity['preferredUsername'])) {
										$user_login = $identity['preferredUsername'];
									}
									elseif (!empty($identity['displayName'])) {
										$user_login = $identity['displayName'];
									}
									elseif (!empty($identity['name']['formatted'])) {
										$user_login = $identity['name']['formatted'];
									}
									else {
										$user_login = trim($user_first_name . ' ' . $user_last_name);
									}

									// We absolutely need a unique username.
									if (strlen(trim($user_login)) == 0 || \social_login_get_uid_for_name(trim($user_login)) !== FALSE) {
										$i = 1;
										$user_login = $provider_name . t('User');
										while (\social_login_get_uid_for_name($user_login) !== FALSE) {
											$user_login = $provider_name . t('User') . $i++;
										}
									}

									// We also need a password.
									$user_password = user_password(8);

									// Check the approval setting.
									switch ($registration_approval) {
										// No approval required.
										case 'disable':
											$user_status = 1;
											break;

											// Manual approval required.
										case 'enable':
											$user_status = 0;
											break;

											// Use the system-wide setting.
										default:
											$user_status = \Drupal::config('user.settings')->get('register') == USER_REGISTER_VISITORS ? 1 : 0;
											break;
									}

									$user_roles = array();  // real user accounts get the authenticated user role.
									// Make sure at least one module implements our hook.
									if (count(\Drupal::moduleHandler()->getImplementations('social_login_default_user_roles')) > 0) {
										// Call modules that implements the hook.
										$user_roles = \Drupal::moduleHandler()->invokeAll('social_login_default_user_roles', $user_roles);
									}

									// Setup the user fields.
									$user_fields = array(
											'name' => $user_login,
											'mail' => $user_email,
											'pass' => $user_password,
											'status' => $user_status,
											'init' => $user_email,
											'roles' => $user_roles,
									);

									// Create a new user.
									$account = User::create($user_fields);
									$account->save();

									// The new account has been created correctly.
									if ($account !== FALSE) {

										// Disable Drupal legacy registration.
										$registration_method = 'auto';

										// Log the new user in.
										if (($uid = \Drupal::service("user.auth")->authenticate($user_login, $user_password)) !== FALSE) {

											// Loads a user object.
											$user = User::load($uid);

											user_login_finalize($user);

											// Send email if it's not a random email.
											if ($user_email_is_random !== TRUE) {
												// No approval required.
												if ($user_status == 1) {
													_user_mail_notify('register_no_approval_required', $user);
													drupal_set_message(t('You have succesfully created an account and linked it with your @social_network account.', array(
															'@social_network' => $provider_name,
													)), 'status');
												}
												// Approval required.
												else {
													$a = _user_mail_notify('register_pending_approval', $user);
													drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />You will receive an email once your account has been approved and you can then login with your @social_network account.', array(
															'@social_network' => $provider_name,
													)), 'status');
												}
											}
											// Random email used.
											else {
												drupal_set_message(t('You have succesfully created an account and linked it with your @social_network account.', array(
														'@social_network' => $provider_name,
												)), 'status');
											}
										}
										// For some reason we could not log the user in.
										else {
											// Redirect to login page (login manually).
											drupal_set_message(t('Error while logging you in, please try to login manually.'), 'error');
											\Drupal::logger('social_login')->error('- '. __FUNCTION__ .'@'. __LINE__ .' auto login, redirecting to '. \Drupal::url('user.login'));
											return new RedirectResponse(\Drupal::url('user.login'));
										}
									}
									// An error occured during user->save().
									else {
										// Redirect to registration page (register manually).
										drupal_set_message(t('Error while creating your user account, please try to register manually.'), 'error');
										\Drupal::logger('social_login')->error('- '. __FUNCTION__ .'@'. __LINE__ .' auto register, redirecting to '. \Drupal::url('user.register'));
										return new RedirectResponse(\Drupal::url('user.register'));
									}
								}

								// Use the legacy registration form?
								if ($registration_method == 'manual') {
									// Redirect to the registration page (+ prepopulate form with SESSION data).
									\Drupal::logger('social_login')->notice('- '. __FUNCTION__ .'@'. __LINE__ .' manual register, redirecting to '. \Drupal::url('user.register'));
									return new RedirectResponse(\Drupal::url('user.register'));
								}
							}
							// Registration disabled.
							else {
								drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
								return new RedirectResponse(\Drupal::url('<front>'));
							}
						}
					}
				}
				else {
					\Drupal::logger('social_login')->error('- '. __FUNCTION__ .'@'. __LINE__ .' invalid JSON received from resource');
				}
			}
		}

		// Return to the front page.
		return new RedirectResponse(\Drupal::url('<front>'));
	}
コード例 #16
0
 /**
  * Send account email.
  *
  * @param \Drupal\user\UserInterface $user
  *   User who should receive the notification.
  * @param string $email_type
  *   Type of email to be sent.
  */
 protected function doExecute(UserInterface $user, $email_type)
 {
     _user_mail_notify($email_type, $user);
 }
コード例 #17
0
ファイル: UserSync.php プロジェクト: kingsj/core
 /**
  * Create missed Drupal accounts 
  * 
  * @return void
  */
 protected function createMissedDrupalAccounts()
 {
     if (!defined('LC_SUPPRESS_EMAIL_ALREADY_EXISTS_MESSAGE')) {
         define('LC_SUPPRESS_EMAIL_ALREADY_EXISTS_MESSAGE', true);
     }
     foreach ($this->accountsMissedInDrupal as $k => $account) {
         if ($this->checkUserAccountsPerStepCounter()) {
             $newAccount = new \stdclass();
             $newAccountData = array('is_new' => true, 'name' => $this->getNameFromEmail($account['login']), 'mail' => $account['login'], 'pass' => user_password(), 'status' => true);
             if (user_save($newAccount, $newAccountData)) {
                 $this->drupalAccountNames[] = $newAccount->name;
                 \XLite\Core\Database::getRepo('XLite\\Model\\Profile')->linkProfiles(\XLite\Core\Database::getRepo('XLite\\Model\\Profile')->find($account['profile_id']), $newAccount->uid);
                 if (variable_get('lc_user_sync_notify', false)) {
                     // Send notification with one time login URL and instructions
                     _user_mail_notify('password_reset', $newAccount);
                 }
                 unset($this->accountsMissedInDrupal[$k]);
             }
         } else {
             break;
         }
     }
 }
コード例 #18
0
 public function createUser($userprofile)
 {
     if (isset($userprofile->ID) && !empty($userprofile->ID)) {
         $user_config = \Drupal::config('user.settings');
         $user_register = $user_config->get('register');
         if ($user_register == 'visitors' || $user_register == 'visitors_admin_approval' || $this->module_config->get('admin_login') == 1) {
             $newUserStatus = 0;
             if ($user_register != 'visitors_admin_approval' && ($user_register == 'visitors' || $this->module_config->get('admin_login') == 1)) {
                 $newUserStatus = 1;
             }
             $data = $this->checkExistUsername($userprofile);
             //set up the user fields
             $password = user_password(32);
             $fields = array('name' => $data['username'], 'mail' => $userprofile->Email_value, 'init' => $userprofile->Email_value, 'pass' => $password, 'status' => $newUserStatus);
             $new_user = User::create($fields);
             $this->field_create_user_object($new_user, $userprofile);
             $new_user->save();
             // Log notice and invoke Rules event if new user was succesfully created
             if ($new_user->id()) {
                 \Drupal::logger('sociallogin')->notice('New user created. Username %username, UID: %uid', array('%username' => $new_user->getUsername(), '%uid' => $new_user->id()));
                 //  return $new_user;
                 $this->connection->insert('loginradius_mapusers')->fields(array('user_id' => $new_user->id(), 'provider' => $userprofile->Provider, 'provider_id' => $userprofile->ID))->execute();
                 $this->downloadProfilePic($userprofile->ImageUrl, $userprofile->ID, $new_user);
                 //Advanced module LR Code Hook Start
                 if (count(\Drupal::moduleHandler()->getImplementations('add_user_data_after_save')) > 0) {
                     // Call all modules that implement the hook, and let them make changes to $variables.
                     \Drupal::moduleHandler()->invokeAll('add_user_data_after_save', [$new_user, $userprofile]);
                 }
                 //Advanced module LR Code Hook End
                 $status = FALSE;
                 if ($user_config->get('verify_mail') == 1 && $this->module_config->get('skip_email_verification') == 1 || !$user_config->get('verify_mail')) {
                     $status = TRUE;
                 }
                 if ($new_user->isActive() && $status && $_SESSION['user_verify'] != 1) {
                     $new_user->setLastLoginTime(REQUEST_TIME);
                 }
             } else {
                 // Something went wrong
                 drupal_set_message(t('Creation of user account failed. Please contact site administrator.'), 'error');
                 \Drupal::logger('sociallogin')->error('Could not create new user.');
                 return FALSE;
             }
             //Advanced module LR Code Hook Start
             // Make sure at least one module implements our hook.
             if (count(\Drupal::moduleHandler()->getImplementations('check_send_verification_email')) > 0) {
                 // Call all modules that implement the hook, and let them make changes to $variables.
                 $userprofile->Password = $form_state['values']['pass'];
                 $result = \Drupal::moduleHandler()->invokeAll('check_send_verification_email', $account, $userprofile);
                 if (isset($result['lr_social_invite_message_popup'])) {
                     return array('lr_social_invite_message_popup' => $result['lr_social_invite_message_popup']);
                 }
                 $status = end($result);
             }
             //Advanced module LR Code Hook End
             if ($new_user->isActive() && $status && $_SESSION['user_verify'] != 1) {
                 if ($this->module_config->get('welcome_email') == 1) {
                     $params = array('account' => $new_user, 'pass' => $password);
                     \Drupal::service('plugin.manager.mail')->mail('sociallogin', 'welcome_email', $new_user->getEmail(), $new_user->getPreferredLangcode(), $params);
                 }
                 return $this->provideLogin($new_user, $userprofile);
             } elseif ($user_register != 'visitors_admin_approval' && ($new_user->isActive() || $_SESSION['user_verify'] == 1 && $status)) {
                 // Require email confirmation
                 _user_mail_notify('status_activated', $new_user);
                 $_SESSION['user_verify'] = 0;
                 drupal_set_message(t('Once you have verified your e-mail address, you may log in via Social Login.'));
                 return new RedirectResponse(Url::fromRoute('user.login')->toString());
             } else {
                 _user_mail_notify('register_pending_approval', $new_user);
                 drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.'));
                 return new RedirectResponse(Url::fromRoute('user.login')->toString());
             }
         } else {
             drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
             return new RedirectResponse(Url::fromRoute('user.login')->toString());
         }
     }
 }
コード例 #19
0
ファイル: User.php プロジェクト: ravindrasingh22/Drupal-8-rc
 /**
  * {@inheritdoc}
  */
 public function postSave(EntityStorageInterface $storage, $update = TRUE)
 {
     parent::postSave($storage, $update);
     if ($update) {
         $session_manager = \Drupal::service('session_manager');
         // If the password has been changed, delete all open sessions for the
         // user and recreate the current one.
         if ($this->pass->value != $this->original->pass->value) {
             $session_manager->delete($this->id());
             if ($this->id() == \Drupal::currentUser()->id()) {
                 \Drupal::service('session')->migrate();
             }
         }
         // If the user was blocked, delete the user's sessions to force a logout.
         if ($this->original->status->value != $this->status->value && $this->status->value == 0) {
             $session_manager->delete($this->id());
         }
         // Send emails after we have the new user object.
         if ($this->status->value != $this->original->status->value) {
             // The user's status is changing; conditionally send notification email.
             $op = $this->status->value == 1 ? 'status_activated' : 'status_blocked';
             _user_mail_notify($op, $this);
         }
     }
 }
コード例 #20
0
ファイル: Checkout.php プロジェクト: kingsj/core
 /**
  * Save anonymous profile
  * FIXME
  *
  * @return void
  */
 protected function saveAnonymousProfile()
 {
     parent::saveAnonymousProfile();
     $pass = user_password();
     $status = variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS;
     $data = array('name' => \XLite\Core\Session::getInstance()->order_username, 'init' => $this->getCart()->getOrigProfile()->getLogin(), 'mail' => $this->getCart()->getOrigProfile()->getLogin(), 'roles' => array(), 'status' => $status, 'pass' => $pass);
     $account = user_save('', $data);
     if ($account) {
         $account->password = $pass;
         if ($account->status) {
             _user_mail_notify('register_no_approval_required', $account);
         } else {
             _user_mail_notify('register_pending_approval', $account);
         }
         $this->getCart()->getProfile()->setCmsName('');
         $this->getCart()->getProfile()->setCmsProfileId(0);
         $this->getCart()->getOrigProfile()->setPassword(md5($pass));
         \XLite\Core\Database::getRepo('XLite\\Model\\Profile')->linkProfiles($this->getCart()->getOrigProfile(), $account->uid);
     }
     unset(\XLite\Core\Session::getInstance()->order_username);
 }