Example #1
0
function sendInvitation()
{
    //Send the invitation. Many steps are performed in this function.
    global $debug, $message, $success;
    if (isset($_POST['folderId']) && isset($_POST['invitationFolderRole']) && !empty($_POST['invitationToAddress'])) {
        $folderId = intval($_POST['folderId']);
        $invitationFolderRole = intval($_POST['invitationFolderRole']);
        $toAddress = trim($_POST['invitationToAddress']);
        $invitationMessage = $_POST['invitationMessage'] != '(optional person message here)' ? trim($_POST['invitationMessage']) : '';
        $fromAddress = $_SESSION['primaryEmail'];
        $code = sha1($toAddress . TIMESTAMP);
        $link = LINKJOIN . '/?invitationCode=' . $code;
        $body = '<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#' . COLORBLACK . '" marginheight="0" marginwidth="0" text="#000000" topmargin="0">
<table width="800" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="left">' . buildHeaderForEmail() . '</td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE5 . '"><b>You\'ve Been Invited!</b><br>
&nbsp;</font></td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE3 . '">' . $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared an ADR list with you. To accept this invitation follow the link below:<br>
Link: <a href="' . $link . '">' . $link . '</a><br>
<br>
' . $invitationMessage . '<br>
&nbsp;</font><br>
<div style="height:100px">&nbsp;</div></td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE1 . '">This message was sent to you on behalf of ' . $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . '. Your email address has not been added to any mailing lists or given to third parties.</font><br>
&nbsp;</td>
	</tr>
</table>		
</body>
</html>';
        //<a href="' . LINKPRIVACY . '">Read our Privacy Policy here.</a>
        $subject = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared an ADR list with you at ' . THENAMEOFTHESITE;
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
        $headers .= 'To: ' . $toAddress . "\r\n";
        $headers .= 'From: ' . $fromAddress . "\r\n";
        //$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
        //$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
        //$headers .= 'Reply-to: ' . $fromAddress . '\r\n';
        //Check the users table to see if the email address already exists. If it does, make the link and refresh the 'Linked Accounts' section to show the user.
        $userCheckQuery = "SELECT\n\tusers.userId as 'userId'\nFROM\n\tusers\nWHERE\n\tusers.primaryEmail = '" . $toAddress . "'";
        if ($result = mysql_query($userCheckQuery)) {
            if (mysql_affected_rows() == 0) {
                $debug->add("A user with the email address of {$toAddress} does not exist in the database.");
                //Check the 'invitations' table to see if an invitation has already been made, but not responded to. This means the recipient hasn't joined yet. If there is no existing invitation make one.
                $invitationCheckQuery = "SELECT\n\tinvitations.email AS 'email'\nFROM\n\tinvitations\nWHERE\n\tinvitations.email = '" . $toAddress . "' AND\n\tinvitations.senderId = '" . $_SESSION['userId'] . "' AND\n\tinvitations.responded IS NULL";
                if (mysql_query($invitationCheckQuery)) {
                    if (mysql_affected_rows() == 0) {
                        //Insert the invitation in the database.
                        if (!empty($_POST['invitationListId']) && isset($_POST['invitationListRole'])) {
                            $invitationListId = intval($_POST['invitationListId']);
                            $invitationListRole = intval($_POST['invitationListRole']);
                            $invitationInsertQuery = "INSERT INTO\n\tinvitations\nSET\n\temail = '{$toAddress}',\n\tinvitationCode = '{$code}',\n\tfolderId = '{$folderId}',\n\tfolderRoleId = '{$invitationFolderRole}',\n\tlistId = '{$invitationListId}',\n\tlistRoleId = '{$invitationListRole}',\n\tsenderId = '" . $_SESSION['userId'] . "',\n\tsentDate = '" . DATETIME . "'";
                        } else {
                            $invitationInsertQuery = "INSERT INTO\n\tinvitations\nSET\n\temail = '{$toAddress}',\n\tinvitationCode = '{$code}',\n\tfolderId = '{$folderId}',\n\tfolderRoleId = '{$invitationFolderRole}',\n\tsenderId = '" . $_SESSION['userId'] . "',\n\tsentDate = '" . DATETIME . "'";
                        }
                        if (mysql_query($invitationInsertQuery)) {
                            $lastInvitationId = mysql_insert_id();
                            if (mysql_affected_rows() == 0) {
                                error(__LINE__);
                                pdoError(__LINE__, $invitationInsertQuery, '$invitationInsertQuery', 1);
                            } else {
                                if (!mail($toAddress, $subject, $body, $headers)) {
                                    error(__LINE__);
                                    ${$debug}->add('There was an error trying to send this email<br>
From Address: ' . $fromAddress . '<br>
' . "To Address: " . $toAddress . '<br>
' . "Headers: " . $headers . '<br>
' . "Subject: " . $subject . '<br>
' . "Body: " . $body . '.');
                                    $deleteInvitationQuery = "DELETE FROM\n\tinvitations\nWHERE\n\tinvitationId = '{$lastInvitationId}'";
                                    if (mysql_query($deleteInvitationQuery)) {
                                        if (mysql_affected_rows() == 0) {
                                            pdoError(__LINE__, $deleteInvitationQuery, '$deleteInvitationQuery', 1);
                                        }
                                        $debug->add('The invitation was deleted.');
                                    } else {
                                        pdoError(__LINE__, $deleteInvitationQuery, '$deleteInvitationQuery');
                                    }
                                } else {
                                    $message .= 'The invitation was sent.';
                                    $debug->add('An email has been sent.<br>
$body: ' . "{$body}.");
                                    $success = true;
                                    $returnThis['returnCode'] = buildInvitation();
                                }
                            }
                        } else {
                            error(__LINE__);
                            pdoError(__LINE__, $invitationInsertQuery, '$invitationInsertQuery');
                        }
                    } else {
                        $message .= "You've already sent an invitation to {$toAddress}, but the recipient has not responded yet. ";
                        $debug->add("An invitation already exists for {$toAddress}.");
                    }
                } else {
                    error(__LINE__);
                    pdoError(__LINE__, $invitationCheckQuery, '$invitationCheckQuery');
                }
            } else {
                $row = mysql_fetch_assoc($result);
                //A user with a matching email address exists. Check to see if the user is already linked to this folder account.
                $linkCheckQuery = "SELECT\n\tuserFolderSettings.folderId\nFROM\n\tuserFolderSettings\nJOIN\n\tusers ON userFolderSettings.userId = users.userId AND\n\tuserFolderSettings.folderId = '{$folderId}' AND\n\tusers.userId = '" . $row['userId'] . "'";
                $debug->add('$linkCheckQuery: ' . "{$linkCheckQuery}.");
                if ($result = mysql_query($linkCheckQuery)) {
                    if (mysql_affected_rows() == 0) {
                        //The user does not have a link to this folder account. Make a link in the database and send a different email to the newly linked user to notify him/her of the link.
                        $debug->add('Zero lines were affected by the query: $linkCheckQuery.');
                        $createLinkQuery = "INSERT INTO\n\tuserFolderSettings\nSET\n\tfolderId = '{$folderId}',\n\tuserId = (SELECT users.userId FROM users WHERE users.primaryEmail = '" . $toAddress . "'),\n\tfolderRoleId = (SELECT roles.roleId FROM roles WHERE roles.role = '{$invitationFolderRole}')";
                        if ($result = mysql_query($createLinkQuery)) {
                            if (mysql_affected_rows() == 0) {
                                error(__LINE__);
                                pdoError(__LINE__, $createLinkQuery, '$createLinkQuery', 1);
                            } else {
                                $body = '<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#' . COLORBLACK . '" marginheight="0" marginwidth="0" text="#000000" topmargin="0">
<table width="800" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="left">' . buildHeaderForEmail() . '</td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE3 . '">' . $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared an ADR list with you. <a href="' . LINKLOGIN . '">Login to view the list</a>.<br>
&nbsp;</font></td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE1 . '">This message was sent to you on behalf of ' . $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . '. Your email address has not been added to any mailing lists or given to third parties.<br>
&nbsp;</font></td>
	</tr>
</table>		
</body>
</html>';
                                // <a href="' . LINKPRIVACY . '">Read our Privacy Policy here.</a>
                                if (!mail($toAddress, $subject, $body, $headers)) {
                                    $message .= 'There was an error trying to send the email. Please try resending in a few moments. If further attempts fail please contact the webmaster. ';
                                    $debug->add('There was an error trying to send this email<br>
From Address: ' . $fromAddress . '<br>
' . "To Address: " . $toAddress . '.');
                                } else {
                                    $message .= 'The invitation was sent.';
                                    $debug->add('An email has been sent.<br>
$toAddress: ' . "{$toAddress}<br>" . '
$subject: ' . "{$subject}<br>" . '
$headers: ' . "{$headers}<br>" . '
$body: ' . "{$body}");
                                    $success = true;
                                    $returnThis['returnBuildFolders'] = buildFolders();
                                    $returnThis['returnBuildInvitation'] = buildInvitation();
                                }
                            }
                        } else {
                            error(__LINE__);
                            pdoError(__LINE__, $createLinkQuery, '$createLinkQuery');
                        }
                    } else {
                        $message .= 'The user at ' . $toAddress . ' already has a link to that folder. ';
                    }
                } else {
                    error(__LINE__);
                    pdoError(__LINE__, $linkCheckQuery, '$linkCheckQuery');
                }
            }
        } else {
            error(__LINE__);
            pdoError(__LINE__, $userCheckQuery, '$userCheckQuery');
        }
    } else {
        error(__LINE__);
        if (empty($_POST['invitationFolder'])) {
            $debug->add('$_POST[\'invitationFolder\'] is empty.');
        } elseif (!isset($_POST['invitationFolderRole'])) {
            $debug->add('$_POST[\'invitationFolderRole\'] is not set.');
        } elseif (empty($_POST['invitationToAddress'])) {
            $debug->add('$_POST[\'invitationToAddress\'] is empty.');
        } else {
            $debug->add('Something else is wrong.');
        }
    }
    returnData();
}
Example #2
0
function email($fromAddress, $toAddress, $subject, $bodyHtml, $bodyText, $senderAddress = NULL, $returnAddress = NULL)
{
    /*
    Send an email using the Swift Mailer class library. Returns true if sent successfully, false otherwise.
    $fromAddress = (string, array, associative array) one or more senders' email addresses. The email will show as coming from this address. Array structure is array('*****@*****.**' => 'Joe Bob'). Strings will be converted to an array.
    $toAddress = (string, array, associative array) recipients' email addresses. Array structure is array('*****@*****.**' => 'Joe Bob'). Strings will be converted to an array.
    $subject = (string) the subject of the email.
    $bodyHtml = (string) the body or message of the email. May contain HTML.
    $bodyText = (string) the text version of the message. Should not contain HTML.
    $senderAddress = (string) optional single email address of the sender, not necessarily the creator of the message. This address is visible in the message headers, will be seen by the recipients, and will be used as the Return-Path: unless otherwise specified. Default is EMAILDONOTREPLY set in config.php.
    $returnAddress = (string) an optional single email address to handle bounced emails. This address specifies where bounce notifications should be sent and is set with the setReturnPath() method of the message. You can use only one email address and it must not include a personal name. Default is EMAILDONOTREPLY defined in config.php.
    */
    require_once 'Classes/Swift/swift_init.php';
    global $debug, $message;
    if ((array) $fromAddress === $fromAddress) {
        $thisCount = 0;
        $newFromAddress = array();
        foreach ($fromAddress as $key) {
            //Add valid email addresses to the new array.
            if (emailValidate($key) === true) {
                $newFromAddress[] = $key;
            } elseif ($thisCount == 0) {
                error(__LINE__, '', "The to address '{$fromAddress}' is not valid.<br>");
                return false;
            }
            $thisCount++;
        }
        $fromAddress = $newFromAddress;
    } else {
        if (emailValidate($fromAddress) === true) {
            $fromAddress = array($fromAddress);
        } else {
            error(__LINE__, '', "The to address '{$fromAddress}' is not valid.<br>");
            return false;
        }
    }
    if ((array) $toAddress === $toAddress) {
        $thisCount = 0;
        $newToAddress = array();
        foreach ($toAddress as $key) {
            //Add valid email addresses to the new array.
            if (emailValidate($key) === true) {
                $newToAddress[] = $key;
            } elseif ($thisCount == 0) {
                error(__LINE__, '', "The to address '{$toAddress}' is not valid.<br>");
                return false;
            }
            $thisCount++;
        }
        $toAddress = $newToAddress;
    } else {
        if (emailValidate($toAddress) === true) {
            $toAddress = array($toAddress);
        } else {
            error(__LINE__, '', "The to address '{$toAddress}' is not valid.<br>");
            return false;
        }
    }
    $debug->add('$senderAddress before validation: ' . "{$senderAddress}");
    $senderAddress = emailValidate($senderAddress) ? $senderAddress : EMAILDONOTREPLY;
    $returnAddress = emailValidate($returnAddress) ? $returnAddress : EMAILDONOTREPLY;
    $debug->add('$senderAddress after validation: ' . "{$senderAddress}");
    //Create the message
    $email = Swift_Message::newInstance()->setFrom($fromAddress)->setTo($toAddress)->setSubject($subject)->addPart('<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF" marginheight="0" marginwidth="0" text="#000000" topmargin="0">
<table width="800" cellpadding="10" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="left">' . buildHeaderForEmail() . '</td>
	</tr>
	<tr>
		<td align="left"><font face="' . FONT . '" size="3">' . $bodyHtml . '
			<br>
			<br>
			Sincerly,<br>
			<br>
			' . THENAMEOFTHESITE . '
			<br>
			<br></font>
		</td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE1 . '">This is an automated message. Please do not reply.</font><br><br>
<a href="' . LINKSUPPORT . '">Click here to contact support.</a></td>
	</tr>
</table>		
</body>
</html>', 'text/html')->setBody($bodyText . '
Sincerly,

' . THENAMEOFTHESITE . ' Support


This is an automated message. Please do not reply.')->setSender($senderAddress)->setReturnPath($returnAddress);
    if (LOCAL) {
        //$transport = Swift_SmtpTransport::newInstance('127.0.0.0', 25);//Doesn't work on local machine.
        $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
        //This uses the local machine's MTA, not a remote service.
        //$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')->setUsername('*****@*****.**')->setPassword('');//This uses a remote service like gmail for secure mail transactions.
    } else {
        $transport = Swift_SendmailTransport::newInstance('/usr/sbin/exim -bs');
        //This works better with ServInt.
    }
    $mailer = Swift_Mailer::newInstance($transport);
    //To use the ArrayLogger.
    $logger = new Swift_Plugins_Loggers_ArrayLogger();
    $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
    if ($mailer->send($email, $failures)) {
        return true;
    } else {
        $debug->printArray($failures, 'email address undeliverable');
        return false;
    }
    //Dump the error log.
    $debug->add($logger->dump());
}