Skip to content

Commit

Permalink
Fixed issue: Optimized SMTP connections so they are re-used instead o…
Browse files Browse the repository at this point in the history
…f opening one connection for each email send

git-svn-id: file:///Users/Shitiz/Downloads/lssvn/source/limesurvey@10626 b72ed6b6-b9f8-46b5-92b4-906544132732
  • Loading branch information
c-schmitz committed Aug 2, 2011
1 parent 4dd3173 commit c56b5ee
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 33 deletions.
2 changes: 1 addition & 1 deletion admin/dataentry.php
Expand Up @@ -394,7 +394,7 @@
if (isset($tokendata['token'])) {$message.="&token=".$tokendata['token'];}
$from = $thissurvey['adminemail'];

if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid)))
if (SendEmailMessage(null, $message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid)))
{
$emailsent="Y";
$dataentryoutput .= "<font class='successtitle'>".$clang->gT("An email has been sent with details about your saved survey")."</font><br />\n";
Expand Down
18 changes: 11 additions & 7 deletions admin/tokens.php
Expand Up @@ -1553,6 +1553,7 @@
if ($emcount > 0)
{
$tokenoutput .= "<ul>\n";
$oMail = new PHPMailer;
while ($emrow = $emresult->FetchRow())
{
unset($fieldsarray);
Expand Down Expand Up @@ -1605,10 +1606,10 @@
$fieldsarray["@@SURVEYURL@@"]="$publicurl/index.php?lang=".trim($emrow['language'])."&amp;sid=$surveyid&amp;token={$emrow['token']}";
}
}
$customheaders = array( '1' => "X-surveyid: ".$surveyid,
'2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]);
$customheaders = array( '1' => "X-surveyid: ".$surveyid,
'2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]);

$modsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray);
$modsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray);
$modmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray);

if (trim($emrow['validfrom'])!='' && convertDateTimeFormat($emrow['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1)
Expand All @@ -1619,7 +1620,7 @@
{
$tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."<br />", $fieldsarray);
}
elseif (SendEmailMessage($modmessage, $modsubject, $to , $from, $sitename, $ishtml, getBounceEmail($surveyid),null,$customheaders))
elseif (SendEmailMessage($oMail, $modmessage, $modsubject, $to , $from, $sitename, $ishtml, getBounceEmail($surveyid),null,$customheaders))
{
// Put date into sent
$today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust);
Expand Down Expand Up @@ -1678,6 +1679,7 @@
}
$tokenoutput .="</form>\n";
}
$oMail->SmtpClose();
}
else
{
Expand Down Expand Up @@ -1879,6 +1881,7 @@
$tokenoutput .= "<table width='450' align='center' >\n"
."\t<tr>\n"
."<td><font size='1'>\n";
$oMail = new PHPMailer;
while ($emrow = $emresult->FetchRow())
{
unset($fieldsarray);
Expand Down Expand Up @@ -1942,8 +1945,8 @@

$msgsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray);
$sendmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray);
$customheaders = array( '1' => "X-surveyid: ".$surveyid,
'2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]);
$customheaders = array( '1' => "X-surveyid: ".$surveyid,
'2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]);

if (trim($emrow['validfrom'])!='' && convertDateTimeFormat($emrow['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1)
{
Expand All @@ -1953,7 +1956,7 @@
{
$tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."<br />", $fieldsarray);
}
elseif (SendEmailMessage($sendmessage, $msgsubject, $to, $from, $sitename,$ishtml,getBounceEmail($surveyid),null,$customheaders))
elseif (SendEmailMessage($oMail, $sendmessage, $msgsubject, $to, $from, $sitename,$ishtml,getBounceEmail($surveyid),null,$customheaders))
{

// Put date into remindersent
Expand All @@ -1976,6 +1979,7 @@
}
$lasttid = $emrow['tid'];
}
$oMail->SmtpClose();
if ($ctcount > $emcount)
{
$lefttosend = $ctcount-$maxemails;
Expand Down
10 changes: 5 additions & 5 deletions admin/usercontrol.php
Expand Up @@ -75,7 +75,7 @@
$from = $siteadminemail;
$sitename = $siteadminname;

if(SendEmailMessage($body, $subject, $to, $from, $sitename, false,$siteadminbounce))
if(SendEmailMessage(null, $body, $subject, $to, $from, $sitename, false,$siteadminbounce))
{
$query = "UPDATE ".db_table_name('users')." SET password='".SHA256::hashing($new_pass)."' WHERE uid={$fields['uid']}";
$connect->Execute($query); //Checked
Expand Down Expand Up @@ -190,7 +190,7 @@
}
else
{

if ( $fields['lang']=='auto' && isset( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ) )
{
$browlang=strtolower( $_SERVER["HTTP_ACCEPT_LANGUAGE"] );
Expand All @@ -211,7 +211,7 @@
else
{
$_SESSION['adminlang'] = $fields['lang'];
}
}
$clang = new limesurvey_lang($_SESSION['adminlang']);
}
$login = true;
Expand Down Expand Up @@ -430,7 +430,7 @@
elseif($valid_email)
{
$new_pass = createPassword();
$uquery = "INSERT INTO {$dbprefix}users (users_name, password,full_name,parent_id,lang,email,create_survey,create_user,delete_user,superadmin,configurator,manage_template,manage_label)
$uquery = "INSERT INTO {$dbprefix}users (users_name, password,full_name,parent_id,lang,email,create_survey,create_user,delete_user,superadmin,configurator,manage_template,manage_label)
VALUES ('".db_quote($new_user)."', '".SHA256::hashing($new_pass)."', '".db_quote($new_full_name)."', {$_SESSION['loginID']}, 'auto', '".db_quote($new_email)."',0,0,0,0,0,0,0)";
$uresult = $connect->Execute($uquery); //Checked

Expand Down Expand Up @@ -478,7 +478,7 @@
$to = $new_user." <$new_email>";
$from = $siteadminname." <$siteadminemail>";
$addsummary .="<div class='messagebox ui-corner-all'>";
if(SendEmailMessage($body, $subject, $to, $from, $sitename, true, $siteadminbounce))
if(SendEmailMessage(null, $body, $subject, $to, $from, $sitename, true, $siteadminbounce))
{
$addsummary .= "<br />".$clang->gT("Username").": $new_user<br />".$clang->gT("Email").": $new_email<br />";
$addsummary .= "<br />".$clang->gT("An email with a generated password was sent to the user.");
Expand Down
16 changes: 8 additions & 8 deletions admin/userrighthandling.php
Expand Up @@ -33,7 +33,7 @@
$grpquery = "SELECT gp.* FROM ".db_table_name('user_groups')." AS gp, ".db_table_name('user_in_groups')." AS gu WHERE gp.ugid=gu.ugid AND gp.ugid = $ugid AND gu.uid=".$_SESSION['loginID'];
$grpresult = db_execute_assoc($grpquery);//Checked
$grpresultcount = $grpresult->RecordCount();
if ($grpresultcount>0)
if ($grpresultcount>0)
{
$grow = array_map('htmlspecialchars', $grpresult->FetchRow());
}
Expand Down Expand Up @@ -152,7 +152,7 @@
."<br /><input type='checkbox' alt='".$clang->gT("Check or uncheck all items")."' class='tipme' id='checkall' />"
."</th>\n\t</tr>\n"
."\t</thead>\n";

$usersummary .= "<tfoot>\n"
."<tr>\n"
."<td colspan=\"3\">\n"
Expand All @@ -162,7 +162,7 @@
."</td>\n"
."</tr>\n"
."</tfoot>\n";

$usersummary .= "<tbody>\n";

$tquery = "SELECT * FROM ".$dbprefix."templates";
Expand Down Expand Up @@ -305,7 +305,7 @@
$row=$adminresult->FetchRow();

$usersummary .="<tr>\n";

// Only Initial SuperAdmin can give SuperAdmin rights
if($row['uid'] == $_SESSION['loginID'])
{ // RENAMED AS SUPERADMIN
Expand Down Expand Up @@ -581,7 +581,7 @@
$userlist = array();
$srow = $uresult->FetchRow();
$usr['parent'] = $srow['users_name'];

//TODO: Find out why parent isn't set
// ==> because it is parent_id ;-)
if (isset($usr['parent_id']))
Expand Down Expand Up @@ -816,7 +816,7 @@


//echo $body . '-'.$subject .'-'.'<pre>'.htmlspecialchars($to).'</pre>'.'-'.$from;
if (SendEmailMessage( $body, $subject, $to, $from,''))
if (SendEmailMessage(null, $body, $subject, $to, $from,''))
{
$usersummary = "<div class=\"messagebox\">\n";
$usersummary .= "<div class=\"successheader\">".$clang->gT("Message(s) sent successfully!")."</div>\n"
Expand Down Expand Up @@ -857,13 +857,13 @@
$usersummary = "<div class=\"messagebox\">\n";
if(updateusergroup($db_name, $db_description, $ugid))
{

$usersummary .= "<div class=\"successheader\">".$clang->gT("Edit User Group Successfully!")."</div>\n"
. "<br />".$clang->gT("Name").": {$html_name}<br />\n"
. $clang->gT("Description: ").$html_description."<br />\n"
. "<br /><a href='$scriptname?action=editusergroups&amp;ugid={$ugid}'>".$clang->gT("Continue")."</a><br />&nbsp;\n";
}
else
else
{
$usersummary .= "<div class=\"warningheader\">".$clang->gT("Failed to update!")."</div>\n"
. "<br /><a href='$scriptname?action=editusergroups'>".$clang->gT("Continue")."</a><br />&nbsp;\n";
Expand Down
20 changes: 18 additions & 2 deletions common_functions.php
Expand Up @@ -4179,7 +4179,10 @@ function ReplaceFields ($text,$fieldsarray, $bReplaceInsertans=false)
/**
* This function mails a text $body to the recipient $to.
* You can use more than one recipient when using a semikolon separated string with recipients.
* If you send several emails at once please supply an email object so that it can be re-used over and over. Especially with SMTP connections this speeds up things by 200%.
* If you supply an email object Do not forget to close the mail connection by calling $mail->SMTPClose();
*
* @param mixed $mail This is an PHPMailer object. If null, one will be created automatically and unset afterwards. If supplied it won't be unset.
* @param string $body Body text of the email in plain text or HTML
* @param mixed $subject Email subject
* @param mixed $to
Expand All @@ -4190,7 +4193,7 @@ function ReplaceFields ($text,$fieldsarray, $bReplaceInsertans=false)
* @param mixed $attachment
* @return bool If successful returns true
*/
function SendEmailMessage($body, $subject, $to, $from, $sitename, $ishtml=false, $bouncemail=null, $attachment=null, $customheaders="")
function SendEmailMessage($mail, $body, $subject, $to, $from, $sitename, $ishtml=false, $bouncemail=null, $attachment=null, $customheaders="")
{

global $emailmethod, $emailsmtphost, $emailsmtpuser, $emailsmtppassword, $defaultlang, $emailsmtpdebug;
Expand All @@ -4215,8 +4218,17 @@ function SendEmailMessage($body, $subject, $to, $from, $sitename, $ishtml=false,
{
$sender=$bouncemail;
}
$bUnsetEmail=false;
if (is_null($mail))
{
$bUnsetEmail=true;
$mail = new PHPMailer;
}
else
{
$mail->SMTPKeepAlive=true;
}

$mail = new PHPMailer;
if (!$mail->SetLanguage($defaultlang,$rootdir.'/classes/phpmailer/language/'))
{
$mail->SetLanguage('en',$rootdir.'/classes/phpmailer/language/');
Expand Down Expand Up @@ -4326,6 +4338,10 @@ function SendEmailMessage($body, $subject, $to, $from, $sitename, $ishtml=false,
ob_end_clean();
}
$maildebugbody=$mail->Body;
if ($bUnsetEmail)
{
unset($mail);
}
return $sent;
}

Expand Down
12 changes: 8 additions & 4 deletions index.php
Expand Up @@ -2063,7 +2063,7 @@ function submittokens($quotaexit=false)
//Only send confirmation email if there is a valid email address
if (validate_email($cnfrow['email']))
{
SendEmailMessage($message, $subject, $to, $from, $sitename,$ishtml);
SendEmailMessage(null,$message, $subject, $to, $from, $sitename,$ishtml);
}
}
else
Expand Down Expand Up @@ -2200,32 +2200,36 @@ function SendSubmitNotifications()
{
$sMessage=templatereplace($thissurvey['email_admin_notification'],$aReplacementVars,($thissurvey['anonymized'] == "Y"));
$sSubject=templatereplace($thissurvey['email_admin_notification_subj'],$aReplacementVars,($thissurvey['anonymized'] == "Y"));
$oMail = new PHPMailer;
foreach ($aEmailNotificationTo as $sRecipient)
{
if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, $bIsHTML, getBounceEmail($surveyid)))
if (!SendEmailMessage($oMail, $sMessage, $sSubject, $sRecipient, $sFrom, $sitename, $bIsHTML, getBounceEmail($surveyid)))
{
if ($debug>0)
{
echo '<br />Email could not be sent. Reason: '.$maildebug.'<br/>';
}
}
}
$oMail->SmtpClose();
}

if (count($aEmailResponseTo)>0)
{
$sMessage=templatereplace($thissurvey['email_admin_responses'],$aReplacementVars);
$sSubject=templatereplace($thissurvey['email_admin_responses_subj'],$aReplacementVars);
$mail = new PHPMailer;
foreach ($aEmailResponseTo as $sRecipient)
{
if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, $bIsHTML, getBounceEmail($surveyid)))
if (!SendEmailMessage($mail,$sMessage, $sSubject, $sRecipient, $sFrom, $sitename, $bIsHTML, getBounceEmail($surveyid)))
{
if ($debug>0)
{
echo '<br />Email could not be sent. Reason: '.$maildebug.'<br/>';
}
}
}
$mail->SmtpClose();
}


Expand Down Expand Up @@ -2257,7 +2261,7 @@ function submitfailed($errormsg='')
. "$subquery\n\n"
. $clang->gT("ERROR MESSAGE","unescaped").":\n"
. $errormsg."\n\n";
SendEmailMessage($email, $clang->gT("Error saving results","unescaped"), $thissurvey['adminemail'], $thissurvey['adminemail'], "LimeSurvey", false, getBounceEmail($surveyid));
SendEmailMessage(null,$email, $clang->gT("Error saving results","unescaped"), $thissurvey['adminemail'], $thissurvey['adminemail'], "LimeSurvey", false, getBounceEmail($surveyid));
//echo "<!-- EMAIL CONTENTS:\n$email -->\n";
//An email has been sent, so we can kill off this session.
session_unset();
Expand Down
8 changes: 4 additions & 4 deletions register.php
Expand Up @@ -117,7 +117,7 @@
$result = $connect->Execute($query, array($postfirstname,
$postlastname,
returnglobal('register_email'),
'OK',
'OK',
$newtoken)
// $postattribute1, $postattribute2)
) or safe_die ($query."<br />".$connect->ErrorMsg()); //Checked - According to adodb docs the bound variables are quoted automatically
Expand Down Expand Up @@ -158,7 +158,7 @@

$html=""; //Set variable

if (SendEmailMessage($message, $subject, returnglobal('register_email'), $from, $sitename,$useHtmlEmail,getBounceEmail($surveyid)))
if (SendEmailMessage(null, $message, $subject, returnglobal('register_email'), $from, $sitename,$useHtmlEmail,getBounceEmail($surveyid)))
{
// TLR change to put date into sent
// $query = "UPDATE {$dbprefix}tokens_$surveyid\n"
Expand All @@ -180,8 +180,8 @@
if (!$thissurvey['template'])
{
$thistpl=sGetTemplatePath(validate_templatedir('default'));
}
else
}
else
{
$thistpl=sGetTemplatePath(validate_templatedir($thissurvey['template']));
}
Expand Down
4 changes: 2 additions & 2 deletions save.php
Expand Up @@ -389,7 +389,7 @@ function savedcontrol()

if ($clienttoken){$message.="&token=".$clienttoken;}
$from="{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid)))
if (SendEmailMessage(null, $message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid)))
{
$emailsent="Y";
}
Expand Down Expand Up @@ -434,7 +434,7 @@ function savedsilent()
{
$message .= "\n\n$publicurl/index.php?lang=$language&sid=$surveyid&token=$clienttoken";
};
if (SendEmailMessage($message, $subject, $to, $from, $sitename, false, getBounceEmail($surveyid)))
if (SendEmailMessage(null, $message, $subject, $to, $from, $sitename, false, getBounceEmail($surveyid)))
{
$emailsent="Y";
}
Expand Down

0 comments on commit c56b5ee

Please sign in to comment.