Przeglądaj źródła

#703 Send emails from "contact us" form from sender's email address

Alex Trofimov 9 lat temu
rodzic
commit
6c8f52d43a

+ 16 - 5
inc/utils.inc.php

@@ -316,9 +316,10 @@ function sendMailTemplateSystem($sTemplateName, $aReplaceVars = array(), $iEmail
  * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  * @param $sEmailFlag - use 'html' for HTML email message
  * @param $isDisableAlert - disable alert
+ * @param $aCustomHeaders - custom email headers
  * @return true if message was send or false otherwise
  */
-function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false)
+function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false, $aCustomHeaders = array())
 {
     // make sure that recipient's email is valid and message isn't empty
     if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
@@ -365,10 +366,19 @@ function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0
     }
 
     // email message headers
-    $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
-    $sMailParameters = "-f{$sEmailNotify}";
-    $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
-    $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
+    $sMailHeader = '';
+    foreach ($aCustomHeaders as $sHeaderName => $sHeaderValue)
+        $sMailHeader = "$sHeaderName: $sHeaderValue\r\n" . $sMailHeader;
+
+    if (!isset($aCustomHeaders['From']))
+        $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
+
+    if (!isset($aCustomHeaders['MIME-Version']))
+        $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
+
+    $sMailParameters = isset($aCustomHeaders['Sender']) ? "-f{$aCustomHeaders['Sender']}" : "-f{$sEmailNotify}";
+
+    $sMailSubject = !isset($aCustomHeaders['Subject']) ? '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=' : $aCustomHeaders['Subject'];
 
     // build data for alert handler
     $bResult = null;
@@ -380,6 +390,7 @@ function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0
         'params' => $sMailParameters,
         'recipient' => $aRecipientInfo,
         'html' => 'html' == $sEmailFlag ? true : false,
+        'custom_headers' => $aCustomHeaders,
         'override_result' => &$bResult,
     );
 

+ 6 - 1
modules/boonex/contact/classes/BxContactModule.php

@@ -71,7 +71,12 @@ class BxContactModule extends BxDolModule
 
                 $sResult = '';
                 $sRecipientEmail = $this->_oConfig->getEmail();
-                if(sendMail($sRecipientEmail, $aMessage['Subject'], $aMessage['Body'], 0, array(), BX_EMAIL_SYSTEM)) {
+                $aCustomHeaders = array(
+                    'From' => $oForm->getCleanValue('name') . ' <' . bx_process_output($oForm->getCleanValue('email')) . '>',
+                    'Sender' => trim(getParam('bx_smtp_from_email')) ? trim(getParam('bx_smtp_from_email')) : getParam('site_email_notify'),
+                );
+                
+                if(sendMail($sRecipientEmail, $aMessage['Subject'], $aMessage['Body'], 0, array(), BX_EMAIL_SYSTEM, 'html', false, $aCustomHeaders)) {
                     $this->onContact();
 
                     foreach($oForm->aInputs as $iKey => $aInput) 

+ 1 - 1
modules/boonex/smtpmailer/classes/BxSMTPAlertsResponse.php

@@ -20,7 +20,7 @@ class BxSMTPAlertsResponse extends BxDolAlertsResponse
             return;
 
         $a = $oAlert->aExtras;
-        $a['override_result'] = BxDolService::call('bx_smtp', 'send', array($a['email'], $a['subject'], $a['body'], $a['header'], $a['params'], $a['html'], $a['recipient']));
+        $a['override_result'] = BxDolService::call('bx_smtp', 'send', array($a['email'], $a['subject'], $a['body'], $a['header'], $a['params'], $a['html'], $a['recipient'], $a['custom_headers'] ));
     }
 }
 

+ 28 - 10
modules/boonex/smtpmailer/classes/BxSMTPModule.php

@@ -19,7 +19,7 @@ class BxSMTPModule extends BxDolModule
         parent::__construct($aModule);
     }
 
-    function serviceSend ($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters, $isHtml, $aRecipientInfo = array())
+    function serviceSend ($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters, $isHtml, $aRecipientInfo = array(), $aCustomHeaders = array())
     {
         $iRet = true;
 
@@ -29,7 +29,7 @@ class BxSMTPModule extends BxDolModule
 
             if ('on' == getParam('bx_smtp_on'))
                 $mail->IsSMTP();
-            //$mail->SMTPDebug = 2;
+            // $mail->SMTPDebug = 2;
 
             $mail->CharSet = 'utf8';
 
@@ -67,16 +67,20 @@ class BxSMTPModule extends BxDolModule
             $mail->Username = getParam ('bx_smtp_username');
             $mail->Password = getParam ('bx_smtp_password');
 
-            $sParamSender = trim(getParam('bx_smtp_from_email'));
-            if ($sParamSender)
-                $mail->From = $sParamSender;
-            else
-                $mail->From = getParam('site_email_notify');
+            if (!isset($aCustomHeaders['From'])) {
+                $sParamSender = trim(getParam('bx_smtp_from_email'));
+                if ($sParamSender)
+                    $mail->From = $sParamSender;
+                else
+                    $mail->From = getParam('site_email_notify');
+
+                // get site name or some other name as sender's name
+                $mail->FromName = getParam ('bx_smtp_from_name');
+            } 
 
-            // get site name or some other name as sender's name
-            $mail->FromName = getParam ('bx_smtp_from_name');
+            if (!isset($aCustomHeaders['Subject']))
+                $mail->Subject = $sMailSubject;
 
-            $mail->Subject = $sMailSubject;
             if ($isHtml) {
                 $mail->Body = $sMailBody;
                 $mail->AltBody = $isHtml ? strip_tags($sMailBody) : $sMailBody;
@@ -90,6 +94,20 @@ class BxSMTPModule extends BxDolModule
 
             $mail->IsHTML($isHtml ? true : false);
 
+            foreach ($aCustomHeaders as $sHeaderName => $sHeaderValue) {
+                if ('From' == $sHeaderName) {
+                    if (preg_match('/(.+)<(.+)>/', $sHeaderValue, $m)) {
+                        $mail->setFrom($m[2], trim($m[1]), false);
+                    }
+                    else {
+                        $mail->setFrom($sHeaderValue, '', false);
+                    }
+                } 
+                else {
+                    $mail->addCustomHeader($sHeaderName, $sHeaderValue);
+                }
+            }
+
             try {
                 $mail->Send();
             } catch (phpmailerException $e) {

+ 1 - 1
plugins/phpmailer/LICENSE

@@ -31,7 +31,7 @@ class PHPMailer
      * The PHPMailer Version number.
      * @var string
      */
-    public $Version = '5.2.22';
+    public $Version = '5.2.23';
 
     /**
      * Email priority.

+ 54 - 52
plugins/phpmailer/class.smtp.php

@@ -30,7 +30,7 @@ class SMTP
      * The PHPMailer SMTP version number.
      * @var string
      */
-    const VERSION = '5.2.22';
+    const VERSION = '5.2.23';
 
     /**
      * SMTP line break constant.
@@ -81,7 +81,7 @@ class SMTP
      * @deprecated Use the `VERSION` constant instead
      * @see SMTP::VERSION
      */
-    public $Version = '5.2.22';
+    public $Version = '5.2.23';
 
     /**
      * SMTP server port number.
@@ -150,16 +150,16 @@ class SMTP
      */
     public $Timelimit = 300;
 
-	/**
-	 * @var array patterns to extract smtp transaction id from smtp reply
-	 * Only first capture group will be use, use non-capturing group to deal with it
-	 * Extend this class to override this property to fulfil your needs.
-	 */
-	protected $smtp_transaction_id_patterns = array(
-		'exim' => '/[0-9]{3} OK id=(.*)/',
-		'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
-		'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
-	);
+    /**
+     * @var array patterns to extract smtp transaction id from smtp reply
+     * Only first capture group will be use, use non-capturing group to deal with it
+     * Extend this class to override this property to fulfil your needs.
+     */
+    protected $smtp_transaction_id_patterns = array(
+        'exim' => '/[0-9]{3} OK id=(.*)/',
+        'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
+        'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
+    );
 
     /**
      * The socket for the server connection.
@@ -231,8 +231,7 @@ class SMTP
                     preg_replace('/[\r\n]+/', '', $str),
                     ENT_QUOTES,
                     'UTF-8'
-                )
-                . "<br>\n";
+                ) . "<br>\n";
                 break;
             case 'echo':
             default:
@@ -242,7 +241,7 @@ class SMTP
                     "\n",
                     "\n                   \t                  ",
                     trim($str)
-                )."\n";
+                ) . "\n";
         }
     }
 
@@ -276,7 +275,8 @@ class SMTP
         }
         // Connect to the SMTP server
         $this->edebug(
-            "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true),
+            "Connection: opening to $host:$port, timeout=$timeout, options=" .
+            var_export($options, true),
             self::DEBUG_CONNECTION
         );
         $errno = 0;
@@ -362,14 +362,14 @@ class SMTP
         }
 
         // Begin encrypted connection
-        if (!stream_socket_enable_crypto(
+        set_error_handler(array($this, 'errorHandler'));
+        $crypto_ok = stream_socket_enable_crypto(
             $this->smtp_conn,
             true,
             $crypto_method
-        )) {
-            return false;
-        }
-        return true;
+        );
+        restore_error_handler();
+        return $crypto_ok;
     }
 
     /**
@@ -398,8 +398,7 @@ class SMTP
         }
 
         if (array_key_exists('EHLO', $this->server_caps)) {
-        // SMTP extensions are available. Let's try to find a proper authentication method
-
+            // SMTP extensions are available; try to find a proper authentication method
             if (!array_key_exists('AUTH', $this->server_caps)) {
                 $this->setError('Authentication is not allowed at this stage');
                 // 'at this stage' means that auth may be allowed after the stage changes
@@ -424,7 +423,7 @@ class SMTP
                     $this->setError('No supported authentication methods found');
                     return false;
                 }
-                self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
+                self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
             }
 
             if (!in_array($authtype, $this->server_caps['AUTH'])) {
@@ -550,7 +549,7 @@ class SMTP
      * Works like hash_hmac('md5', $data, $key)
      * in case that function is not available
      * @param string $data The data to hash
-     * @param string $key  The key to hash with
+     * @param string $key The key to hash with
      * @access protected
      * @return string
      */
@@ -893,7 +892,8 @@ class SMTP
             $code_ex = (count($matches) > 2 ? $matches[2] : null);
             // Cut off error code from each response line
             $detail = preg_replace(
-                "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
+                "/{$code}[ -]" .
+                ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
                 '',
                 $this->last_reply
             );
@@ -1105,7 +1105,7 @@ class SMTP
             // Now check if reads took too long
             if ($endtime and time() > $endtime) {
                 $this->edebug(
-                    'SMTP -> get_lines(): timelimit reached ('.
+                    'SMTP -> get_lines(): timelimit reached (' .
                     $this->Timelimit . ' sec)',
                     self::DEBUG_LOWLEVEL
                 );
@@ -1208,42 +1208,44 @@ class SMTP
      * Reports an error number and string.
      * @param integer $errno The error number returned by PHP.
      * @param string $errmsg The error message returned by PHP.
+     * @param string $errfile The file the error occurred in
+     * @param integer $errline The line number the error occurred on
      */
-    protected function errorHandler($errno, $errmsg)
+    protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
     {
-        $notice = 'Connection: Failed to connect to server.';
+        $notice = 'Connection failed.';
         $this->setError(
             $notice,
             $errno,
             $errmsg
         );
         $this->edebug(
-            $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg,
+            $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]",
             self::DEBUG_CONNECTION
         );
     }
 
-	/**
-	 * Will return the ID of the last smtp transaction based on a list of patterns provided
-	 * in SMTP::$smtp_transaction_id_patterns.
-	 * If no reply has been received yet, it will return null.
-	 * If no pattern has been matched, it will return false.
-	 * @return bool|null|string
-	 */
-	public function getLastTransactionID()
-	{
-		$reply = $this->getLastReply();
-
-		if (empty($reply)) {
-			return null;
-		}
-
-		foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
-			if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
-				return $matches[1];
-			}
-		}
-
-		return false;
+    /**
+     * Will return the ID of the last smtp transaction based on a list of patterns provided
+     * in SMTP::$smtp_transaction_id_patterns.
+     * If no reply has been received yet, it will return null.
+     * If no pattern has been matched, it will return false.
+     * @return bool|null|string
+     */
+    public function getLastTransactionID()
+    {
+        $reply = $this->getLastReply();
+
+        if (empty($reply)) {
+            return null;
+        }
+
+        foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
+            if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
+                return $matches[1];
+            }
+        }
+
+        return false;
     }
 }