function saveViewOptions()
{
    //Set the view options.
    global $debug, $message, $success, $Dbc, $returnThis;
    try {
        $userListDefaults = getDefaultListSettings();
        $debug->printArray($userListDefaults, '$userListDefaults');
        if ($userListDefaults === false) {
            throw new Adrlist_CustomException('', "Could not get the user's default list settings.");
        }
        $tempArray = array('defaultViewReels' => 'viewAll', 'defaultViewCharacters' => '');
        $userListDefaults = array_merge($userListDefaults, $tempArray);
        $resetOffset = false;
        //We will build the update statement in parts.
        $updateListSettingsStmt = "UPDATE\n\tuserListSettings\nSET\n\t";
        $updateListSettingsParams = array();
        //Order by statement. Order by must always be 78 characters long using a combination of the string options.
        if (!empty($_POST['orderBy'])) {
            $updateListSettingsStmt .= "orderBy = ?,";
            if (strlen($_POST['orderBy']) == 86) {
                //The user has used the advanced view options. A complete string of order by options should have been submitted.
                $updateListSettingsParams[] = $_POST['orderBy'];
            } else {
                $updateListSettingsParams[] = $userListDefaults['defaultOrderBy'];
                $debug->add('Set order by to default.');
            }
        }
        //Order direction statement.
        if (!empty($_POST['orderDirection'])) {
            $updateListSettingsStmt .= "orderDirection = ?,";
            //The user has used the advanced view options.
            if ($_POST['orderDirection'] == 'ASC' || $_POST['orderDirection'] == 'DESC') {
                $updateListSettingsParams[] = $_POST['orderDirection'];
            } else {
                $updateListSettingsParams[] = $userListDefaults['defaultOrderDirection'];
                $debug->add('Set order direction to default.');
            }
        }
        //View reels statement. Default is 'viewAll' and implies view all reels.
        $updateListSettingsStmt .= "viewReels = ?,";
        if (isset($_POST['viewReels'])) {
            $updateListSettingsParams[] = $_POST['viewReels'];
            $resetOffset = $_SESSION['viewReels'] == $_POST['viewReels'] ? false : true;
            //Reset the offset if view reels has changed.
        } else {
            $updateListSettingsParams[] = $userListDefaults['defaultViewReels'];
            $debug->add('Set view reels to default.');
            $resetOffset = true;
        }
        //View characters statement. An empty value '' implies view all characters.
        $updateListSettingsStmt .= "viewCharacters = ?,";
        if (isset($_POST['viewCharacters'])) {
            $updateListSettingsParams[] = $_POST['viewCharacters'];
        } else {
            $_POST['viewCharacters'] = '';
            $updateListSettingsParams[] = $userListDefaults['defaultViewCharacters'];
        }
        $resetOffset = $_SESSION['viewCharacters'] == $_POST['viewCharacters'] ? false : true;
        //Reset the offset if view characters has changed.
        //The following options are in quotes because jquery is passing values via POST, which does not respect data types (boolean vs string vs integer). Here we check for 'true' (string) and not true (boolean). Furthermore, PHP is not strictly typed, so it equates any string  or 1 as true.
        //Show character colors stmt.
        $updateListSettingsStmt .= "showCharacterColors = ?,";
        if (isset($_POST['showCharacterColors'])) {
            $updateListSettingsParams[] = $_POST['showCharacterColors'] === 'true' ? 1 : 0;
        } else {
            $_POST['showCharacterColors'] = '';
            $updateListSettingsParams[] = $userListDefaults['defaultShowCharacterColors'];
        }
        //Show completed lines stmt.
        $updateListSettingsStmt .= "showCompletedLines = ?,";
        if (isset($_POST['showCompletedLines'])) {
            $updateListSettingsParams[] = $_POST['showCompletedLines'] === 'true' ? 1 : 0;
        } else {
            $_POST['showCompletedLines'] = '';
            $updateListSettingsParams[] = $userListDefaults['defaultShowCompletedLines'];
        }
        //Show deleted lines stmt.
        $updateListSettingsStmt .= "showDeletedLines = ?";
        if (isset($_POST['showDeletedLines'])) {
            $updateListSettingsParams[] = $_POST['showDeletedLines'] === 'true' ? 1 : 0;
        } else {
            $_POST['showDeletedLines'] = '';
            $updateListSettingsParams[] = $userListDefaults['defaultShowDeletedLines'];
        }
        $debug->add('$_POST[\'showCharacterColors\']: ' . $_POST['showCharacterColors'] . '<br>
$_POST[\'showCompletedLines\']: ' . $_POST['showCompletedLines'] . '<br>
$_POST[\'showDeletedLines\']: ' . $_POST['showDeletedLines'] . '.');
        array_push($updateListSettingsParams, $_SESSION['userId'], $_SESSION['listId']);
        $updateListSettingsStmt .= "\nWHERE\n\tuserId = ? AND\n\tlistId = ?";
        $debug->add('$updateListSettingsStmt: ' . "{$updateListSettingsStmt}.");
        $debug->printArray($updateListSettingsParams, '$updateListSettingsParams');
        $updateListSettingsStmt = $Dbc->prepare($updateListSettingsStmt);
        $updateListSettingsStmt->execute($updateListSettingsParams);
        initializeList();
        $_SESSION['offset'] = 0;
        if (MODE == 'saveViewOptions') {
            $success = true;
            //It's okay if no lines were updated by this query. The user may have hit the default view button and not changed any view options.
            $returnThis['buildLines'] = buildLines();
            $message .= 'Saved view options.';
        }
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
    }
    if (MODE == 'saveViewOptions') {
        returnData();
    }
}
Example #2
0
function shareListStep2()
{
    //Share a list = send an invitation.
    global $debug, $message, $success, $Dbc, $returnThis;
    $output = '';
    try {
        if (empty($_POST['listId'])) {
            throw new Adrlist_CustomException('', '$_POST[\'listId\'] is empty.');
        } elseif (empty($_POST['email'])) {
            throw new Adrlist_CustomException('', '$_POST[\'email\'] is empty.');
        } elseif (emailValidate($_POST['email']) === false) {
            throw new Adrlist_CustomException('The email address your entered is not valid.', '$_POST[\'email\'] failed the emailValidate() test.');
        } elseif ($_POST['email'] == $_SESSION['primaryEmail']) {
            throw new Adrlist_CustomException('Why are your trying to share the folder with yourself?', '$_POST[\'email\'] == $_SESSION[\'primaryEmail\'].');
        } elseif ($_POST['email'] == $_SESSION['secondaryEmail']) {
            throw new Adrlist_CustomException('The email address you entered is linked to your account?', '$_POST[\'email\'] == $_SESSION[\'secondaryEmail\'].');
        }
        $_POST['email'] = trim($_POST['email']);
        $Dbc->beginTransaction();
        //Get the list's information.
        $currentUserListInfo = getListInfo($_SESSION['userId'], $_POST['listId']);
        //Verify the current user has an appropriate listRoleId to add users - Manager (3) or Owner (4).
        if ($currentUserListInfo === false || $currentUserListInfo['listRoleId'] < 3) {
            throw new Adrlist_CustomException("Your role does not allow you to add users to this list.", '');
        }
        //Verify the current user has a folderRoleId of at least Member (1). This is because a user may be a manager of a list, but not of it's folder.
        if ($currentUserListInfo['folderRoleId'] === 0) {
            //The requesting user is implicitly denied access to a folder.
            throw new Adrlist_CustomException("Your role does not allow you to add members to this folder.", '');
        }
        //The current user has access to the folder, or the list is not in a folder.
        $folderRoleId = $currentUserListInfo['folderId'] ? 1 : NULL;
        //If a folder exists, the default folderRoleId is Member (1), otherwise NULL.
        //Check if the recipient has an account.
        $userCheckStmt = $Dbc->prepare("SELECT\n\tuserId AS 'userId'\nFROM\n\tusers\nWHERE\n\tprimaryEmail = ? OR\n\tsecondaryEmail = ?");
        $userCheckStmt->execute(array($_POST['email'], $_POST['email']));
        $userCheckRow = $userCheckStmt->fetch(PDO::FETCH_ASSOC);
        $subject = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared a list with you at ' . THENAMEOFTHESITE;
        if (empty($userCheckRow['userId'])) {
            //The recipient does not have an account. See if they already have an invitation to this list.
            $invitationCheckStmt = $Dbc->prepare("SELECT\n\temail AS 'email'\nFROM\n\tinvitations\nWHERE\n\temail = ? AND\n\tlistId = ?");
            $invitationCheckStmt->execute(array($_POST['email'], $_POST['listId']));
            $invitationCheckRow = $invitationCheckStmt->fetch(PDO::FETCH_ASSOC);
            if (!empty($invitationCheckRow['email'])) {
                throw new Adrlist_CustomException('This list has already been shared with that user.', '');
            }
            //The user has no existing invitation to this list. Insert an invitation record.
            $invitationCode = sha1($_POST['email'] . time());
            $insertInvitationStmt = $Dbc->prepare("INSERT INTO\n\tinvitations\nSET\n\temail = ?,\n\tinvitationCode = ?,\n\tfolderId = ?,\n\tfolderRoleId = ?,\n\tlistId = ?,\n\tlistRoleId = ?,\n\tsenderId = ?,\n\tsentDate = ?");
            $insertInvitationStmt->execute(array($_POST['email'], $invitationCode, $currentUserListInfo['folderId'], $folderRoleId, $_POST['listId'], 1, $_SESSION['userId'], DATETIME));
            $bodyText = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared the ADR list "' . $currentUserListInfo['listName'] . '" with you at ' . THENAMEOFTHESITE . '. 
View this list by creating an account: ' . LINKCREATEACCOUNT . '
';
            $bodyHtml = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared the ADR list "' . $currentUserListInfo['listName'] . '" with you at ' . THENAMEOFTHESITE . '. <br>
		<br>
			<a href="' . LINKCREATEACCOUNT . '?invitationCode=' . $invitationCode . '">View this list by creating an account here.</a><br>';
            if (email($_SESSION['primaryEmail'], $_POST['email'], $subject, $bodyHtml, $bodyText)) {
                $message .= 'You shared this list with ' . $_POST['email'] . '.';
                $Dbc->commit();
                if (MODE == 'shareListStep2') {
                    $success = true;
                    $returnThis['buildListUsers'] = buildListUsers();
                }
            } else {
                $Dbc->rollback();
                throw new Adrlist_CustomException('', 'Could not send an email to the user.');
            }
        } else {
            //The recipient has an existing account.
            if ($currentUserListInfo['folderId']) {
                //The list is part of a folder. Check if the recipient has a role for the folder.
                $recipientFolderInfo = getFolderInfo($userCheckRow['userId'], $currentUserListInfo['folderId']);
                $recipientFolderRoleId = $recipientFolderInfo['folderRoleId'];
                if ($recipientFolderRoleId === 0) {
                    $success = false;
                    throw new Adrlist_CustomException('The user you are trying to share this list with has been implicitly denied a role for the containing folder. You must grant the user a minimum folder role of "View" before sharing this list.');
                } elseif (empty($recipientFolderRoleId)) {
                    //The user does not have an existing folder role, so insert one.
                    $insertFolderRole = $Dbc->prepare("INSERT INTO\n\tuserFolderSettings\nSET\n\tfolderId = ?,\n\tuserId = ?,\n\tfolderRoleId = ?,\n\tdateAdded = ?");
                    $insertFolderRole->execute(array($currentUserListInfo['folderId'], $userCheckRow['userId'], 1, DATETIME));
                }
            }
            //See if the recipient has a listRoleId. This is very redundant. The current user should not have been able to share this list if the recipient alreay has a list role.
            $recipientListInfo = getListInfo($userCheckRow['userId'], $_POST['listId']);
            if ($recipientListInfo === false) {
                //The user exists and does not have an existing role, so insert the list role. First, get the user's default list settings.
                $listSettings = getDefaultListSettings($userCheckRow['userId']);
                //Insert a list setting for this list.
                $listSettingsStmt = $Dbc->prepare("INSERT INTO\n\tuserListSettings\nSET\n\tuserId = ?,\n\tlistId = ?,\n\tlistRoleId = ?,\n\tdateAdded = ?,\n\tlimitCount = ?,\n\torderBy = ?,\n\torderDirection = ?,\n\tviewCharacters = ?,\n\tshowCharacterColors = ?");
                $listSettingsStmt->execute(array($userCheckRow['userId'], $_POST['listId'], 1, DATETIME, $listSettings['defaultLimit'], $listSettings['defaultOrderBy'], $listSettings['defaultOrderDirection'], '', $listSettings['defaultShowCharacterColors']));
                $bodyText = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared the ADR list "' . $currentUserListInfo['listName'] . '" with you at ' . THENAMEOFTHESITE . '. Log in to your account to view this list: ' . LINKLOGIN . '
';
                $bodyHtml = $_SESSION['firstName'] . ' ' . $_SESSION['lastName'] . ' has shared the ADR list "' . $currentUserListInfo['listName'] . '" with you at ' . THENAMEOFTHESITE . '.<br>
<br>
Log in to your account to view this list: <a href="' . LINKLOGIN . '">' . LINKLOGIN . '</a><br<br>';
                if (email($_SESSION['primaryEmail'], $_POST['email'], $subject, $bodyHtml, $bodyText)) {
                    $message .= 'You shared this list with the user at ' . $_POST['email'] . '.';
                    $Dbc->commit();
                    if (MODE == 'shareList') {
                        $success = true;
                    }
                } else {
                    $Dbc->rollback();
                    throw new Adrlist_CustomException('We ran into trouble trying to send an email to the user. Please try again<br><br>
 If the problem persists, <a href="' . LINKSUPPORT . '" data-ajax="false">contact support</a>.', '');
                }
            } elseif ($recipientListInfo['listRoleId'] === 0) {
                throw new Adrlist_CustomException('The user you are trying to share this list with has been implicitly denied a role. You cannot share this list with that person.', '');
            } else {
                throw new Adrlist_CustomException('The user already has access to this list.', '');
            }
        }
    } catch (Adrlist_CustomException $e) {
    } catch (PDOException $e) {
        error(__LINE__, '', '<pre>' . $e . '</pre>');
    }
    if (MODE == 'shareListStep2') {
        returnData();
    }
}