Example #1
0
 /**
  * Sets whether the admin menu is in compact mode or not.
  *
  * @param string $mode
  *   Valid values are 'on' and 'off'.
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function compactPage($mode)
 {
     user_cookie_save(array('admin_compact_mode' => $mode == 'on'));
     return $this->redirect('<front>');
 }
Example #2
0
 /**
  * Overrides Drupal\Core\Entity\EntityForm::save().
  */
 public function save(array $form, array &$form_state)
 {
     $comment = $this->entity;
     $entity = $comment->getCommentedEntity();
     $field_name = $comment->getFieldName();
     $uri = $entity->urlInfo();
     if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
         // Save the anonymous user information to a cookie for reuse.
         if ($this->currentUser->isAnonymous()) {
             user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
         }
         $comment->save();
         $form_state['values']['cid'] = $comment->id();
         // Add an entry to the watchdog log.
         watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->getSubject()), WATCHDOG_NOTICE, l(t('View'), 'comment/' . $comment->id(), array('fragment' => 'comment-' . $comment->id())));
         // Explain the approval queue if necessary.
         if (!$comment->isPublished()) {
             if (!$this->currentUser->hasPermission('administer comments')) {
                 drupal_set_message($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
             }
         } else {
             drupal_set_message($this->t('Your comment has been posted.'));
         }
         $query = array();
         // Find the current display page for this comment.
         $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
         $page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
         if ($page > 0) {
             $query['page'] = $page;
         }
         // Redirect to the newly posted comment.
         $uri->setOption('query', $query);
         $uri->setOption('fragment', 'comment-' . $comment->id());
     } else {
         watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject()), WATCHDOG_WARNING);
         drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject())), 'error');
         // Redirect the user to the entity they are commenting on.
     }
     $form_state['redirect_route'] = $uri;
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, array &$form_state)
 {
     $user = $this->currentUser();
     $language_interface = $this->languageManager->getCurrentLanguage();
     $message = $this->entity;
     $sender = clone $this->entityManager->getStorage('user')->load($user->id());
     if ($user->isAnonymous()) {
         // At this point, $sender contains an anonymous user, so we need to take
         // over the submitted form values.
         $sender->name = $message->getSenderName();
         $sender->mail = $message->getSenderMail();
         // Save the anonymous user information to a cookie for reuse.
         // @todo remove when https://www.drupal.org/node/749748 is in.
         user_cookie_save(array('name' => $message->getSenderName(), 'mail' => $message->getSenderMail()));
         // For the email message, clarify that the sender name is not verified; it
         // could potentially clash with a username on this site.
         $sender->name = $this->t('!name (not verified)', array('!name' => $message->getSenderName()));
     }
     // Build email parameters.
     $params['contact_message'] = $message;
     $params['sender'] = $sender;
     if (!$message->isPersonal()) {
         // Send to the category recipient(s), using the site's default language.
         $category = $message->getCategory();
         $params['contact_category'] = $category;
         $to = implode(', ', $category->recipients);
         $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId();
     } elseif ($recipient = $message->getPersonalRecipient()) {
         // Send to the user in the user's preferred language.
         $to = $recipient->getEmail();
         $recipient_langcode = $recipient->getPreferredLangcode();
         $params['recipient'] = $recipient;
     } else {
         throw new \RuntimeException($this->t('Unable to determine message recipient.'));
     }
     // Send email to the recipient(s).
     $key_prefix = $message->isPersonal() ? 'user' : 'page';
     drupal_mail('contact', $key_prefix . '_mail', $to, $recipient_langcode, $params, $sender->getEmail());
     // If requested, send a copy to the user, using the current language.
     if ($message->copySender()) {
         drupal_mail('contact', $key_prefix . '_copy', $sender->getEmail(), $language_interface->id, $params, $sender->getEmail());
     }
     // If configured, send an auto-reply, using the current language.
     if (!$message->isPersonal() && $category->reply) {
         // User contact forms do not support an auto-reply message, so this
         // message always originates from the site.
         drupal_mail('contact', 'page_autoreply', $sender->getEmail(), $language_interface->id, $params);
     }
     $this->flood->register('contact', $this->config('contact.settings')->get('flood.interval'));
     if (!$message->isPersonal()) {
         watchdog('contact', '%sender-name (@sender-from) sent an email regarding %category.', array('%sender-name' => $sender->getUsername(), '@sender-from' => $sender->getEmail(), '%category' => $category->label()));
     } else {
         watchdog('contact', '%sender-name (@sender-from) sent %recipient-name an email.', array('%sender-name' => $sender->getUsername(), '@sender-from' => $sender->getEmail(), '%recipient-name' => $message->getPersonalRecipient()->getUsername()));
     }
     drupal_set_message($this->t('Your message has been sent.'));
     // To avoid false error messages caused by flood control, redirect away from
     // the contact form; either to the contacted user account or the front page.
     if ($message->isPersonal() && $user->hasPermission('access user profiles')) {
         $form_state['redirect_route'] = $message->getPersonalRecipient()->urlInfo();
     } else {
         $form_state['redirect_route']['route_name'] = '<front>';
     }
     // Save the message. In core this is a no-op but should contrib wish to
     // implement message storage, this will make the task of swapping in a real
     // storage controller straight-forward.
     $message->save();
 }
Example #4
0
function onelogin_saml_auth($auth)
{
    $username = '';
    $email = '';
    $autocreate = variable_get('saml_options_autocreate', FALSE);
    // Get the NameId.
    $nameId = $auth->getNameId();
    if (empty($nameId)) {
        drupal_set_message("A NameId could not be found. Please supply a NameId in your SAML Response.", 'error', FALSE);
        drupal_goto();
    }
    // Get SAML attributes
    $attrs = $auth->getAttributes();
    $usernameFromEmail = variable_get('saml_options_username_from_email', FALSE);
    if (!empty($attrs)) {
        $usernameMapping = variable_get('saml_attr_mapping_username');
        $mailMapping = variable_get('saml_attr_mapping_email');
        // Try to get $email and $username from attributes of the SAML Response
        if (!empty($usernameMapping) && isset($attrs[$usernameMapping]) && !empty($attrs[$usernameMapping][0])) {
            $username = $attrs[$usernameMapping][0];
        }
        if (!empty($mailMapping) && isset($attrs[$mailMapping]) && !empty($attrs[$mailMapping][0])) {
            $email = $attrs[$mailMapping][0];
        }
    }
    // If there are attrs but the mail is in NameID try to obtain it
    if (empty($email) && strpos($nameId, '@')) {
        $email = $nameId;
    }
    if (empty($username) && $usernameFromEmail) {
        $username = str_replace('@', '.', $email);
    }
    $matcher = variable_get('saml_options_account_matcher');
    if ($matcher == 'username') {
        if (empty($username)) {
            drupal_set_message("Username value not found on the SAML Response. Username was selected as the account matcher field. Review at the settings the username mapping and be sure that the IdP provides this value", 'error', FALSE);
            drupal_goto();
        }
        // Query for active users given an usermail.
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'user')->propertyCondition('status', 1)->propertyCondition('name', $username);
    } else {
        if (empty($email)) {
            drupal_set_message("Email value not found on the SAML Response. Email was selected as the account matcher field. Review at the settings the username mapping and be sure that the IdP provides this value", 'error', FALSE);
            drupal_goto();
        }
        // Query for active users given an e-mail address.
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'user')->propertyCondition('status', 1)->propertyCondition('mail', $email);
    }
    $syncroles = variable_get('saml_options_syncroles', FALSE);
    $roles = array();
    if ($syncroles) {
        // saml_attr_mapping_role
        $roleMapping = variable_get('saml_attr_mapping_role', '');
        if (!empty($roleMapping) && isset($attrs[$roleMapping]) && !empty($attrs[$roleMapping])) {
            $adminsRole = explode(',', variable_get('saml_role_mapping_administrator', ''));
            // Add here your customRoleMapping directly
            // $customRole = array ('value1', $value2);
            $administrator = user_role_load_by_name('administrator');
            $adminWeight = $administrator->rid;
            $roleWeight = 0;
            foreach ($attrs[$roleMapping] as $samlRole) {
                $samlRole = trim($samlRole);
                if (empty($samlRole)) {
                    break;
                } else {
                    if (in_array($samlRole, $adminsRole)) {
                        if ($roleWeight < $adminWeight) {
                            $roleWeight = $adminWeight;
                        }
                        break;
                    } else {
                        if ($loadedRole = user_role_load_by_name($samlRole)) {
                            $roles[$loadedRole->rid] = $loadedRole->name;
                        }
                    }
                }
            }
            switch ($roleWeight) {
                // case 5:
                //   $roles = array(5 => 'customrole');
                //   break;
                case $adminWeight:
                    $roles[$adminWeight] = 'administrator';
                    break;
                case DRUPAL_AUTHENTICATED_RID:
                    // default value => 2
                // default value => 2
                default:
                    $roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
                    break;
            }
        }
    }
    // If a user exists, attempt to authenticate.
    $result = $query->execute();
    if ($result && ($user = user_load(key($result['user'])))) {
        $GLOBALS['user'] = $user;
        $form_state['uid'] = $user->uid;
        if (!empty($roles)) {
            try {
                $fields = array('roles' => $roles);
                user_save($user, $fields);
            } catch (Exception $e) {
                return FALSE;
            }
        }
        user_login_finalize($form_state);
        user_cookie_save(array('drupal_saml_login' => '1'));
    } else {
        if ($autocreate) {
            // If auto-privisioning is enabled but there are no required attributes, we need to stop.
            if (empty($email) || empty($username)) {
                drupal_set_message("Auto-provisioning accounts requires a username and email address. Please supply both in your SAML response.", 'error', FALSE);
                drupal_goto();
            }
            $fields = array('name' => $username, 'mail' => $email, 'pass' => user_password(16), 'status' => 1, 'init' => $email, 'timezone' => date_default_timezone_get());
            if (!empty($roles)) {
                $fields['roles'] = $roles;
            }
            try {
                $user = user_save(NULL, $fields);
                $GLOBALS['user'] = $user;
                $form_state['uid'] = $user->uid;
                user_login_finalize($form_state);
                user_cookie_save(array('drupal_saml_login' => '1'));
            } catch (Exception $e) {
                return FALSE;
            }
        } else {
            drupal_set_message("User '" . ($matcher == 'username' ? $username : $email) . "' not found.", 'error', FALSE);
            drupal_goto();
        }
    }
}