예제 #1
0
function testDb()
{
    global $Dbc, $debug, $message, $success;
    if (!empty($_POST['email']) && emailValidate($_POST['email']) && !empty($_POST['firstName']) && !empty($_POST['lastName']) && !empty($_POST['password']) && passwordValidate($_POST['password'])) {
        destroySession();
        $email = trim($_POST['email']);
        $pass = sha1(trim($_POST['password']));
        $firstName = trim($_POST['firstName']);
        $lastName = trim($_POST['lastName']);
        $rememberMeCode = sha1($email);
        $Dbc->beginTransaction();
        try {
            $stmt = $Dbc->prepare("SELECT getUserIdByEmail(?) AS 'userId'");
            $stmt .= $stmt->execute(array($email));
            while ($row = $stmt->fetch()) {
                $debug->add('$row[\'userId\']: ' . $row['userId']);
                $debug->printArray($row, '$row');
                if (empty($row['userId'])) {
                    //There are no users with the email address, so continue.
                    pdoError(__LINE__, $stmt, 1);
                    $stmt = $Dbc->prepare("INSERT INTO\n\tusers\nSET\n\tprimaryEmail = ?,\n\tuserPassword = ?,\n\tfirstName = ?,\n\tlastName = ?,\n\tjoinDate = ?");
                    if ($stmt->execute(array($email, $pass, $firstName, $lastName, DATETIME))) {
                        $debug->add('last id: ' . $Dbc->lastInsertId());
                    } else {
                        pdoError(__LINE__, $stmt);
                    }
                } else {
                    $message .= 'That email address is already associated with an account. Please enter a different email address.<br>';
                }
            }
        } catch (PDOException $e) {
            //Rollback occurs automatically if an exception is thrown.
            error(__LINE__, '', '<pre>' . $e . '</pre>');
            pdoError(__LINE__);
        }
    } elseif (empty($_POST['email'])) {
        $debug->add('email is empty on line ' . __LINE__ . '');
        $message .= 'Please enter an email address.';
    } elseif (!emailValidate($_POST['email'])) {
        $message .= 'Please enter a valid email address.';
        $debug->add('Email address is not valid.');
    } elseif (empty($_POST['firstName'])) {
        $debug->add('first name is empty on line ' . __LINE__ . '.');
        $message .= 'Please enter a First Name.';
    } elseif (empty($_POST['lastName'])) {
        $debug->add('last name is empty on line ' . __LINE__ . '.');
        $message .= 'Please enter a Last Name.';
    } elseif (empty($_POST['password'])) {
        $debug->add('password is empty on line ' . __LINE__ . '.');
        $message .= 'Please enter a password.';
    } else {
        $debug->add('Something is missing.');
    }
    returnData();
}
예제 #2
0
function importIntoMySQL($options)
{
    $username = $options["u"];
    $password = $options["p"];
    $host = $options["h"];
    $dbname = $options["d"];
    //database connection details
    $conn = new mysqli($host, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $val = "select 1 from `Users` LIMIT 1";
    if ($conn->query($val) === FALSE) {
        echo 'Table Users does not existed' . PHP_EOL;
        createTable($options);
    }
    $csv_file = $options["file"];
    if (($handle = fopen($csv_file, "r")) !== FALSE) {
        fgetcsv($handle);
        while (($data = fgetcsv($handle, ",")) !== FALSE) {
            $num = count($data);
            for ($c = 0; $c < $num; $c++) {
                $col[$c] = $data[$c];
            }
            $name = mysqli_real_escape_string($conn, ucfirst($col[0]));
            $surname = mysqli_real_escape_string($conn, ucfirst($col[1]));
            $email = strtolower(trim($col[2]));
            $status = emailValidate($email);
            if (!$status) {
                echo $name . " " . $surname . " ";
                echo "This ({$email}) email address is not valid." . PHP_EOL;
            } else {
                $sql = "INSERT INTO `Users`( `name`, `surname`, `email`) VALUES ('" . $name . "','" . $surname . "','" . mysqli_real_escape_string($conn, $email) . "') ";
                if ($conn->query($sql) === TRUE) {
                    echo "New record created successfully" . PHP_EOL;
                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error . PHP_EOL;
                }
            }
        }
        fclose($handle);
    }
    $conn->close();
}
예제 #3
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());
}
예제 #4
0
include "./DB.php";
$dom = new DOMDocument();
$user_Info = $dom->createElement("Info");
$user_Login = $dom->createElement("Login");
//$txt = $dom->createTextNode("true");
$_SESSION['login'] = false;
if (!isset($_POST["email"]) || !isset($_POST["password"])) {
    $txt = $dom->createTextNode("false");
    $user_Login->appendChild($txt);
    $user_Info->appendChild($user_Login);
    $dom->appendChild($user_Info);
    echo $dom->saveXML();
    return;
}
$email = $_POST["email"];
if (!emailValidate($email)) {
    $txt = $dom->createTextNode("false");
    $user_Login->appendChild($txt);
    $user_Info->appendChild($user_Login);
    $dom->appendChild($user_Info);
    echo $dom->saveXML();
    return;
}
$password = $_POST["password"];
$userinfo = LogIN($email, $password);
if (!isset($userinfo["login"])) {
    $txt = $dom->createTextNode("false");
    $user_Login->appendChild($txt);
    $user_Info->appendChild($user_Login);
    $dom->appendChild($user_Info);
    echo $dom->saveXML();
예제 #5
0
     //Delete cookie.
     header('Location: ' . AUTOLINK);
 } elseif (isset($_POST['mode']) && $_POST['mode'] == 'login') {
     //The cookie is empty. See if the user is attempting to login and check the email and password against the database.
     $debug->add('4');
     if (!isset($_POST['email'])) {
         throw new Adrlist_CustomException('', '$_POST[\'email\'] is not set.');
     }
     if (!isset($_POST['password'])) {
         throw new Adrlist_CustomException('', '$_POST[\'password\'] is not set.');
     }
     $loggedEmail = trim($_POST['email']);
     //use trim to clear any white space from the beginning and end
     $loggedPassword = trim($_POST['password']);
     $sha1loggedPassword = sha1($loggedPassword);
     $emailCheck = emailValidate($_POST['email']);
     if (!$emailCheck) {
         throw new Adrlist_CustomException('', 'Please enter a valid email address.');
     }
     $loginStmt = $Dbc->prepare("SELECT\n\tusers.userId AS 'userId',\n\tusers.primaryEmail AS 'primaryEmail',\n\tusers.secondaryEmail AS 'secondaryEmail',\n\tusers.firstName AS 'firstName',\n\tusers.lastName AS 'lastName',\n\tuserSiteSettings.timeZone AS 'timeZone',\n\tuserSiteSettings.siteRoleId AS 'siteRoleId',\n\tdateFormat.dateFormat AS 'dateFormat'\nFROM\n\tusers\nJOIN\n\tuserSiteSettings ON userSiteSettings.userId = users.userId AND\n\tusers.primaryEmail = ? AND\n\tusers.userPassword = ?\nJOIN\n\tdateFormat ON dateFormat.dateFormatId = userSiteSettings.dateFormatId");
     $loginParams = array($loggedEmail, $sha1loggedPassword);
     $loginStmt->execute($loginParams);
     $row = $loginStmt->fetch(PDO::FETCH_ASSOC);
     if (empty($row)) {
         pdoError(__LINE__, $loginStmt, $loginParams, 1);
         throw new Adrlist_CustomException('Your email/password was not found. Please try again.', '');
     }
     if (empty($row['siteRoleId'])) {
         $message .= 'An administrative action is preventing you from logging in. Please <a href="' . LINKSUPPORT . '">contact support</a> for help.';
         returnData();
     }
예제 #6
0
            $rowE = pg_fetch_row($result1);
            $GLOBALS['rowEmpresa'] = $rowE;
        }
        $p = $GLOBALS["rowUser"][0];
        $e = $GLOBALS['rowEmpresa'][0];
        $query2 = "insert into persona_empresa(idPersona, idEmpresa) values({$p},{$e});";
        $result2 = pg_query($GLOBALS["conn"], $query2);
        return array('state' => "Correcto", 'box' => "#box-company-profile");
    } else {
        $GLOBALS["estado"] = 1;
        return array('state' => "Incorrecto", 'box' => "#box-company-profile", 'errorBox' => "#error-company-profile", 'error' => "Debe tener al menos 2 caracteres.");
    }
}
$array_data[] = nameValidate($name);
$array_data[] = lastNameValidate($lastName);
$array_data[] = emailValidate($email, $username);
$query2 = "delete from persona_empresa where idPersona={$rowUser['0']}";
$result2 = pg_query($GLOBALS["conn"], $query2);
unset($_SESSION["rowCompany"]);
if ($companyName != "") {
    $array_data[] = companyNameValidate($companyName);
    $query = "Select * from empresas where nombre='{$companyName}'";
    $result = pg_query($conn, $query);
    $row = pg_fetch_row($result);
    $_SESSION["rowCompany"] = $row;
}
if ($estado === 0) {
    $query = "update personas set nombre='{$name}', apellidos='{$lastName}', correo='{$email}' where idPersona='{$rowUser['0']}'";
    $result = pg_query($conn, $query);
    $query1 = "Select * from personas where idPersona='{$rowUser['0']}'";
    $result1 = pg_query($conn, $query1);
예제 #7
0
function saveMyInformation()
{
    /*Save the updated user information.
    	//This has become a rather complex and lengthy script. The best way to handle it is to compare the current information to the new information to see what has changed. Then do verifications on the changed information.
    	*/
    global $debug, $message, $success, $Dbc, $returnThis;
    try {
        //The secondary email and new password fields are optional, so we must test them separately from the rest.
        if (empty($_POST['firstName'])) {
            throw new Adrlist_CustomException('', '$_POST[\'firstName\'] is empty.');
        } elseif (strlen($_POST['firstName']) > 255) {
            throw new Adrlist_CustomException('', '$_POST[\'firstName\'] is more than 255 characters.');
        } elseif (empty($_POST['lastName'])) {
            throw new Adrlist_CustomException('', '$_POST[\'lastName\'] is empty.');
        } elseif (strlen($_POST['lastName']) > 255) {
            throw new Adrlist_CustomException('', '$_POST[\'lastName\'] is more than 255 characters.');
        } elseif (empty($_POST['primaryEmail'])) {
            throw new Adrlist_CustomException('', '$_POST[\'primaryEmail\'] is empty.');
        } elseif (!emailValidate($_POST['primaryEmail'])) {
            throw new Adrlist_CustomException('', '$_POST[\'primaryEmail\'] is not a valid email address.');
        } elseif (empty($_POST['primaryEmailRetype'])) {
            throw new Adrlist_CustomException('', '$_POST[\'primaryEmailRetype\'] is empty.');
        } elseif ($_POST['primaryEmail'] != $_POST['primaryEmailRetype']) {
            throw new Adrlist_CustomException("The primary email addresses don't match.", '');
        } elseif (empty($_POST['currentPassword'])) {
            throw new Adrlist_CustomException('', '$_POST[\'currentPassword\'] is empty.');
        } elseif (!passwordValidate($_POST['currentPassword'])) {
            throw new Adrlist_CustomException('', '$_POST[\'currentPassword\'] is not valid.');
        }
        $_POST['firstName'] = trim($_POST['firstName']);
        $_POST['lastName'] = trim($_POST['lastName']);
        $_POST['primaryEmail'] = trim($_POST['primaryEmail']);
        $_POST['currentPassword'] = trim($_POST['currentPassword']);
        $_POST['newPassword'] = trim($_POST['newPassword']);
        $_POST['secondaryEmail'] = trim($_POST['secondaryEmail']);
        $toAddress = array();
        $Dbc->beginTransaction();
        //Verify the user has entered the correct current password. Grab other info to check what has been changed.
        $stmt = $Dbc->prepare("SELECT\n\tfirstName AS 'firstName',\n\tlastName AS 'lastName',\n\tprimaryEmail AS 'primaryEmail',\n\tsecondaryEmail AS 'secondaryEmail',\n\tuserPassword AS 'password'\nFROM\n\tusers\nWHERE\n\tuserId = ? AND\n\tuserPassword = ?");
        $sha1CurrentPassword = sha1($_POST['currentPassword']);
        $sha1NewPassword = sha1($_POST['newPassword']);
        $params = array($_SESSION['userId'], $sha1CurrentPassword);
        $stmt->execute($params);
        $currentInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        $debug->printArray($currentInfo, '$currentInfo');
        $debug->printArray($_POST, '$_POST');
        if (empty($currentInfo['password'])) {
            pdoError(__LINE__, $stmt, $params, true);
            throw new Adrlist_CustomException('Your password could not be verified. Please re-enter your current password.', '');
        }
        $debug->add('The user has entered the correct current password.');
        if (!empty($currentInfo['secondaryEmail'])) {
            $toAddress[] = $currentInfo['secondaryEmail'];
        }
        $newInformationArray = array('First Name' => $_POST['firstName'], 'Last Name' => $_POST['lastName'], 'Primary Email Address' => $_POST['primaryEmail'], 'Secondary Email Address' => $_POST['secondaryEmail']);
        //Check if the password has changed.
        if (empty($_POST['newPassword'])) {
            $returnThis['pass'] = $_POST['currentPassword'];
            $newInformationArray['Password'] = $sha1CurrentPassword;
        } elseif ($_POST['newPassword'] != $_POST['newPasswordRetype']) {
            throw new Adrlist_CustomException('The new passwords don\'t match. Please re-enter a new password.', '');
        } elseif (!passwordValidate($_POST['newPassword'])) {
            throw new Adrlist_CustomException('The new password you entered contains invalid characters. Please enter a valid password.', '');
        } else {
            //Update the password.
            $stmt = $Dbc->prepare("UPDATE\n\tusers\nSET\n\tuserPassword = ?\nWHERE\n\tuserId = ?");
            $params = array($sha1NewPassword, $_SESSION['userId']);
            $stmt->execute($params);
            $returnThis['pass'] = $_POST['newPassword'];
            $newInformationArray['Password'] = $sha1NewPassword;
        }
        //Compare the information in the database with the new information to report what has changed.
        $changes = array_diff($newInformationArray, $currentInfo);
        $debug->printArray($changes, '$changes');
        if (empty($changes)) {
            $message .= 'No changes were made.<br>';
        } else {
            //Update the secondary email only if it has changed and isn't empty.
            if (array_key_exists('Secondary Email Address', $changes)) {
                $debug->add('I detect that the Secondary Email Address has been changed.');
                //Verify the new secondary email is different from the current and new primary email, and the re-type matches.
                if (empty($_POST['secondaryEmail'])) {
                    //The user has removed a secondary email. Set the secondary email to null.
                    $stmt = $Dbc->prepare("UPDATE\n\tusers\nSET\n\tsecondaryEmail = ?\nWHERE\n\tuserId = ?");
                    $params = array(NULL, $_SESSION['userId']);
                    $stmt->execute($params);
                } elseif ($_POST['secondaryEmail'] != $currentInfo['primaryEmail'] && $_POST['secondaryEmail'] != $_POST['primaryEmail'] && $_POST['secondaryEmail'] == $_POST['secondaryEmailRetype'] && emailValidate($_POST['secondaryEmail'])) {
                    //Check to see if secondaryEmail is used by another user as either a primary or secondary email.
                    $debug->add('About to check the Secondary Email Address.');
                    $stmt = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tsecondaryEmail = ? OR\n\tprimaryEmail = ? AND\n\tuserId <> ?");
                    $params = array($_POST['secondaryEmail'], $_POST['secondaryEmail'], $_SESSION['userId']);
                    $stmt->execute($params);
                    $row = $stmt->fetch(PDO::FETCH_ASSOC);
                    if (empty($row['userId']) && empty($row['userId'])) {
                        pdoError(__LINE__, $stmt, $params, true);
                        $debug->add('As there are no users with the secondary email address ' . $_POST['secondaryEmail'] . ' this user can use it.');
                        //Update secondary email.
                        $stmt = $Dbc->prepare("UPDATE\n\tusers\nSET\n\tsecondaryEmail = ?\nWHERE\n\tuserId = ?");
                        $stmt->execute(array($_POST['secondaryEmail'], $_SESSION['userId']));
                        $toAddress[] = $_POST['secondaryEmail'];
                    } else {
                        throw new Adrlist_CustomException('The Secondary Email Address your entered is associated with another account.<br>
<div style="height:.6em"></div>
Please choose a different Secondary Email Address.<br>', '');
                    }
                } else {
                    if ($_POST['secondaryEmail'] == $currentInfo['primaryEmail']) {
                        $message .= 'The Primary and Secondary Email Addresses must be different.<br>';
                    } elseif ($_POST['secondaryEmail'] != $_POST['secondaryEmailRetype']) {
                        $message .= 'The secondary email addresses don\'t match.<br>';
                    } elseif (!emailValidate($_POST['secondaryEmail'])) {
                        $debug->add('$_POST[\'secondaryEmail\'] is not a valid email address.<br>
<div style="height:.6em"></div>
Please enter a valid email address.');
                    }
                }
            }
            //Update the Primary Email Address only if it has changed.
            if (array_key_exists('Primary Email Address', $changes)) {
                $debug->add('I detect that the Primary Email Address has been changed.');
                //Verify the new Primary Email is different from the Secondary Email.
                if ($_POST['primaryEmail'] == $currentInfo['secondaryEmail']) {
                    throw new Adrlist_CustomException('The Primary and Secondary email addresses must be different.', '');
                }
                //Check to see if the primary email address is used by another user.
                $debug->add('About to check the Primary Email Address.');
                $stmt = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tsecondaryEmail = ? OR\n\tprimaryEmail = ? AND\n\tuserId <> ?");
                $params = array($_POST['primaryEmail'], $_POST['primaryEmail'], $_SESSION['userId']);
                $stmt->execute($params);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!empty($row['userId'])) {
                    throw new Adrlist_CustomException('The Primary Email Address your entered is associated with another account.<br>
<div style="height:.6em"></div>
Please enter a different Primary Email Address.<br>', '');
                }
                pdoError(__LINE__, $stmt, $params, true);
                $debug->add('As there are no users with the email address ' . $_POST['primaryEmail'] . ' this user can use it.');
                //Update the user's Primary Email Address.
                $stmt = $Dbc->prepare("UPDATE\n\tusers\nSET\n\tprimaryEmail = ?\nWHERE\n\tuserId = ?");
                $params = array($_POST['primaryEmail'], $_SESSION['userId']);
                $stmt->execute($params);
                $toAddress[] = $_POST['primaryEmail'];
            }
            //Update the rest of the info.
            $stmt = $Dbc->prepare("UPDATE\n\tusers\nSET\n\tfirstName = ?,\n\tlastName = ?\nWHERE\n\tuserId = ? AND\n\tuserPassword = ?");
            $params = array($_POST['firstName'], $_POST['lastName'], $_SESSION['userId'], $sha1CurrentPassword);
            $stmt->execute($params);
            //Record the changes made.
            $userChangesStmt = $Dbc->prepare("INSERT INTO userChanges SET\n\tuserId = ?,\n\toldPrimaryEmail = ?,\n\tnewPrimaryEmail = ?,\n\toldSecondaryEmail = ?,\n\tnewSecondaryEmail = ?,\n\toldPassword = ?,\n\tnewPassword = ?,\n\toldFirstName = ?,\n\tnewFirstName = ?,\n\toldLastName = ?,\n\tnewLastName = ?,\n\tdateChanged = ?");
            $userChangesParams = array($_SESSION['userId'], $currentInfo['primaryEmail'], $_POST['primaryEmail'], $currentInfo['secondaryEmail'], $_POST['secondaryEmail'], $currentInfo['password'], $sha1NewPassword, $currentInfo['firstName'], $_POST['firstName'], $currentInfo['lastName'], $_POST['lastName'], DATETIME);
            $userChangesStmt->execute($userChangesParams);
            $changesListText = '';
            $changesListHtml = '';
            foreach ($changes as $key => $value) {
                $changesListText .= "- {$key}\n";
                $changesListHtml .= "&#8226; {$key}<br>";
            }
            $subject = 'Changes have been made to your ' . THENAMEOFTHESITE . ' account';
            $bodyText = 'The following changes have been made to your ' . THENAMEOFTHESITE . ' account:
' . $changesListText . '
If you did not authorize these changes please <a href="' . LINKSUPPORT . '">contact support</a>. 

This is an automated message. Please do not reply.';
            $bodyHtml = 'The following changes have been made to your account:<br>
' . $changesListHtml . '<br>
If you did not authorize these changes please <a href="' . LINKSUPPORT . '">contact support</a>.';
            $debug->printArray($toAddress, '$toAddress');
            if (email(EMAILDONOTREPLY, $currentInfo['primaryEmail'], $subject, $bodyHtml, $bodyText)) {
                $Dbc->commit();
                $message .= 'Saved My Information';
                $success = MODE == 'saveMyInformation' ? true : $success;
                if (!empty($toAddress)) {
                    foreach ($toAddress as $value) {
                        email('donotreply@' . DOMAIN, $value, $subject, $bodyHtml, $bodyText);
                    }
                }
            } else {
                throw new Adrlist_CustomException('', 'There was a problem trying to send an email.');
            }
        }
    } catch (Adrlist_CustomException $e) {
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
    }
    if (MODE == 'saveMyInformation') {
        returnData();
    } else {
        return $output;
    }
}
예제 #8
0
function supportSend()
{
    //Disabled the recaptcha 2014-03-09.
    global $debug, $message, $success, $Dbc, $returnThis;
    $output = '';
    try {
        $emailValidate = emailValidate($_POST['supportEmail']);
        if (empty($_POST['supportName'])) {
            throw new Adrlist_CustomException('', '$_POST[\'supportName\'] is empty.');
        } elseif ($emailValidate === false) {
            throw new Adrlist_CustomException('', '$_POST[\'supportEmail\'] is not valid.');
        } elseif (empty($_POST['supportMessage'])) {
            throw new Adrlist_CustomException('', '$_POST[\'supportMessage\'] is empty.');
        }
        /*elseif(empty($_POST['recaptcha_challenge_field'])){
        			throw new Adrlist_CustomException('','$_POST[\'recaptcha_challenge_field\'] is empty.');
        		}elseif(empty($_POST['recaptcha_response_field'])){
        			throw new Adrlist_CustomException('','$_POST[\'recaptcha_response_field\'] is empty.');
        		}
        		$resp = recaptcha_check_answer(RECAPTCHAPRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
        		if($resp->is_valid || LOCAL){
        			$debug->add('The recaptcha response is valid.');*/
        //See if the user has an account.
        $accountCheckStmt = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tprimaryEmail = ? OR\n\tsecondaryEmail = ?");
        $accountCheckStmt->execute(array($_POST['supportEmail'], $_POST['supportEmail']));
        if ($row = $accountCheckStmt->fetch(PDO::FETCH_ASSOC)) {
            //Add the question to the user's support section.
            $newMessage = new Adrlist_MessageCenter();
            $message .= 'Thank you for contacting us!<br>
<br>
Your message has been received. A response will be sent to the message center.';
            $newMessage->newMessage($row['userId'], 1, 'A message sent from the contact page', $_POST['supportMessage']);
        } else {
            //Send the message.
            $subject = $_POST['supportName'] . ' sent a message to support at ' . THENAMEOFTHESITE . '.';
            $bodyText = 'From: ' . $_POST['supportName'] . ' (' . $_POST['supportEmail'] . ')
Sent on: ' . Adrlist_Time::utcToLocal(false, false)->format('F d, Y H:i:s') . '.';
            $bodyHtml = 'From: ' . $_POST['supportName'] . ' (' . $_POST['supportEmail'] . ')<br>
Sent on: ' . Adrlist_Time::utcToLocal(false, false)->format('F d, Y H:i:s') . '<br>
Mesage:<br>
' . nl2br($_POST['supportMessage']);
            //$fromAddress,$toAddress,$subject,$bodyHtml,$bodyText,$senderAddress = NULL,$returnAddress = NULL
            if (email($_POST['supportEmail'], EMAILSUPPORT, $subject, $bodyHtml, $bodyText, $_POST['supportEmail'])) {
                $message .= 'Thank you for contacting us! We will get back to you as soon as we can.';
                $success = true;
                $debug->add('used the function email(' . $_POST['supportEmail'] . ',' . EMAILSUPPORT . ',$subject,$bodyHtml,$bodyText,' . EMAILSUPPORT);
                $debug->add('$subject:' . $subject . '<br>
$bodyHtml:' . $bodyHtml . '<br>
$bodyText:' . $bodyText);
            } else {
                throw new Adrlist_CustomException('', 'There was a problem trying to send an email.');
            }
        }
        /*}else{
        			//Set the error code so that we can display it.
        			$message .= 'The reCAPTCHA wasn\'t entered correctly. Please enter the new reCAPTCHA.';
        			$debug->add('reCAPTCHA said: ' . $resp->error);
        		}*/
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
    }
    if (MODE == 'supportSend') {
        returnData();
    }
}
예제 #9
0
function createNewUser()
{
    /*
    A new user has entered their information. We will create their account.
    */
    global $debug, $message, $success, $Dbc, $returnThis;
    $output = '';
    try {
        if (empty($_POST['firstName'])) {
            throw new Adrlist_CustomException('', '$_POST[\'lastName\'] is empty.');
        } elseif (empty($_POST['lastName'])) {
            throw new Adrlist_CustomException('', '$_POST[\'lastName\'] is empty.');
        } elseif (empty($_POST['email'])) {
            throw new Adrlist_CustomException('', 'email is empty.');
        } elseif (!emailValidate($_POST['email'])) {
            throw new Adrlist_CustomException('', 'Email address is not valid.');
        } elseif (!passwordValidate($_POST['password'])) {
            throw new Adrlist_CustomException('', '$_POST[\'password\'] is not valid.');
        } elseif (empty($_POST['password'])) {
            throw new Adrlist_CustomException('', '$_POST[\'password\'] is empty.');
        } elseif (empty($_POST['timeZone'])) {
            throw new Adrlist_CustomException('', '$_POST[\'timeZone\'] is empty.');
        }
        /*elseif(empty($_POST['recaptcha_challenge_field'])){
        			throw new Adrlist_CustomException('','$_POST[\'recaptcha_challenge_field\'] is empty.');
        		}elseif(empty($_POST['recaptcha_response_field'])){
        			throw new Adrlist_CustomException('','$_POST[\'recaptcha_response_field\'] is empty.');
        		}*/
        destroySession();
        $_POST['email'] = trim($_POST['email']);
        $passEncoded = sha1(trim($_POST['password']));
        $_POST['firstName'] = trim($_POST['firstName']);
        $_POST['lastName'] = trim($_POST['lastName']);
        $rememberMeCode = sha1($_POST['email']);
        $invitationCode = isset($_POST['invitationCode']) ? trim($_POST['invitationCode']) : '';
        /*
        $resp = recaptcha_check_answer(RECAPTCHAPRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
        if(!$resp->is_valid && !LOCAL){
        	throw new Adrlist_CustomException('The reCAPTCHA wasn\'t entered correctly. Please enter the new reCAPTCHA.','reCAPTCHA said: ' . $resp->error . '.');
        }
        $debug->add('The recaptcha response is valid.');
        */
        $Dbc->beginTransaction();
        //See if this email address is already in use.
        $getUserIdQuery = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tprimaryEmail = ?");
        $getUserIdQuery->execute(array($_POST['email']));
        $row = $getUserIdQuery->fetch(PDO::FETCH_ASSOC);
        if (empty($row['userId'])) {
            //There are no users with the email address, so insert the user record.
            $insertUserQuery = $Dbc->prepare("INSERT INTO\n\tusers\nSET\n\tprimaryEmail = ?,\n\tuserPassword = ?,\n\tfirstName = ?,\n\tlastName = ?,\n\tdateAdded = ?");
            $insertUserQuery->execute(array($_POST['email'], $passEncoded, $_POST['firstName'], $_POST['lastName'], DATETIME));
            $userId = $Dbc->lastInsertId();
            if (!empty($invitationCode)) {
                $debug->add('$invitationCode: ' . "{$invitationCode}");
                //The user is responding to an invitation. Verify the invitation code matches the email.
                $verifyInviteQuery = $Dbc->prepare("SELECT\n\temail as 'email'\nFROM\n\tinvitations\nWHERE\n\tinvitationCode = ? AND\n\temail = ? AND\n\trespondDate IS NULL");
                $verifyInviteQuery->execute(array($invitationCode, $_POST['email']));
                $verifyInvite = $verifyInviteQuery->fetch(PDO::FETCH_ASSOC);
                if ($verifyInvite['email'] === '' || $verifyInvite['email'] === NULL) {
                    //The invitation code wasn't found or didn't match the email address. The user will still be created.
                    $message .= '<div class="red" style="padding:10px;">An invitation wasn\'t found. It may have been cancelled by the person who made the invitation.</div>';
                } else {
                    $invitedEmail = true;
                    //The invitation code and email have been verified. Look for more invitations.
                    $invitationsQuery = $Dbc->prepare("SELECT\n\tinvitationId AS 'invitationId',\n\tfolderId AS 'folderId',\n\tfolderRoleId AS 'folderRoleId',\n\tlistId AS 'listId',\n\tlistRoleId AS 'listRoleId',\n\tsenderId AS 'senderId'\nFROM\n\tinvitations\nWHERE\n\temail = ? AND\n\trespondDate IS NULL");
                    $invitationsQuery->execute(array($_POST['email']));
                    $folderArray = array();
                    //A nested associative array: requestingUserId => array(folderId,userFolderRoleId).
                    //Insert the new user's roles from the invitation(s).
                    while ($invitationsRow = $invitationsQuery->fetch(PDO::FETCH_ASSOC)) {
                        if (!empty($invitationsRow['folderId']) && !empty($invitationsRow['folderRoleId'])) {
                            //Add the folder to an array for creating list roles.
                            $folderArray[$invitationsRow['senderId']][$invitationsRow['folderId']] = $invitationsRow['folderRoleId'];
                            //Insert the folder role.
                            $insertFolderRole = $Dbc->prepare("INSERT INTO\n\tuserFolderSettings\nSET\n\tfolderId = ?,\n\tuserId = ?,\n\tfolderRoleId = ?,\n\tdateAdded = ?");
                            $insertFolderRole->execute(array($invitationsRow['folderId'], $userId, $invitationsRow['folderRoleId'], DATETIME));
                        }
                        if (!empty($invitationsRow['listId']) && !empty($invitationsRow['listRoleId'])) {
                            //Insert the list role.
                            $insertListRole = $Dbc->prepare("INSERT INTO\n\tuserListSettings\nSET\n\tlistId = ?,\n\tuserId = ?,\n\tlistRoleId = ?,\n\tdateAdded = ?");
                            $insertListRole->execute(array($invitationsRow['listId'], $userId, $invitationsRow['listRoleId'], DATETIME));
                        }
                        //Update the invitation respond date.
                        $respondDateQuery = $Dbc->prepare("UPDATE\n\tinvitations\nSET\n\trespondDate = ?\nWHERE\n\tinvitationId = ?");
                        $respondDateQuery->execute(array(DATETIME, $invitationsRow['invitationId']));
                    }
                    //Insert roles for each list in the sharedFolders array.
                    if (!empty($folderArray) && is_array($folderArray)) {
                        $debug->printArray($folderArray, '$folderArray');
                        foreach ($folderArray as $requestingUserId => $sharedFoldersArray) {
                            distributeRoles($requestingUserId, $userId, $sharedFoldersArray, true);
                        }
                    } elseif (!empty($folderArray)) {
                        error(__LINE__, '', '$sharedFoldersArray must be an associative array near line ' . __LINE__ . '.<br>');
                    }
                }
            }
            //Create the user's default userSettings.
            $insertUserSettingsQuery = $Dbc->prepare("INSERT\nINTO\n\tuserSiteSettings\nSET\n\tuserId = ?,\n\trememberMeCode = ?,\n\ttimeZone = ?,\n\tsiteRoleId = ?");
            $insertUserSettingsQuery->execute(array($userId, $rememberMeCode, $_POST['timeZone'], 1));
            //There is no default billing for a user. The user can select a plan, or there may be a promotion when starting an account.
            //We must insert a userBillingAction first.
            $userBillingActionStmt = $Dbc->prepare("INSERT\nINTO\n\tuserBillingActions\nSET\n\tuserId = ?,\n\tbillingOfferId = ?,\n\tbillingActionId = ?,\n\tvendorId = ?,\n\tbillingDatetime = ?");
            $userBillingActionStmt->execute(array($userId, 1, 10, 3, DATETIME));
            $userBillingActionId = $Dbc->lastInsertId();
            $billingQuery = $Dbc->prepare("INSERT\nINTO\n\tuserBilling\nSET\n\tuserId = ?,\n\tbillingOfferId = ?,\n\tuserBillingActionId = ?,\n\tdateAdded = ?");
            $billingQuery->execute(array($userId, 1, $userBillingActionId, DATETIME));
            //Send a welcome email.
            $subject = 'Welcome to ' . THENAMEOFTHESITE . '!';
            $body = '<table width="100%" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="left"><font face="' . FONT . '" size="' . SIZE5 . '"><b>Welcome to ' . THENAMEOFTHESITE . '!</b><br>
&nbsp;</font></td>
	</tr>
	<tr>
		<td align="left"><font face="' . FONT . '" size="' . SIZE3 . '"></font>Create your first ADR list by logging in: <a href="' . LINKLOGIN . '/?email=' . $_POST['email'] . '">' . LINKLOGIN . '</a>.<br>
			<div>&nbsp;</div>
			<div>&nbsp;</div>
			<div>&nbsp;</div>
		</td>
	</tr>
</table>';
            $textBody = "Welcome to " . THENAMEOFTHESITE . ".\nCreate your first list by logging in: https://" . DOMAIN . "/login?email=" . $_POST['email'] . "\nThis is an automated message. Please do not reply.";
            email(EMAILDONOTREPLY, $_POST['email'], $subject, $body, $textBody);
            setcookie(REMEMBERME, $rememberMeCode, time() + 60 * 60 * 24 * 365, COOKIEPATH, COOKIEDOMAIN, false);
            $Dbc->commit();
            $success = true;
            $returnThis['pass'] = $_POST['password'];
        } else {
            $message .= "The email address you entered is already in use. Please choose another or try logging in.<br>";
            $debug->add('The email address belongs to userId: ' . $row['userId'] . '.');
        }
    } catch (Adrlist_CustomException $e) {
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
        if (MODE == 'createNewUser') {
            returnData();
        }
    }
    returnData();
}
예제 #10
0
    return $orderCost;
}
if (empty($_POST) && isset($_COOKIE['products']) && !empty($_COOKIE['products'])) {
    $orderCost = orderCost($connection);
    echo "<div class=order-cost> Общая стоимость заказа: <span>{$orderCost}</span> рублей</div>";
    include_once "templates/_create-order-form.php";
} elseif (empty($_COOKIE['products'])) {
    echo "Ваша корзина пуста";
}
if (!empty($_POST) && isset($_COOKIE['products']) && !empty($_COOKIE['products'])) {
    include_once "order_data-validate.php";
    // Data sanitising and validation
    $errors = [];
    $name = nameValidate($errors, $_POST['name']);
    $address = addressValidate($errors, $_POST['address']);
    $email = emailValidate($errors, $_POST['email']);
    $addition = "";
    if (v::string()->notEmpty()->validate(filter_var(trim($_POST['addition']), FILTER_SANITIZE_STRING))) {
        $addition = filter_var(trim($_POST['addition']), FILTER_SANITIZE_STRING);
    }
    if (!v::arr()->notEmpty()->validate($errors)) {
        // No errors after form validation
        $order = new \App\DB\OrdersProducts($connection, $name, $address, $email, $addition);
        foreach ($_COOKIE['products'] as $id => $value) {
            setcookie("products[{$id}]", "", time() - 3600, "/");
        }
        echo "<p class='order-created'>Поздравляем! Заказ оформлен</p>";
        echo "<a href=" . \App\Utilities\Options::URL . "../catalog class='adm-btn order'>В каталог</a>";
        header('Refresh:0 url=/');
    } else {
        echo "<div class=order-cost> Общая стоимость заказа: <span>{$orderCost}</span> рублей</div>";
예제 #11
0
function transferListStep2()
{
    /*
    This function behaves very much like shareList(). The user enters the email address of the intended recipient and an email is sent. Upon acceptance the list ownership is changed. This does not affect the list roles of non-owners. The list will be moved out of any containing folders.
    */
    global $debug, $message, $success, $Dbc, $returnThis;
    $output = '';
    try {
        $emailValidate = emailValidate($_POST['intendedEmail']);
        if (empty($_POST['listId'])) {
            throw new Adrlist_CustomException('', '$_POST[\'listId\'] is empty.');
        } elseif ($emailValidate === false) {
            throw new Adrlist_CustomException('The email address you entered is not valid.', '$_POST[\'intendedEmailAddress\'] is not valid.');
        } elseif (empty($_POST['intendedEmail'])) {
            throw new Adrlist_CustomException('', '$_POST[\'intendedEmail\'] is empty.');
        } elseif (empty($_POST['intendedEmailRetype'])) {
            throw new Adrlist_CustomException('', '$_POST[\'intendedEmailRetype\'] is empty.');
        } elseif ($_POST['intendedEmail'] != $_POST['intendedEmailRetype']) {
            throw new Adrlist_CustomException('The email addresses don\'t match.', '$_POST[\'intendedEmail\'] != $_POST[\'intendedEmailRetype\']');
        } elseif ($_POST['intendedEmail'] == $_SESSION['primaryEmail'] || $_POST['intendedEmail'] == $_SESSION['secondaryEmail']) {
            throw new Adrlist_CustomException('The email address you entered is linked to your account.', '$_POST[\'intendedEmail\'] == user\'s email.');
        }
        $Dbc->beginTransaction();
        //Check for a pending transfer.
        $pendingTransferStmt = $Dbc->prepare("SELECT\n\ttlId AS 'tlId'\nFROM\n\ttransferList\nWHERE\n\tlistId = ?");
        $pendingTransferStmt->execute(array($_POST['listId']));
        $pendingTransferRow = $pendingTransferStmt->fetch(PDO::FETCH_ASSOC);
        if (empty($pendingTransferRow['tlId'])) {
            //Verify the user has a sufficient role to transfer the list.
            $listInfo = getListInfo($_SESSION['userId'], $_POST['listId']);
            $debug->printArray($listInfo, '$listInfo');
            if ($listInfo === false || $listInfo['listRoleId'] < 4) {
                $message .= 'Your role does not allow you to transfer this list.<br>';
            } else {
                //Insert a record of transfer.
                $transferListCode = sha1($_POST['intendedEmail'] . time());
                $insertTransferStmt = $Dbc->prepare("INSERT INTO\n\ttransferList\nSET\n\tintendedEmail = ?,\n\ttransferListCode = ?,\n\tlistId = ?,\n\tsenderId = ?,\n\tsentDate = ?");
                $insertTransferParams = array($_POST['intendedEmail'], $transferListCode, $_POST['listId'], $_SESSION['userId'], DATETIME);
                $insertTransferStmt->execute($insertTransferParams);
                //Email the recipient.
                $subject = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has transferred an ADR list to you at ' . THENAMEOFTHESITE;
                $bodyText = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has transferred the ADR list "' . $listInfo['listName'] . '" to you at ' . THENAMEOFTHESITE . '. Log in to your account to view this list: ' . LINKLOGIN . '
';
                $bodyHtml = '
<table width="100%" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE3 . '">' . $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has transferred the ADR list "' . $listInfo['listName'] . '" to you at ' . THENAMEOFTHESITE . '. Log in to your account to view this list: <a href="' . LINKLOGIN . '">' . LINKLOGIN . '</a></td>
	</tr>
</table>		
';
                if (email(EMAILDONOTREPLY, $_POST['intendedEmail'], $subject, $bodyHtml, $bodyText)) {
                    $message .= 'The list "' . $listInfo['listName'] . '" will be transferred to the user at ' . $_POST['intendedEmail'] . '.';
                    if (MODE == 'transferListStep2') {
                        $success = true;
                    }
                    $Dbc->commit();
                } else {
                    $Dbc->rollback();
                    error(__LINE__, 'We ran into trouble trying to send an email to the user. Please verify the email address and try sharing this list again.');
                }
                //Email the sender.
                $subject = 'You have transferred an ADR list at' . THENAMEOFTHESITE;
                $bodyText = 'You transferred the ADR list "' . $listInfo['listName'] . '" to the user at ' . $_POST['intendedEmail'] . ' at ' . THENAMEOFTHESITE . '. Log in to your account to view this list: ' . LINKLOGIN . '
';
                $bodyHtml = '<table width="100%" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE3 . '">You transferred the ADR list "' . $listInfo['listName'] . '" to the user at ' . $_POST['intendedEmail'] . ' at ' . THENAMEOFTHESITE . '. Log in to your account to view this list: <a href="' . LINKLOGIN . '">' . LINKLOGIN . '</a></td>
	</tr>
</table>
';
                email($_SESSION['primaryEmail'], $_SESSION['primaryEmail'], $subject, $bodyHtml, $bodyText);
            }
        } else {
            $message .= 'There is already a transfer pending for this list.';
        }
    } catch (Adrlist_CustomException $e) {
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
    }
    if (MODE == 'transferListStep2') {
        returnData();
    }
}
예제 #12
0
function updateUserInfo()
{
    global $debug, $message, $success;
    $output = '';
    if (isset($_POST['userId']) && isset($_POST['firstName']) && strlen($_POST['firstName']) <= 25 && isset($_POST['lastName']) && strlen($_POST['lastName']) <= 25 && isset($_POST['email'])) {
        $userId = intval($_POST['userId']);
        $firstName = trim($_POST['firstName']);
        $lastName = trim($_POST['lastName']);
        $email = trim($_POST['email']);
        if (emailValidate($email)) {
            //Check to see if the email address is being used by another user.
            $emailCheckQuery = "SELECT\n\tCONCAT_WS(' ', users.firstName, users.lastName) AS 'name',\n\tusers.primaryEmail AS 'primaryEmail'\nFROM\n\tusers\nWHERE\n\tusers.primaryEmail = '{$email}' AND\n\tusers.userId <> '{$userId}'";
            if ($result = mysql_query($emailCheckQuery)) {
                if (mysql_affected_rows() == 0) {
                    pdoError(__LINE__, $emailCheckQuery, '$emailCheckQuery', 1);
                    $updateUserInfoQuery = "UPDATE\n\tusers\nSET\n\tfirstName = '" . $firstName . "',\n\tlastName = '" . $lastName . "',\n\tprimaryEmail = '" . $email . "'\nWHERE\n\tuserId = '{$userId}'";
                    if (mysql_query($updateUserInfoQuery)) {
                        if (mysql_affected_rows() == 0) {
                            pdoError(__LINE__, $updateUserInfoQuery, '$updateUserInfoQuery', 1);
                        }
                        $success = true;
                        $message .= 'Updated';
                        $returnThis['returnCode'] = buildUserInfo();
                    } else {
                        error(__LINE__);
                        pdoError(__LINE__, $updateUserInfoQuery, '$updateUserInfoQuery');
                    }
                } else {
                    while ($row = mysql_fetch_assoc($result)) {
                        $message .= "That email address is already being used by " . $row['name'] . " . Please enter a another. ";
                    }
                }
            } else {
                error(__LINE__);
                pdoError(__LINE__, $emailCheckQuery, '$emailCheckQuery');
            }
        } else {
            $message .= 'Please enter a valid email address. ';
        }
    } elseif (!isset($_POST['userId'])) {
        $message .= 'userId is empty. ';
    } elseif (!isset($_POST['firstName'])) {
        $message .= 'Please enter a first name. ';
    } elseif (strlen($_POST['firstName']) > 25) {
        $message .= 'The first name must be 25 characters or less. ';
    } elseif (!isset($_POST['lastName'])) {
        $message .= 'Please enter a last name. ';
    } elseif (strlen($_POST['lastName']) > 25) {
        $message .= 'The last name must be 25 characters or less. ';
    } elseif (!isset($_POST['email'])) {
        $message .= 'Please enter an email address. ';
    } else {
        error(__LINE__);
        $debug->add('Something else is wrong.');
    }
    returnData();
}
예제 #13
0
function resetPasswordStep1()
{
    global $debug, $message, $success, $Dbc, $returnThis;
    $output = '';
    try {
        if (empty($_POST['email'])) {
            throw new Adrlist_CustomException('', '$_POST[\'email\'] is empty.');
        }
        $_POST['email'] = trim($_POST['email']);
        $emailValidate = emailValidate($_POST['email']);
        if ($emailValidate !== true) {
            throw new Adrlist_CustomException('', '$_POST[\'email\'] is not valid.');
        }
        $Dbc->beginTransaction();
        //See if a user with the email exists before sending.
        $emailCheckQuery = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tprimaryEmail = ?");
        $debug->add('$_POST[\'email\']: ' . $_POST['email'] . '.');
        $emailCheckQuery->execute(array($_POST['email']));
        $row = $emailCheckQuery->fetch(PDO::FETCH_ASSOC);
        if (empty($row['userId'])) {
            $message .= 'Please <a href="' . LINKSUPPORT . '">contact support</a> for help with accessing your account.<br>';
        } else {
            $resetCode = sha1($_POST['email'] . DATETIME);
            $insertQuery = $Dbc->prepare("INSERT INTO\n\tforgotPassword\nSET\n\tuserId = ?,\n\temailEntered = ?,\n\tresetCode = ?,\n\trequestMade = ?,\n\tREMOTE_ADDR = ?,\n\tHTTP_X_FORWARDED_FOR = ?");
            $httpX = empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? '' : $_SERVER['HTTP_X_FORWARDED_FOR'];
            $insertQuery->execute(array($row['userId'], $_POST['email'], $resetCode, DATETIME, $_SERVER['REMOTE_ADDR'], $httpX));
            $resetLink = LINKFORGOTPASSWORD . '/?resetCode=' . $resetCode;
            //This will build https://adrlist.....
            $subject = 'Reset password at ' . THENAMEOFTHESITE;
            $body = '<table width="100%" cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE4 . '"><b>Please follow the link below to reset your password:</b></font></td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE4 . '"><a href="' . $resetLink . '">' . $resetLink . '</a>
			</font>
			<div>&nbsp;</div>
			<div>&nbsp;</div>
			<div>&nbsp;</div>
		</td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE2 . '">The request was sent from ' . $_SERVER['REMOTE_ADDR'] . '. If you did not request to reset your password, please ignore this message.</font></td>
	</tr>
</table>';
            $textBody = "Please follow this link to reset your password: "******"\nIf you did not request to reset your password, please ignore this message.";
            $insertId = $Dbc->lastInsertId();
            if (!empty($insertId) && email(EMAILDONOTREPLY, $_POST['email'], $subject, $body, $textBody) === true) {
                $Dbc->commit();
                $success = true;
                $message .= 'An email has been sent to ' . $_POST['email'] . ' with instructions on how to reset your password.
<div class="red textCenter" style="margin:1em 0">Didn\'t get an email? Be sure to check your spam folder.</div>';
                $returnThis['buildReset'] = buildReset();
            } else {
                $Dbc->rollback();
                error(__LINE__, false, 'Could not add the record on line ' . __LINE__ . ' in forgotPasswordMethods.php.<br>');
            }
        }
    } catch (Adrlist_CustomException $e) {
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
        if (MODE == 'resetPasswordStep1') {
            returnData();
        }
    }
    if (MODE == 'resetPasswordStep1') {
        returnData();
    }
}
$email = $_REQUEST['email'];
$admissionDate = $_REQUEST['admission-date'];
$user = $_REQUEST['user'];
if (isset($_REQUEST['sex'])) {
    $sex = $_REQUEST['sex'];
} else {
    $sex = "";
}
$pass = $_REQUEST['pass'];
$passConfirm = $_REQUEST['pass-confirm'];
$securityAnswer = $_REQUEST['security-answer'];
$strconn = "host=localhost port=5432 dbname=gitbook user=postgres password=12345";
$conn = pg_connect($strconn);
$array_data[] = nameValidate($name);
$array_data[] = lastNameValidate($lastName);
$array_data[] = emailValidate($email, $conn);
$array_data[] = admissionDateValidate($admissionDate);
$array_data[] = userValidate($user, $conn);
$array_data[] = sexValidate($sex);
$array_data[] = passValidate($pass);
$array_data[] = passConfirmValidate($pass, $passConfirm);
$array_data[] = securityAnswerValidate($securityAnswer);
echo json_encode($array_data);
function nameValidate($name)
{
    if (strlen($name) >= 3) {
        return array('state' => "Correcto", 'box' => "#box-name");
    } else {
        return array('state' => "Incorrecto", 'box' => "#box-name", 'errorBox' => "#error-name", 'error' => "Debe tener al menos 3 caracteres.");
    }
}