/**
  * Implements \Drupal\Core\Form\FormInterface::validateForm().
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $form_state->set('notify_emails', []);
     if (!$form_state->isValueEmpty('update_notify_emails')) {
         $valid = array();
         $invalid = array();
         foreach (explode("\n", trim($form_state->getValue('update_notify_emails'))) as $email) {
             $email = trim($email);
             if (!empty($email)) {
                 if (valid_email_address($email)) {
                     $valid[] = $email;
                 } else {
                     $invalid[] = $email;
                 }
             }
         }
         if (empty($invalid)) {
             $form_state->set('notify_emails', $valid);
         } elseif (count($invalid) == 1) {
             $form_state->setErrorByName('update_notify_emails', $this->t('%email is not a valid email address.', array('%email' => reset($invalid))));
         } else {
             $form_state->setErrorByName('update_notify_emails', $this->t('%emails are not valid email addresses.', array('%emails' => implode(', ', $invalid))));
         }
     }
     parent::validateForm($form, $form_state);
 }
示例#2
0
 /**
  * Implements \Drupal\Core\Form\FormInterface::validateForm().
  */
 public function validateForm(array &$form, array &$form_state)
 {
     $form_state['notify_emails'] = array();
     if (!empty($form_state['values']['update_notify_emails'])) {
         $valid = array();
         $invalid = array();
         foreach (explode("\n", trim($form_state['values']['update_notify_emails'])) as $email) {
             $email = trim($email);
             if (!empty($email)) {
                 if (valid_email_address($email)) {
                     $valid[] = $email;
                 } else {
                     $invalid[] = $email;
                 }
             }
         }
         if (empty($invalid)) {
             $form_state['notify_emails'] = $valid;
         } elseif (count($invalid) == 1) {
             $this->setFormError('update_notify_emails', $form_state, $this->t('%email is not a valid email address.', array('%email' => reset($invalid))));
         } else {
             $this->setFormError('update_notify_emails', $form_state, $this->t('%emails are not valid email addresses.', array('%emails' => implode(', ', $invalid))));
         }
     }
     parent::validateForm($form, $form_state);
 }
示例#3
0
 /**
  * Form element validation handler for #type 'email'.
  *
  * Note that #maxlength and #required is validated by _form_validate() already.
  */
 public static function validateEmail(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $value = trim($element['#value']);
     $form_state->setValueForElement($element, $value);
     if ($value !== '' && !valid_email_address($value)) {
         $form_state->setError($element, t('The email address %mail is not valid.', array('%mail' => $value)));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $added = array();
     $invalid = array();
     $unsubscribed = array();
     $checked_newsletters = array_keys(array_filter($form_state->getValue('newsletters')));
     $langcode = $form_state->getValue('language');
     $emails = preg_split("/[\\s,]+/", $form_state->getValue('emails'));
     foreach ($emails as $email) {
         $email = trim($email);
         if ($email == '') {
             continue;
         }
         if (valid_email_address($email)) {
             $subscriber = simplenews_subscriber_load_by_mail($email);
             /** @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager */
             $subscription_manager = \Drupal::service('simplenews.subscription_manager');
             foreach (simplenews_newsletter_load_multiple($checked_newsletters) as $newsletter) {
                 // If there is a valid subscriber, check if there is a subscription for
                 // the current newsletter and if this subscription has the status
                 // unsubscribed.
                 $is_unsubscribed = $subscriber ? $subscriber->isUnsubscribed($newsletter->id()) : FALSE;
                 if (!$is_unsubscribed || $form_state->getValue('resubscribe') == TRUE) {
                     $subscription_manager->subscribe($email, $newsletter->id(), FALSE, 'mass subscribe', $langcode);
                     $added[] = $email;
                 } else {
                     $unsubscribed[$newsletter->label()][] = $email;
                 }
             }
         } else {
             $invalid[] = $email;
         }
     }
     if ($added) {
         $added = implode(", ", $added);
         drupal_set_message(t('The following addresses were added or updated: %added.', array('%added' => $added)));
         $list_names = array();
         foreach (simplenews_newsletter_load_multiple($checked_newsletters) as $newsletter) {
             $list_names[] = $newsletter->label();
         }
         drupal_set_message(t('The addresses were subscribed to the following newsletters: %newsletters.', array('%newsletters' => implode(', ', $list_names))));
     } else {
         drupal_set_message(t('No addresses were added.'));
     }
     if ($invalid) {
         $invalid = implode(", ", $invalid);
         drupal_set_message(t('The following addresses were invalid: %invalid.', array('%invalid' => $invalid)), 'error');
     }
     foreach ($unsubscribed as $name => $subscribers) {
         $subscribers = implode(", ", $subscribers);
         drupal_set_message(t('The following addresses were skipped because they have previously unsubscribed from %name: %unsubscribed.', array('%name' => $name, '%unsubscribed' => $subscribers)), 'warning');
     }
     if (!empty($unsubscribed)) {
         drupal_set_message(t("If you would like to resubscribe them, use the 'Force resubscription' option."), 'warning');
     }
     // Return to the parent page.
     $form_state->setRedirect('view.simplenews_subscribers.page_1');
 }
示例#5
0
function os_poker_admin_form_validate($from, &$form_state)
{
    $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
    if ($op != t('Reset to defaults')) {
        if (!valid_email_address($form_state['values']['os_poker_abuse_mail_to'])) {
            form_set_error('os_poker_abuse_mail_to', t('The e-mail address you specified is not valid.'));
        }
    }
}
示例#6
0
 /**
  * Validates a user account.
  */
 public function entityValidate($account)
 {
     if (empty($account->name->value) || empty($account->mail->value) || !valid_email_address($account->mail->value)) {
         throw new ValidationException('User name missing or email not valid.');
     }
     if ($this->configuration['defuse_mail']) {
         $account->mail = $account->mail->value . '_test';
     }
     // Remove pass from $account if the password is unchanged.
     if (isset($account->feeds_original_pass) && $account->pass == $account->feeds_original_pass) {
         unset($account->pass);
     }
 }
示例#7
0
 /**
  * {@inheritdoc}
  */
 public function validate(array $form, FormStateInterface $form_state)
 {
     parent::validate($form, $form_state);
     // Validate and each email recipient.
     $recipients = explode(',', $form_state['values']['recipients']);
     foreach ($recipients as &$recipient) {
         $recipient = trim($recipient);
         if (!valid_email_address($recipient)) {
             $form_state->setErrorByName('recipients', $this->t('%recipient is an invalid email address.', array('%recipient' => $recipient)));
         }
     }
     $form_state['values']['recipients'] = $recipients;
 }
示例#8
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     if ($values['smtp_on'] == 1 && $values['smtp_host'] == '') {
         $form_state->setErrorByName('smtp_host', $this->t('You must enter an SMTP server address.'));
     }
     if ($values['smtp_on'] == 1 && $values['smtp_port'] == '') {
         $form_state->setErrorByName('smtp_port', $this->t('You must enter an SMTP port number.'));
     }
     if ($values['smtp_from'] && !valid_email_address($values['smtp_from'])) {
         $form_state->setErrorByName('smtp_from', $this->t('The provided from e-mail address is not valid.'));
     }
     if ($values['smtp_test_address'] && !valid_email_address($values['smtp_test_address'])) {
         $form_state->setErrorByName('smtp_test_address', $this->t('The provided test e-mail address is not valid.'));
     }
     // If username is set empty, we must set both username/password empty as well.
     if (empty($values['smtp_username'])) {
         $values['smtp_password'] = '';
     } elseif (empty($values['smtp_password'])) {
         $form_state->unsetValue('smtp_password');
     }
 }
 /**
  * Mailer.
  */
 public function mailer(Request $request)
 {
     $content = $request->getContent();
     if (empty($content)) {
         return new JsonResponse(['status' => 'error']);
     }
     $params = Json::decode($content);
     $email = $params['email'];
     $result = $params['selection'];
     $progress = $params['progress'];
     // Handle errors.
     if (!valid_email_address($email) || strlen($result) < 2) {
         return new JsonResponse(['status' => 'error']);
     }
     // Prepare email.
     $to = [$email];
     $view = views_embed_view('answer', 'rest_export_1', $result);
     $content = \Drupal::service('renderer')->render($view);
     $nodes = Json::decode($content);
     // Get the hidden fields
     $view = views_embed_view('hideanswers', 'rest_export_1', $result);
     $content = \Drupal::service('renderer')->render($view);
     $hidden = Json::decode($content);
     $hidden = array_map(function ($item) {
         return $item['nid'];
     }, $hidden);
     $view = views_embed_view('disclaimer', 'rest_export_1', $result);
     $content = \Drupal::service('renderer')->render($view);
     $disclaimer = Json::decode($content);
     $view = views_embed_view('intro_email', 'rest_export_1', $result);
     $content = \Drupal::service('renderer')->render($view);
     $intro = Json::decode($content);
     $result = \Drupal::service('plugin.manager.mail')->mail('angapp', 'results', implode(', ', $to), \Drupal::currentUser()->getPreferredLangcode(), ['progress' => $progress, 'intro' => $intro, 'disclaimer' => $disclaimer, 'nodes' => $nodes, 'hidden' => $hidden]);
     if ($result['result'] === TRUE) {
         return new JsonResponse(['status' => 'ok']);
     } else {
         return new JsonResponse(['status' => 'error']);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $removed = array();
     $invalid = array();
     $checked_lists = array_keys(array_filter($form_state->getValue('newsletters')));
     /** @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager */
     $subscription_manager = \Drupal::service('simplenews.subscription_manager');
     $emails = preg_split("/[\\s,]+/", $form_state->getValue('emails'));
     foreach ($emails as $email) {
         $email = trim($email);
         if (valid_email_address($email)) {
             foreach ($checked_lists as $newsletter_id) {
                 $subscription_manager->unsubscribe($email, $newsletter_id, FALSE, 'mass unsubscribe');
                 $removed[] = $email;
             }
         } else {
             $invalid[] = $email;
         }
     }
     if ($removed) {
         $removed = implode(", ", $removed);
         drupal_set_message(t('The following addresses were unsubscribed: %removed.', array('%removed' => $removed)));
         $newsletters = simplenews_newsletter_get_all();
         $list_names = array();
         foreach ($checked_lists as $newsletter_id) {
             $list_names[] = $newsletters[$newsletter_id]->label();
         }
         drupal_set_message(t('The addresses were unsubscribed from the following newsletters: %newsletters.', array('%newsletters' => implode(', ', $list_names))));
     } else {
         drupal_set_message(t('No addresses were removed.'));
     }
     if ($invalid) {
         $invalid = implode(", ", $invalid);
         drupal_set_message(t('The following addresses were invalid: %invalid.', array('%invalid' => $invalid)), 'error');
     }
     // Return to the parent page.
     $form_state->setRedirect('view.simplenews_subscribers.page_1');
 }
示例#11
0
	public function checkValue($value, $type) {
		$min_length = 0;
		$max_length = 0;
		$regexp = false;
		$optional = false;
		if (is_array($type)) {
			$min_length = isset($type['min_length']) ? (int) $type['min_length'] : 0;
			$max_length = isset($type['max_length']) ? (int) $type['max_length'] : 0;
			$regexp = isset($type['regexp']) ? $type['regexp'] : false;
			$optional = isset($type['*']) ? true : false;
			$type = $type['type'];
		}
		switch ($type) {
			case 'email':
				if (!valid_email_address($value))
					return false;
				break;
			case 'string':
				if (!$value && $optional)
					return '';
				if (!$value)
					return false;
				if ($min_length)
					if (mb_strlen(trim($value), 'UTF-8') < $min_length)
						return false;
				if ($max_length)
					if (mb_strlen(trim($value), 'UTF-8') > $max_length)
						return false;
				if ($regexp)
					if (!preg_match($regexp, $value))
						return false;
				break;
			case 'int':
				if ($value == null) {
					if ($optional)
						return false;
				}
				if (!is_numeric($value)) {
					$value = (int) $value;
				}
				break;
			case '':
				break;
		}
		return $value;
	}
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (!valid_email_address($form_state->getValue('email'))) {
         $form_state->setErrorByName('email', t('That e-mail address is not valid.'));
     }
 }
示例#13
0
/**
 * Primary function for validating email addresses.
 *
 * @param string $mail
 *   An email address to check, such as drupal@drupal.org.
 *
 * @return
 *   Empty if address is valid, a text error string if it's invalid.
 */
function _email_verify_check($mail)
{
    if (!valid_email_address($mail)) {
        // The address is syntactically incorrect.
        // The problem will be caught by the 'user' module anyway, so we avoid
        // duplicating the error reporting here, just return.
        return;
    }
    // Only add include if we are running Windows
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        include_once dirname(__FILE__) . '/windows_compat.inc';
    }
    $host = substr(strchr($mail, '@'), 1);
    // If the domain is not cached, perform tests
    if (!_email_verify_checkdb($host)) {
        // Let's see if we can find anything about this host in the DNS
        if (!checkdnsrr($host, 'ANY')) {
            return t('Email host %host invalid, please retry.', array('%host' => "{$host}"));
        }
        if ($whitelist = variable_get('email_verify_whitelist', FALSE)) {
            $whitelist = explode("\n", $whitelist);
            if (in_array($host, $whitelist)) {
                return;
            }
        }
        // What SMTP servers should we contact?
        $mx_hosts = array();
        if (!getmxrr($host, $mx_hosts)) {
            // When there is no MX record, the host itself should be used
            $mx_hosts[] = $host;
        }
        // Try to connect to one SMTP server
        foreach ($mx_hosts as $smtp) {
            $connect = @fsockopen($smtp, 25, $errno, $errstr, 15);
            if (!$connect) {
                continue;
            }
            if (ereg("^220", $out = fgets($connect, 1024))) {
                // OK, we have a SMTP connection
                break;
            } else {
                // The SMTP server probably does not like us
                // (dynamic/residential IP for aol.com for instance)
                // Be on the safe side and accept the address, at least it has a valid
                // domain part...
                watchdog('email_verify', "Could not verify email address at host {$host}: {$out} for {$mail}");
                return;
            }
        }
        if (!$connect) {
            return t('Email host %host is invalid, please contact us for clarification.', array('%host' => "{$host}"));
        }
        $from = variable_get('site_mail', ini_get('sendmail_from'));
        // Extract the <...> part if there is one
        if (preg_match('/\\<(.*)\\>/', $from, $match) > 0) {
            $from = $match[1];
        }
        $localhost = $_SERVER["HTTP_HOST"];
        if (!$localhost) {
            // Happens with HTTP/1.0
            // should be good enough for RFC compliant SMTP servers
            $localhost = 'localhost';
        }
        fputs($connect, "HELO {$localhost}\r\n");
        $out = fgets($connect, 1024);
        fputs($connect, "MAIL FROM: <{$from}>\r\n");
        $from = fgets($connect, 1024);
        fputs($connect, "RCPT TO: <{$mail}>\r\n");
        $to = fgets($connect, 1024);
        fputs($connect, "QUIT\r\n");
        fclose($connect);
        if (!ereg("^250", $from)) {
            // Again, something went wrong before we could really test the address,
            // be on the safe side and accept it.
            watchdog('email_verify', "Could not verify email address at host {$host}: {$from}");
            return;
        }
        if (ereg("(Client host|Helo command) rejected", $to) || ereg("^4", $to) && !ereg("^450", $to)) {
            // In those cases, accept the email, but log a warning
            watchdog('email_verify', "Could not verify email address at host {$host}: {$to}");
            return;
        }
        if (!ereg("^250", $to)) {
            watchdog('email_verify', "Rejected email address: {$mail}. Reason: {$to}");
            return t('%mail is invalid, please contact us for clarification.', array('%mail' => "{$mail}"));
        }
        // If the previous checks pass, save the valid domain to the DB table.
        _email_verify_updatedb($host);
    }
    // Everything OK
    return;
}
示例#14
0
function libya_quick_subscribe_form_validate($form, &$form_state)
{
    $mail = $form_state['values']['mail'];
    $obj = subscriptionData('read', $mail);
    if (gettype($obj) == 'object' && $obj->mail) {
        $resend = '';
        if ($obj->confirm == 0) {
            $resend = '<a class="my-btn" href="#" data-mail="' . $obj->mail . '" data-key="' . $obj->code . '" id="resend">resend confirmation mail</a>';
        }
        form_set_error('subscribe][mail', t('This email is already subscribed. ') . $resend);
    }
    if (!valid_email_address($mail)) {
        form_set_error('mail', t('Email address did not validate: please check'));
    }
}
示例#15
0
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    if ($values['smtp_on'] == 1 && $values['smtp_host'] == '') {
      $form_state->setErrorByName('smtp_host', $this->t('You must enter an SMTP server address.'));
    }

    if ($values['smtp_on'] == 1 && $values['smtp_port'] == '') {
      $form_state->setErrorByName('smtp_port', $this->t('You must enter an SMTP port number.'));
    }

    if ($values['smtp_from'] && !valid_email_address($values['smtp_from'])) {
      $form_state->setErrorByName('smtp_from', $this->t('The provided from e-mail address is not valid.'));
    }

    if ($values['smtp_test_address'] && !valid_email_address($values['smtp_test_address'])) {
      $form_state->setErrorByName('smtp_test_address', $this->t('The provided test e-mail address is not valid.'));
    }

    // If username is set empty, we must set both username/password empty as well.
    if (empty($values['smtp_username'])) {
      $values['smtp_password'] = '';
    }
    // A little hack. When form is presented, the password is not shown (Drupal way of doing).
    // So, if user submits the form without changing the password, we must prevent it from being reset.
    elseif (empty($values['smtp_password'])) {
      $form_state->unsetValue('smtp_password');
    }
  }
示例#16
0
 /**
  * Checks whether a header is a path header.
  *
  * It is difficult to distinguish id, mailbox and path headers from each other
  * as they all may very well contain the exact same value. This public static function simply
  * checks whether the header key equals to 'Message-ID' to determine if the
  * header is a path header.
  *
  * @see http://swift_mailer.org/docs/header-path
  *
  * @param string $key
  *   The header key.
  * @param string $value
  *   The header value.
  *
  * @return boolean
  *   TRUE if the provided header is a path header, and otherwise FALSE.
  */
 public static function swiftmailer_is_path_header($key, $value)
 {
     if (valid_email_address($value) && $key == 'Return-Path') {
         return TRUE;
     } else {
         return FALSE;
     }
 }
示例#17
0
 /** 
  *  Method to write or update an akteur to database
  *  @param $data : akteure-object
  *  @param $defaultAID : integer [optional, required for update-action]
  *  @return $akteurId : integer || $this->fehler : array
  *
  *  TODO: Remove $_POST's
  */
 public function setUpdateAkteur($data, $defaultAID = NULL)
 {
     $this->__setSingleAkteurVars($data);
     // Validate inputs, abort & return $this->fehler if necessary
     if (empty($this->name)) {
         $this->fehler['name'] = t('Bitte einen Organisationsnamen eingeben!');
     }
     if (empty($this->email) || !valid_email_address($this->email)) {
         $this->fehler['email'] = t('Bitte eine (gültige) Emailadresse eingeben!');
     }
     if (empty($this->adresse->bezirk)) {
         $this->fehler['ort'] = t('Bitte einen Bezirk auswählen!');
     }
     if (strlen($this->name) > 64) {
         $this->fehler['name'] = t('Bitte geben Sie einen kürzeren Namen an oder verwenden Sie ein Kürzel.');
     }
     if (strlen($this->email) > 100) {
         $this->fehler['email'] = t('Bitte geben Sie eine kürzere Emailadresse an.');
     }
     if (strlen($this->telefon) > 100) {
         $this->fehler['telefon'] = t('Bitte geben Sie eine kürzere Telefonnummer an.');
     }
     if (strlen($this->url) > 100) {
         $this->fehler['url'] = t('Bitte geben Sie eine kürzere URL an.');
     }
     if (!empty($this->url) && preg_match('/\\A(http:\\/\\/|https:\\/\\/)(\\w*[.|-]\\w*)*\\w+\\.[a-z]{2,3}(\\/.*)*\\z/', $this->url) == 0) {
         $this->fehler['url'] = t('Bitte eine gültige URL zur Akteurswebseite eingeben! (z.B. <i>http://meinakteur.de</i>)');
     }
     if (strlen($this->ansprechpartner) > 100) {
         $this->fehler['ansprechpartner'] = t('Bitte geben Sie einen kürzeren Ansprechpartner an.');
     }
     if (strlen($this->funktion) > 100) {
         $this->fehler['funktion'] = t('Bitte geben Sie eine kürzere Funktion an.');
     }
     if (strlen($this->beschreibung) > 65000) {
         $this->fehler['beschreibung'] = t('Bitte geben Sie eine kürzere Beschreibung an.');
     }
     if (strlen($this->oeffnungszeiten) > 200) {
         $this->fehler['oeffnungszeiten'] = t('Bitte geben Sie kürzere Öffnungszeiten an.');
     }
     if (strlen($this->adresse->strasse) > 100) {
         $this->fehler['strasse'] = t('Bitte geben Sie einen kürzeren Strassennamen an.');
     }
     if (strlen($this->adresse->nr) > 100) {
         $this->fehler['nr'] = t('Bitte geben Sie eine kürzere Hausnummer an.');
     }
     if (strlen($this->adresse->adresszusatz) > 100) {
         $this->fehler['adresszusatz'] = t('Bitte geben Sie einen kürzeren Adresszusatz an.');
     }
     if (strlen($this->adresse->plz) > 100) {
         $this->fehler['plz'] = t('Bitte geben Sie eine kürzere PLZ an.');
     }
     if (strlen($this->adresse->gps) > 100) {
         $this->fehler['gps'] = t('Bitte geben Sie kürzere GPS-Daten an.');
     }
     if (strlen($this->rssFeed) > 400 || preg_match('/\\A(http:\\/\\/|https:\\/\\/)(\\w*[.|-]\\w*)*\\w+\\.[a-z]{2,3}(\\/.*)*\\z/', $this->rssFeed) == 0) {
         # $this->fehler['rssFeed'] = t('Die URL zum RSS-Feed ist zu lang oder ungültig...');
     }
     if ($this->gps == 'Ermittle Geo-Koordinaten...') {
         $this->gps = '';
     }
     if (!empty($this->fehler)) {
         return $this->fehler;
     }
     // ----- INSERT- or UPDATE-Actions --------
     // Wenn Bilddatei ausgewählt wurde...
     if (isset($_FILES['bild']['name']) && !empty($_FILES['bild']['name'])) {
         $this->bild = $this->upload_image($_FILES['bild']);
     } else {
         if (isset($_POST['oldPic'])) {
             $this->bild = $this->clearContent($_POST['oldPic']);
         }
     }
     if ($defaultAID) {
         // = Prepare UPDATE-Action
         $akteurAdress = db_select($this->tbl_akteur, 'a')->fields('a', array('adresse'))->condition('AID', $defaultAID)->execute()->fetchObject();
         $this->adresse->ADID = $akteurAdress->adresse;
         // remove current picture manually
         if (!empty($this->removedPic)) {
             $b = end(explode('/', $this->removedPic));
             if (file_exists($this->short_bildpfad . $b)) {
                 unlink($this->short_bildpfad . $b);
             }
             if ($_POST['oldPic'] == $this->removedPic) {
                 $this->bild = '';
             }
         }
     }
     $this->adresse = $this->adressHelper->setUpdateAdresse($this->adresse);
     $this->akteur_id = $this->__db_action($this->tbl_akteur, array('name' => $this->name, 'adresse' => $this->adresse, 'email' => $this->email, 'telefon' => $this->telefon, 'url' => $this->url, 'ansprechpartner' => $this->ansprechpartner, 'funktion' => $this->funktion, 'bild' => $this->bild, 'beschreibung' => $this->beschreibung, 'oeffnungszeiten' => $this->oeffnungszeiten, 'barrierefrei' => !empty($this->barrierefrei) && ($this->barrierefrei || $this->barrierefrei == 'on') ? 1 : 0), $defaultAID ? array('AID', $defaultAID) : NULL, true);
     if (!$defaultAID) {
         $userHasAkteur = $this->__db_action($this->tbl_hat_user, array('hat_UID' => $this->user_id, 'hat_AID' => $this->akteur_id));
     }
     if (module_exists('aggregator')) {
         if (empty($defaultAID) && !empty($this->rssFeed)) {
             $feed = array('category' => 'aae-feeds', 'title' => 'aae-feed-' . $this->akteur_id, 'description' => t('Feed for AAE-User :username', array(':username' => $this->name)), 'url' => $this->rssFeed, 'refresh' => '86400', 'link' => base_path() . 'akteurprofil/' . $this->akteur_id, 'block' => 0);
             aggregator_save_feed($feed);
             aggregator_refresh($feed);
         } else {
             if (!empty($defaultAID)) {
                 $akteurFeed = db_select('aggregator_feed', 'af')->fields('af', array('fid', 'url'))->condition('title', 'aae-feed-' . $this->akteur_id)->execute();
                 $hasFeed = $akteurFeed->rowCount();
                 $akteurFeed = $akteurFeed->fetchObject();
                 if (!empty($this->rssFeed) && $hasFeed) {
                     // UPDATE-ACTION: Rewrite RSS-path of Feed
                     $feedUpdate = db_update('aggregator_feed')->fields(array('url' => $this->rssFeed))->condition('title', 'aae-feed-' . $this->akteur_id)->execute();
                     // Trunkate all current feed items
                     db_delete('aggregator_item')->condition('fid', $hasFeed);
                 } else {
                     if (!empty($this->rssFeed) && !$hasFeed) {
                         // INSERT-ACTION:
                         $feed = array('category' => 'aae-feeds', 'title' => 'aae-feed-' . $this->akteur_id, 'description' => t('Feed for AAE-User :username', array(':username' => $this->name)), 'url' => $this->rssFeed, 'refresh' => '86400', 'link' => base_path() . 'akteurprofil/' . $this->akteur_id, 'block' => 0);
                         aggregator_save_feed($feed);
                         aggregator_refresh($feed);
                     } else {
                         if (empty($this->rssFeed) && $hasFeed && $akteurFeed->url != $this->rssFeed) {
                             // REMOVE-ACTION
                             db_delete('aggregator_feed')->condition('fid', $akteurFeed->fid)->execute();
                             db_delete('aggregator_item')->condition('fid', $akteurFeed->fid)->execute();
                         }
                     }
                 }
             }
         }
         // END IF update_mode
     }
     // END IF module_exists('aggregator')
     // Update or insert Tags
     $this->tagsHelper->setRemoveTags($this->tags, array('akteur', $this->akteur_id), $this->removedTags);
     // TODO: Check for proper HOOK-call
     if (empty($defaultAID)) {
         // Tell Drupal about new akteurprofil/ID-item
         $parentItem = db_query("SELECT menu_links.mlid\n     FROM {menu_links} menu_links\n     WHERE menu_name = :menu_name AND link_path = :link_path", array(":menu_name" => "navigation", ":link_path" => 'akteure'));
         $plid = $parentItem->fetchObject();
         $item = array('menu_name' => 'navigation', 'weight' => 1, 'link_title' => t('Akteurprofil von !username', array('!username' => $this->name)), 'module' => 'aae_data', 'link_path' => 'akteurprofil/' . $this->akteur_id, 'plid' => $plid->mlid);
         module_invoke_all('hook_akteur_created');
     } else {
         module_invoke_all('hook_akteur_modified');
     }
     return $this->akteur_id;
 }
示例#18
0
/**
 * It checks if the given e-mails are valid, otherwise it shows an error.
 *
 * @todo
 *   Unused function?
 */
function guifi_tools_mail_update_form_validate($form, &$form_state)
{
    if (!valid_email_address($form_state['values']['mail_replacewith'])) {
        form_set_error('mail_replacewith', t('%email is not valid', array('%email' => $form_state['values']['mail_replacewith'])));
    }
    if ($form_state['values']['mail_search'] == $form_state['values']['mail_replacewith']) {
        form_set_error('mail_replacewith', t('%email is equal to current value', array('%email' => $form_state['values']['mail_replacewith'])));
    }
}
示例#19
0
/**
 *  validation wrapper that tests for existing FQDN
 */
function _connect_valid_email_strict($address)
{
    $FQDN = '/^(?:[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])+(?:\\.(?:[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])+)*(?:\\.[a-zA-Z]{2,})$/';
    list($mailbox, $domain) = split('@', $address);
    if (!preg_match($FQDN, $domain) || !checkdnsrr($domain . '.', 'MX')) {
        return FALSE;
    }
    return valid_email_address($address);
}
示例#20
0
/**
 * Checks the email address for validity.
 */
function _email_verify_check($mail)
{
    if (!valid_email_address($mail)) {
        // The address is syntactically incorrect.
        // The problem will be caught by the 'user' module anyway, so we avoid
        // duplicating the error reporting here, just return.
        return;
    }
    module_load_include('inc', 'email_verify', 'windows_compat');
    $host = drupal_substr(strchr($mail, '@'), 1);
    // Let's see if we can find anything about this host in the DNS.
    if (!checkdnsrr($host . '.', 'ANY')) {
        return t('%host is not a valid email host. Please check the spelling and try again.', array('%host' => "{$host}"));
    }
    // If install found port 25 closed or fsockopen() disabled, we can't test
    // mailboxes.
    if (variable_get('email_verify_skip_mailbox', FALSE)) {
        return;
    }
    // What SMTP servers should we contact?
    $mx_hosts = array();
    if (!getmxrr($host, $mx_hosts)) {
        // When there is no MX record, the host itself should be used.
        $mx_hosts[] = $host;
    }
    // Try to connect to one SMTP server.
    foreach ($mx_hosts as $smtp) {
        $connect = @fsockopen($smtp, 25, $errno, $errstr, 15);
        if (!$connect) {
            continue;
        }
        if (preg_match("/^220/", $out = fgets($connect, 1024))) {
            // An SMTP connection was made.
            break;
        } else {
            // The SMTP server probably does not like us (dynamic/residential IP for
            // aol.com for instance).
            // Be on the safe side and accept the address, at least it has a valid
            // domain part.
            watchdog('email_verify', 'Could not verify email address at host @host: @out', array('@host' => $host, '@out' => $out));
            return;
        }
    }
    if (!$connect) {
        return t('%host is not a valid email host. Please check the spelling and try again or contact us for clarification.', array('%host' => "{$host}"));
    }
    $from = variable_get('site_mail', ini_get('sendmail_from'));
    // Extract the <...> part, if there is one.
    if (preg_match('/\\<(.*)\\>/', $from, $match) > 0) {
        $from = $match[1];
    }
    // Should be good enough for RFC compliant SMTP servers.
    $localhost = $_SERVER["HTTP_HOST"];
    if (!$localhost) {
        $localhost = 'localhost';
    }
    fputs($connect, "HELO {$localhost}\r\n");
    $out = fgets($connect, 1024);
    fputs($connect, "MAIL FROM: <{$from}>\r\n");
    $from = fgets($connect, 1024);
    fputs($connect, "RCPT TO: <{$mail}>\r\n");
    $to = fgets($connect, 1024);
    fputs($connect, "QUIT\r\n");
    fclose($connect);
    if (!preg_match("/^250/", $from)) {
        // Again, something went wrong before we could really test the address.
        // Be on the safe side and accept it.
        watchdog('email_verify', 'Could not verify email address at host @host: @from', array('@host' => $host, '@from' => $from));
        return;
    }
    if (preg_match("/(Client host|Helo command) rejected/", $to) || preg_match("/^4/", $to) && !preg_match("/^450/", $to)) {
        // In those cases, accept the email, but log a warning.
        watchdog('email_verify', 'Could not verify email address at host @host: @to', array('@host' => $host, '@to' => $to));
        return;
    }
    if (!preg_match("/^250/", $to)) {
        watchdog('email_verify', 'Rejected email address: @mail. Reason: @to', array('@mail' => $mail, '@to' => $to));
        return t('%mail is not a valid email address. Please check the spelling and try again or contact us for clarification.', array('%mail' => "{$mail}"));
    }
    // Everything is OK, so don't return anything.
    return;
}
示例#21
0
 /**
  * {@inheritdoc}
  */
 public function validateConfigurationForm(array &$form, array &$form_state)
 {
     if (!valid_email_address($form_state['values']['recipient']) && strpos($form_state['values']['recipient'], ':mail') === FALSE) {
         // We want the literal %author placeholder to be emphasized in the error message.
         form_set_error('recipient', $form_state, t('Enter a valid email address or use a token email address such as %author.', array('%author' => '[node:author:mail]')));
     }
 }
示例#22
0
 /**
  * Check if username and email exists in the drupal db.
  *
  * @param array $params
  *   Array of name and mail values.
  * @param array $errors
  *   Array of errors.
  * @param string $emailName
  *   Field label for the 'email'.
  */
 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email')
 {
     $errors = form_get_errors();
     if ($errors) {
         // unset drupal messages to avoid twice display of errors
         unset($_SESSION['messages']);
     }
     if (!empty($params['name'])) {
         if ($nameError = user_validate_name($params['name'])) {
             $errors['cms_name'] = $nameError;
         } else {
             $uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $params['name']))->fetchField();
             if ((bool) $uid) {
                 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
             }
         }
     }
     if (!empty($params['mail'])) {
         if (!valid_email_address($params['mail'])) {
             $errors[$emailName] = ts('The e-mail address %1 is not valid.', array('%1' => $params['mail']));
         } else {
             $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(':mail' => $params['mail']))->fetchField();
             if ((bool) $uid) {
                 $resetUrl = url('user/password');
                 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>', array(1 => $params['mail'], 2 => $resetUrl));
             }
         }
     }
 }
/**
 * @file
 * Check the email for email_verify module.
 */
function _email_verify_check($mail)
{
    if (!valid_email_address($mail)) {
        // The address is syntactically incorrect.
        // The problem will be caught by the 'user' module anyway, so we avoid
        // duplicating the error reporting here, just return.
        return;
    }
    // checkdnsrr and getmxrr were added to Windows platform in PHP 5.3
    // http://www.php.net/checkdnsrr http://www.php.net/manual/en/function.getmxrr.php
    if (stristr(PHP_OS, 'WIN') && PHP_VERSION < 5.3) {
        drupal_set_message(t('Email Verify could not check the address because the server is running on Windows with a version of PHP below 5.3.'), 'warning');
        return;
    }
    $host = substr(strchr($mail, '@'), 1);
    // Let's see if we can find anything about this host in the DNS
    if (!checkdnsrr($host, 'ANY')) {
        return t('Email host %host invalid, please retry.', array('%host' => "{$host}"));
    }
    // What SMTP servers should we contact?
    $mx_hosts = array();
    if (!getmxrr($host, $mx_hosts)) {
        // When there is no MX record, the host itself should be used
        $mx_hosts[] = $host;
    }
    // Try to connect to one SMTP server
    foreach ($mx_hosts as $smtp) {
        $connect = @fsockopen($smtp, 25, $errno, $errstr, 15);
        if (!$connect) {
            continue;
        }
        if (ereg("^220", $out = fgets($connect, 1024))) {
            // OK, we have a SMTP connection
            break;
        } else {
            // The SMTP server probably does not like us
            // (dynamic/residential IP for aol.com for instance)
            // Be on the safe side and accept the address, at least it has a valid
            // domain part...
            watchdog('email_verify', "Could not verify email address at host {$host}: {$out}");
            return;
        }
    }
    if (!$connect) {
        return t('Email host %host is invalid, please contact us for clarification.', array('%host' => "{$host}"));
    }
    $from = variable_get('site_mail', ini_get('sendmail_from'));
    // Extract the <...> part if there is one
    if (preg_match('/\\<(.*)\\>/', $from, $match) > 0) {
        $from = $match[1];
    }
    $localhost = $_SERVER["HTTP_HOST"];
    if (!$localhost) {
        // Happens with HTTP/1.0
        //should be good enough for RFC compliant SMTP servers
        $localhost = 'localhost';
    }
    fputs($connect, "HELO {$localhost}\r\n");
    $out = fgets($connect, 1024);
    fputs($connect, "MAIL FROM: <{$from}>\r\n");
    $from = fgets($connect, 1024);
    fputs($connect, "RCPT TO: <{$mail}>\r\n");
    $to = fgets($connect, 1024);
    fputs($connect, "QUIT\r\n");
    fclose($connect);
    if (!ereg("^250", $from)) {
        // Again, something went wrong before we could really test the address,
        // be on the safe side and accept it.
        watchdog('email_verify', "Could not verify email address at host {$host}: {$from}");
        return;
    }
    if (ereg("(Client host|Helo command) rejected", $to) || ereg("^4", $to) && !ereg("^450", $to)) {
        // In those cases, accept the email, but log a warning
        watchdog('email_verify', "Could not verify email address at host {$host}: {$to}");
        return;
    }
    if (!ereg("^250", $to)) {
        watchdog('email_verify', "Rejected email address: {$mail}. Reason: {$to}");
        return t('%mail is invalid, please contact us for clarification.', array('%mail' => "{$mail}"));
    }
    // Everything OK
    return;
}
示例#24
0
/**
 * AJAX CALLBACK: SIMPLENEWS SUBSCRIPTION FORM (FOOTER NEWSLETTER BLOCK: 2)
 */
function simplenews_block_form_ajax_submit_2($form, $form_state)
{
    $launch_list_subscription_id = theme_get_setting('launch_list_subscription_id');
    $return = '<div id="block-simplenews-' . $launch_list_subscription_id . '" class="block block-simplenews home-signin input-group wow fadeIn animated home-signin-return">';
    //$return .= '<h2>' . t('Newsletter') . '</h2>';
    if (!valid_email_address($form_state['values']['mail'])) {
        $return .= '<div class="form-validation alert alert-danger">' . t('The e-mail address is not valid.') . '</div>';
        return $return . render($form);
    } else {
        if (module_exists('simplenews')) {
            module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
            $tid = $form['#tid'];
            $account = simplenews_load_user_by_mail($form_state['values']['mail']);
            $confirm = simplenews_require_double_opt_in($tid, $account);
            switch ($form_state['values']['action']) {
                case 'subscribe':
                    simplenews_subscribe_user($form_state['values']['mail'], $tid, $confirm, 'website');
                    if ($confirm) {
                        $return .= '<div class="form-validation alert alert-success">' . t('Success! Please check your e-mail to complete your subscription.') . '</div>';
                        return $return . render($form);
                    } else {
                        $return .= '<div class="form-validation alert alert-success">' . t('Success! You\'ve been subscribed to our newsletter.') . '</div>';
                        return $return . '<input disabled class="subscribe-form-submit btn-primary-full btn submit ajax-processed" data-loading-text="Loading..." type="submit" id="edit-submit" name="op" value="Subscribed">';
                    }
                    break;
                case 'unsubscribe':
                    simplenews_unsubscribe_user($form_state['values']['mail'], $tid, $confirm, 'website');
                    if ($confirm) {
                        $return .= '<div class="form-validation alert alert-success">' . t('You\'re nearly there. Please check your e-mail to confirm.') . '</div>';
                        return $return . render($form);
                    } else {
                        $return .= '<div class="form-validation alert alert-success">' . t('OK, you\'re unsubscribed. Sorry to see you go.') . '</div>';
                        return $return . '<input disabled class="subscribe-form-submit btn-primary-full btn submit ajax-processed" data-loading-text="Loading..." type="submit" id="edit-submit" name="op" value="Unsubscribed">';
                    }
                    break;
            }
        }
    }
    $return .= render($form);
    $return .= '</div>';
}
示例#25
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);
}
 /**
  * Send the e-mail message.
  *
  * @see drupal_mail()
  *
  * @param $message
  *   A message array, as described in hook_mail_alter().
  * @return
  *   TRUE if the mail was successfully accepted, otherwise FALSE.
  */
 public function mail(array $message)
 {
     $id = $message['id'];
     $to = $message['to'];
     $from = $message['from'];
     $body = $message['body'];
     $headers = $message['headers'];
     $subject = $message['subject'];
     // Create a new PHPMailer object - autoloaded from registry.
     $mailer = new PHPMailer();
     // Turn on debugging, if requested.
     if ($this->smtpConfig->get('smtp_debugging') == 1) {
         $mailer->SMTPDebug = TRUE;
     }
     // Set the from name.
     $from_name = $this->smtpConfig->get('smtp_fromname');
     if (empty($from_name)) {
         // If value is not defined in settings, use site_name.
         $from_name = \Drupal::config('system.site')->get('name');
     }
     //Hack to fix reply-to issue.
     $properfrom = $this->smtpConfig->get('site_mail');
     if (!empty($properfrom)) {
         $headers['From'] = $properfrom;
     }
     if (!isset($headers['Reply-To']) || empty($headers['Reply-To'])) {
         if (strpos($from, '<')) {
             $reply = preg_replace('/>.*/', '', preg_replace('/.*</', '', $from));
         } else {
             $reply = $from;
         }
         $headers['Reply-To'] = $reply;
     }
     // Blank value will let the e-mail address appear.
     if ($from == NULL || $from == '') {
         // If from e-mail address is blank, use smtp_from config option.
         if (($from = $this->smtpConfig->get('smtp_from')) == '') {
             // If smtp_from config option is blank, use site_email.
             if (($from = $this->smtpConfig->get('site_mail')) == '') {
                 drupal_set_message(t('There is no submitted from address.'), 'error');
                 watchdog('smtp', 'There is no submitted from address.', array(), WATCHDOG_ERROR);
                 return FALSE;
             }
         }
     }
     $from_comp = $this->_get_components($from);
     if (!valid_email_address($from_comp['email'])) {
         drupal_set_message(t('The submitted from address (@from) is not valid.', array('@from' => $from)), 'error');
         watchdog('smtp', 'The submitted from address (@from) is not valid.', array('@from' => $from), WATCHDOG_ERROR);
         return FALSE;
     }
     // Defines the From value to what we expect.
     $mailer->From = $from;
     $mailer->FromName = $from_comp['name'];
     $mailer->Sender = $from_comp['email'];
     // Create the list of 'To:' recipients.
     $torecipients = explode(',', $to);
     foreach ($torecipients as $torecipient) {
         $to_comp = $this->_get_components($torecipient);
         $mailer->AddAddress($to_comp['email'], $to_comp['name']);
     }
     // Parse the headers of the message and set the PHPMailer object's settings
     // accordingly.
     foreach ($headers as $key => $value) {
         //watchdog('error', 'Key: ' . $key . ' Value: ' . $value);
         switch (strtolower($key)) {
             case 'from':
                 if ($from == NULL or $from == '') {
                     // If a from value was already given, then set based on header.
                     // Should be the most common situation since drupal_mail moves the
                     // from to headers.
                     $from = $value;
                     $mailer->From = $value;
                     // then from can be out of sync with from_name !
                     $mailer->FromName = '';
                     $mailer->Sender = $value;
                 }
                 break;
             case 'content-type':
                 // Parse several values on the Content-type header, storing them in an array like
                 // key=value -> $vars['key']='value'
                 $vars = explode(';', $value);
                 foreach ($vars as $i => $var) {
                     if ($cut = strpos($var, '=')) {
                         $new_var = trim(strtolower(substr($var, $cut + 1)));
                         $new_key = trim(substr($var, 0, $cut));
                         unset($vars[$i]);
                         $vars[$new_key] = $new_var;
                     }
                 }
                 // Set the charset based on the provided value, otherwise set it to UTF-8 (which is Drupals internal default).
                 $mailer->CharSet = isset($vars['charset']) ? $vars['charset'] : 'UTF-8';
                 // If $vars is empty then set an empty value at index 0 to avoid a PHP warning in the next statement
                 $vars[0] = isset($vars[0]) ? $vars[0] : '';
                 switch ($vars[0]) {
                     case 'text/plain':
                         // The message includes only a plain text part.
                         $mailer->IsHTML(FALSE);
                         $content_type = 'text/plain';
                         break;
                     case 'text/html':
                         // The message includes only an HTML part.
                         $mailer->IsHTML(TRUE);
                         $content_type = 'text/html';
                         break;
                     case 'multipart/related':
                         // Get the boundary ID from the Content-Type header.
                         $boundary = $this->_get_substring($value, 'boundary', '"', '"');
                         // The message includes an HTML part w/inline attachments.
                         $mailer->ContentType = $content_type = 'multipart/related; boundary="' . $boundary . '"';
                         break;
                     case 'multipart/alternative':
                         // The message includes both a plain text and an HTML part.
                         $mailer->ContentType = $content_type = 'multipart/alternative';
                         // Get the boundary ID from the Content-Type header.
                         $boundary = $this->_get_substring($value, 'boundary', '"', '"');
                         break;
                     case 'multipart/mixed':
                         // The message includes one or more attachments.
                         $mailer->ContentType = $content_type = 'multipart/mixed';
                         // Get the boundary ID from the Content-Type header.
                         $boundary = $this->_get_substring($value, 'boundary', '"', '"');
                         break;
                     default:
                         // Everything else is unsuppored by PHPMailer.
                         drupal_set_message(t('The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.', array('%header' => "Content-Type: {$value}")), 'error');
                         watchdog('smtp', 'The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.', array('%header' => "Content-Type: {$value}"), WATCHDOG_ERROR);
                         // Force the Content-Type to be text/plain.
                         $mailer->IsHTML(FALSE);
                         $content_type = 'text/plain';
                 }
                 break;
             case 'reply-to':
                 // Only add a "reply-to" if it's not the same as "return-path".
                 if ($value != $headers['Return-Path']) {
                     $reply_to_comp = $this->_get_components($value);
                     $mailer->AddReplyTo($reply_to_comp['email'], $reply_to_comp['name']);
                 }
                 break;
             case 'content-transfer-encoding':
                 $mailer->Encoding = $value;
                 break;
             case 'return-path':
                 $mailer->Sender = $value;
                 break;
             case 'mime-version':
             case 'x-mailer':
                 // Let PHPMailer specify these.
                 break;
             case 'errors-to':
                 $mailer->AddCustomHeader('Errors-To: ' . $value);
                 break;
             case 'cc':
                 $ccrecipients = explode(',', $value);
                 foreach ($ccrecipients as $ccrecipient) {
                     $cc_comp = $this->_get_components($ccrecipient);
                     $mailer->AddCC($cc_comp['email'], $cc_comp['name']);
                 }
                 break;
             case 'bcc':
                 $bccrecipients = explode(',', $value);
                 foreach ($bccrecipients as $bccrecipient) {
                     $bcc_comp = $this->_get_components($bccrecipient);
                     $mailer->AddBCC($bcc_comp['email'], $bcc_comp['name']);
                 }
                 break;
             default:
                 // The header key is not special - add it as is.
                 $mailer->AddCustomHeader($key . ': ' . $value);
         }
     }
     /**
      * TODO
      * Need to figure out the following.
      *
      * Add one last header item, but not if it has already been added.
      * $errors_to = FALSE;
      * foreach ($mailer->CustomHeader as $custom_header) {
      *   if ($custom_header[0] = '') {
      *     $errors_to = TRUE;
      *   }
      * }
      * if ($errors_to) {
      *   $mailer->AddCustomHeader('Errors-To: '. $from);
      * }
      */
     // Add the message's subject.
     $mailer->Subject = $subject;
     // Processes the message's body.
     switch ($content_type) {
         case 'multipart/related':
             $mailer->Body = $body;
             // TODO: Figure out if there is anything more to handling this type.
             break;
         case 'multipart/alternative':
             // Split the body based on the boundary ID.
             $body_parts = $this->_boundary_split($body, $boundary);
             foreach ($body_parts as $body_part) {
                 // If plain/text within the body part, add it to $mailer->AltBody.
                 if (strpos($body_part, 'text/plain')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Include it as part of the mail object.
                     $mailer->AltBody = $body_part;
                 } elseif (strpos($body_part, 'text/html')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Include it as part of the mail object.
                     $mailer->Body = $body_part;
                 }
             }
             break;
         case 'multipart/mixed':
             // Split the body based on the boundary ID.
             $body_parts = $this->_boundary_split($body, $boundary);
             // Determine if there is an HTML part for when adding the plain text part.
             $text_plain = FALSE;
             $text_html = FALSE;
             foreach ($body_parts as $body_part) {
                 if (strpos($body_part, 'text/plain')) {
                     $text_plain = TRUE;
                 }
                 if (strpos($body_part, 'text/html')) {
                     $text_html = TRUE;
                 }
             }
             foreach ($body_parts as $body_part) {
                 // If test/plain within the body part, add it to either
                 // $mailer->AltBody or $mailer->Body, depending on whether there is
                 // also a text/html part ot not.
                 if (strpos($body_part, 'multipart/alternative')) {
                     // Get boundary ID from the Content-Type header.
                     $boundary2 = $this->_get_substring($body_part, 'boundary', '"', '"');
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Split the body based on the boundary ID.
                     $body_parts2 = $this->_boundary_split($body_part, $boundary2);
                     foreach ($body_parts2 as $body_part2) {
                         // If plain/text within the body part, add it to $mailer->AltBody.
                         if (strpos($body_part2, 'text/plain')) {
                             // Clean up the text.
                             $body_part2 = trim($this->_remove_headers(trim($body_part2)));
                             // Include it as part of the mail object.
                             $mailer->AltBody = $body_part2;
                             $mailer->ContentType = 'multipart/mixed';
                         } elseif (strpos($body_part2, 'text/html')) {
                             // Get the encoding.
                             $body_part2_encoding = $this->_get_substring($body_part2, 'Content-Transfer-Encoding', ' ', "\n");
                             // Clean up the text.
                             $body_part2 = trim($this->_remove_headers(trim($body_part2)));
                             // Check whether the encoding is base64, and if so, decode it.
                             if (Unicode::strtolower($body_part2_encoding) == 'base64') {
                                 // Include it as part of the mail object.
                                 $mailer->Body = base64_decode($body_part2);
                                 // Ensure the whole message is recoded in the base64 format.
                                 $mailer->Encoding = 'base64';
                             } else {
                                 // Include it as part of the mail object.
                                 $mailer->Body = $body_part2;
                             }
                             $mailer->ContentType = 'multipart/mixed';
                         }
                     }
                 } elseif (strpos($body_part, 'text/plain')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     if ($text_html) {
                         $mailer->AltBody = $body_part;
                         $mailer->IsHTML(TRUE);
                         $mailer->ContentType = 'multipart/mixed';
                     } else {
                         $mailer->Body = $body_part;
                         $mailer->IsHTML(FALSE);
                         $mailer->ContentType = 'multipart/mixed';
                     }
                 } elseif (strpos($body_part, 'text/html')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Include it as part of the mail object.
                     $mailer->Body = $body_part;
                     $mailer->IsHTML(TRUE);
                     $mailer->ContentType = 'multipart/mixed';
                 } elseif (strpos($body_part, 'Content-Disposition: attachment;') && !isset($message['params']['attachments'])) {
                     $file_path = $this->_get_substring($body_part, 'filename=', '"', '"');
                     $file_name = $this->_get_substring($body_part, ' name=', '"', '"');
                     $file_encoding = $this->_get_substring($body_part, 'Content-Transfer-Encoding', ' ', "\n");
                     $file_type = $this->_get_substring($body_part, 'Content-Type', ' ', ';');
                     if (file_exists($file_path)) {
                         if (!$mailer->AddAttachment($file_path, $file_name, $file_encoding, $file_type)) {
                             drupal_set_message(t('Attahment could not be found or accessed.'));
                         }
                     } else {
                         // Clean up the text.
                         $body_part = trim($this->_remove_headers(trim($body_part)));
                         if (Unicode::strtolower($file_encoding) == 'base64') {
                             $attachment = base64_decode($body_part);
                         } elseif (Unicode::strtolower($file_encoding) == 'quoted-printable') {
                             $attachment = quoted_printable_decode($body_part);
                         } else {
                             $attachment = $body_part;
                         }
                         $attachment_new_filename = drupal_tempnam('temporary://', 'smtp');
                         $file_path = file_save_data($attachment, $attachment_new_filename, FILE_EXISTS_REPLACE);
                         $real_path = drupal_realpath($file_path->uri);
                         if (!$mailer->AddAttachment($real_path, $file_name)) {
                             drupal_set_message(t('Attachment could not be found or accessed.'));
                         }
                     }
                 }
             }
             break;
         default:
             $mailer->Body = $body;
             break;
     }
     // Process mimemail attachments, which are prepared in mimemail_mail().
     if (isset($message['params']['attachments'])) {
         foreach ($message['params']['attachments'] as $attachment) {
             if (isset($attachment['filecontent'])) {
                 $mailer->AddStringAttachment($attachment['filecontent'], $attachment['filename'], 'base64', $attachment['filemime']);
             }
             if (isset($attachment['filepath'])) {
                 $filename = isset($attachment['filename']) ? $attachment['filename'] : basename($attachment['filepath']);
                 $filemime = isset($attachment['filemime']) ? $attachment['filemime'] : file_get_mimetype($attachment['filepath']);
                 $mailer->AddAttachment($attachment['filepath'], $filename, 'base64', $filemime);
             }
         }
     }
     // Set the authentication settings.
     $username = $this->smtpConfig->get('smtp_username');
     $password = $this->smtpConfig->get('smtp_password');
     // If username and password are given, use SMTP authentication.
     if ($username != '' && $password != '') {
         $mailer->SMTPAuth = TRUE;
         $mailer->Username = $username;
         $mailer->Password = $password;
     }
     // Set the protocol prefix for the smtp host.
     switch ($this->smtpConfig->get('smtp_protocol')) {
         case 'ssl':
             $mailer->SMTPSecure = 'ssl';
             break;
         case 'tls':
             $mailer->SMTPSecure = 'tls';
             break;
         default:
             $mailer->SMTPSecure = '';
     }
     // Set other connection settings.
     $mailer->Host = $this->smtpConfig->get('smtp_host') . ';' . $this->smtpConfig->get('smtp_hostbackup');
     $mailer->Port = $this->smtpConfig->get('smtp_port');
     $mailer->Mailer = 'smtp';
     $mailerArr = array('mailer' => $mailer, 'to' => $to, 'from' => $from);
     if ($this->smtpConfig->get('smtp_queue')) {
         watchdog('smtp', 'Queue sending mail to: @to', array('@to' => $to));
         smtp_send_queue($mailerArr);
     } else {
         return _smtp_mailer_send($mailerArr);
     }
     return TRUE;
 }
示例#27
0
 function register()
 {
     $error = array();
     if (!valid_email_address($_POST['email'])) {
         $error['email'] = 'неправильный E-mail';
     }
     if (!trim($_POST['password'])) {
         $error['password'] = '******';
     }
     if (!isset($_POST['agree'])) {
         $error['agree'] = 'Примите условия пользовательского соглашения';
     }
     if (count($error)) {
         Site::passWrite('error_register', $error);
         return;
     } else {
         try {
             $fields = array();
             $data['email'] = strtolower(trim($_POST['email']));
             $data['nickname'] = $this->getUniqueNickname(strtolower(trim($_POST['nickname'])), $_POST['email']);
             $data['password'] = md5(trim($_POST['password']));
             $data['registerTime'] = $data['lastAccessTime'] = time();
             $data['role'] = User::ROLE_UNVERIFIED;
             $data['hash'] = md5(time() . '-' . rand(1, 10));
             foreach ($data as $f => $v) {
                 $fields[] = '`' . $f . '`=' . Database::escape($v);
             }
             Database::query('INSERT INTO `user` SET ' . implode(',', $fields));
             $uid = Database::lastInsertId();
             try {
                 Site::passWrite('success', true);
             } catch (Exception $e) {
                 $error['email'] = $e->getMessage();
                 Site::passWrite('error_register', $error);
                 return;
             }
             $this->sendRegisterEmail($data['email'], '', $uid . '-' . $data['hash']);
             Badges::progressAction($uid, Badges::ACTION_TYPE_REGISTER);
         } catch (Exception $e) {
             $error['email'] = 'E-mail уже используется, укажите другой';
             Site::passWrite('error_register', $error);
             return;
         }
         CurrentUser::set_cookie($uid);
     }
 }
示例#28
0
/** guifi_notification_validate(): validates that the given emails are correct
  * arguments:
  * @to: string with a list of emails sepparated by comma
  * @returns: foretted str if all valid, FALSE otherwise
**/
function guifi_notification_validate($to)
{
    $to = strtolower(trim(trim(str_replace(';', ',', $to)), ','));
    $emails = explode(',', $to);
    $trimmed = array();
    foreach ($emails as $email) {
        $temail = trim($email);
        if (!valid_email_address($temail)) {
            drupal_set_message(t('%email is not valid', array('%email' => $temail)), 'error');
            return FALSE;
        }
        $trimmed[] = $temail;
    }
    return implode(', ', $trimmed);
}
 /**
  * Validates the test address.
  */
 public function validateTestAddress(array $form, FormStateInterface $form_state)
 {
     $test_address = $form_state->getValue('test_address');
     $test_address = trim($test_address);
     if (!empty($test_address)) {
         $mails = explode(',', $test_address);
         foreach ($mails as $mail) {
             $mail = trim($mail);
             if (!valid_email_address($mail)) {
                 $form_state->setErrorByName('test_address', t('Invalid email address "%mail".', array('%mail' => $mail)));
             }
         }
         $form_state->set('test_addresses', $mails);
     } else {
         $form_state->setErrorByName('test_address', t('Missing test email address.'));
     }
 }
示例#30
0
文件: sopac_user.php 项目: aadl/sopac
function sopac_notifications_form_validate($form, &$form_state)
{
    if (!valid_email_address($form_state['values']['email'])) {
        form_set_error('email', 'Please enter a valid email address');
    }
}