function updateData($dbc)
{
    $errors = [];
    if (!empty($_POST)) {
        try {
            $userName = Input::getString('username');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $password = Input::getString('pwd');
            $password = password_hash($password, PASSWORD_DEFAULT);
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $firstName = Input::getString('firstname');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $lastName = Input::getString('lastname');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $email = Input::getString('email');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $zipCode = Input::getNumber('zipcode');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        if (Input::notEmpty('username') && Input::notEmpty('pwd') && Input::notEmpty('firstname') && Input::notEmpty('lastname') && Input::notEmpty('email') && Input::notEmpty('zipcode')) {
            // create new instance of user class
            $user = new User();
            $user->first_name = $firstName;
            $user->last_name = $lastName;
            $user->user_name = $userName;
            $user->email = $email;
            $user->zipcode = $zipCode;
            $user->save();
            $_SESSION['logInMessage'] = "Your profile has been updated.!!!";
            header("Location:index.php");
            die;
        }
    }
    return $errors;
}
Example #2
0
function pageController()
{
    session_start();
    if (!Auth::check()) {
        header('Location: /auth/login');
        exit;
    }
    $username = Auth::user();
    $user = User::findUserByUsername($username);
    $adid = Input::get('id');
    $ad = Ad::find($adid);
    $item_name = $ad->attributes['item_name'];
    $price = $ad->attributes['price'];
    $description = $ad->attributes['description'];
    $image_path = $ad->attributes['image_path'];
    $contact = $ad->attributes['contact'];
    $errors = array();
    if (!empty($_POST)) {
        if (Input::notEmpty('item_name')) {
            $item_name = ValidateAd::getItemName();
        }
        if (Input::notEmpty('price')) {
            $price = ValidateAd::getPrice();
        }
        if (Input::notEmpty('description')) {
            $description = ValidateAd::getDescription();
        }
        if (Input::notEmpty('contact')) {
            $contact = ValidateAd::getContact();
        }
        $errors = ValidateAd::getErrors();
        if (empty($errors)) {
            $ad->attributes['item_name'] = $item_name;
            $ad->attributes['price'] = $price;
            $ad->attributes['description'] = $description;
            $ad->attributes['contact'] = $contact;
            $ad->attributes['image_path'] = $image_path;
            $ad->save();
        }
        if (!Input::notEmpty('delete-id')) {
            //if the form has been submitted
            Ad::delete($ad->attributes['id']);
            header("Location: /ads");
            die;
            //delete the specific ad - going to need to somehow tie in the ad id to the delete buttn for that specific id
        }
    }
    return array('ad' => $ad, 'username' => $username, 'item_name' => $item_name, 'price' => $price, 'description' => $description, 'image_path' => $image_path, 'contact' => $contact);
}
function insertData($dbc)
{
    $errors = [];
    if (!empty($_POST)) {
        try {
            $name = Input::getString('name');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $location = Input::getString('location');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $date = Input::getDate('date_established');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $area = Input::getNumber('area_in_acres');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $description = Input::getString('description');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        if (Input::notEmpty('name') && Input::notEmpty('location')) {
            $userData = 'INSERT INTO national_parks (name, location, date_established, area_in_acres, description)
							VALUES (:name, :location, :date_established, :area_in_acres, :description)';
            $userStmt = $dbc->prepare($userData);
            $userStmt->bindValue(':name', $name, PDO::PARAM_STR);
            $userStmt->bindValue(':location', $location, PDO::PARAM_STR);
            $userStmt->bindValue(':date_established', $date, PDO::PARAM_STR);
            $userStmt->bindValue(':area_in_acres', $area, PDO::PARAM_STR);
            $userStmt->bindValue(':description', $description, PDO::PARAM_STR);
            try {
                $userStmt->execute();
            } catch (Exception $e) {
                $errors[] = $e->getMessage();
                throw new Exception('Error: {$e->getMessage()}');
            }
        }
    }
    return $errors;
}
Example #4
0
function pageController()
{
    session_start();
    $errors = array();
    if (!empty($_POST)) {
        // this block checks to see if an error is going to be thrown
        $username = ValidateUser::getUsername();
        $email = ValidateUser::getEmail();
        $password = ValidateUser::getPassword();
        $passwordmatch = ValidateUser::getPasswordMatch();
        //makes sure that passwords match
        if (isset($password) && isset($passwordmatch)) {
            ValidateUser::getCheckMatch($password, $passwordmatch);
        }
        $errors = ValidateUser::getErrors();
        // add inputed data into database
        if (Input::notEmpty('username') && Input::notEmpty('password') && Input::notEmpty('passwordmatch') && Input::notEmpty('email')) {
            ////does not save any user info yet
            if (empty($errors)) {
                // using models to save information
                $user = new User();
                $user->username = $username;
                $user->email = $email;
                $user->password = $password;
                try {
                    $user->save();
                    $log = new Log();
                    // if someone attempts to create a profile using a username and hypothetically the same password they cant get to the existing users profile
                    if (Auth::attempt($username, $password)) {
                        $log->info('User {$username} logged in.');
                        header('Location: /users');
                        exit;
                    } else {
                        $log->error('User {$username} failed to log in!');
                        $message = 'Please input the proper username and password.';
                    }
                } catch (Exception $e) {
                    $error = $e->getMessage();
                    array_push($errors, $error);
                }
                if (empty($errors)) {
                    $errors = array();
                }
            }
        }
    }
    return array('errors' => $errors);
}
function pageController($dbc)
{
    $errors = array();
    try {
        $item_name = Input::getString('item_name');
    } catch (Exception $e) {
        $error = $e->getMessage();
        array_push($errors, $error);
    }
    try {
        $price = Input::getString('price');
    } catch (Exception $e) {
        array_push($errors, $e->getMessage());
    }
    try {
        $image = Input::getString('image');
    } catch (Exception $e) {
        array_push($errors, $e->getMessage());
    }
    try {
        $description = Input::getString('description');
    } catch (Exception $e) {
        array_push($errors, $e->getMessage());
    }
    if (!empty($_POST)) {
        // add inputed data into datebase
        if (Input::notEmpty('item_name') && Input::notEmpty('price') && Input::notEmpty('image') && Input::notEmpty('description')) {
            // if no errors were thrown runs insert park
            if (empty($errors)) {
                insertListing($dbc, $item_name, $price, $image, $description);
            }
            // elseif (Input::notEmpty('deleted_item_name')) {
            // 	$deleteListing($dbc);
            // }
            // else {
            // 	echo "Please make a valid entry.";
            // }
        }
    }
}
Example #6
0
function pageController()
{
    session_start();
    if (!Auth::check()) {
        header('Location: /auth/login');
        exit;
    }
    $username = Auth::user();
    $user = User::findUserByUsername($username);
    $email = $user->attributes['email'];
    $password = $user->attributes['password'];
    $errors = array();
    if (!empty($_POST)) {
        if (Input::notEmpty('email')) {
            $email = ValidateUser::getEmail();
        }
        if (Input::notEmpty('password')) {
            $password = ValidateUser::getPassword();
        }
        if (Input::notEmpty('passwordmatch')) {
            $passwordmatch = ValidateUser::getPasswordMatch();
        }
        if (Input::notEmpty('passwordmatch') && Input::notEmpty('password')) {
            ValidateUser::getCheckMatch($password, $passwordmatch);
        }
        $errors = ValidateUser::getErrors();
        if (empty($errors)) {
            $user->attributes['username'] = $username;
            $user->attributes['email'] = $email;
            $user->attributes['password'] = $password;
            $user->save();
            header('Location: /users');
            exit;
        }
    }
    return array('username' => $username, 'email' => $email, 'password' => $password);
}
Example #7
0
function pageController()
{
    require_once '../db/db_connect.php';
    // Gets the current session and session id for logged in users.
    session_start();
    $sessionId = session_id();
    if (!isset($_SESSION['Loggedinuser'])) {
        header('location: auth.login.php');
        die;
    }
    $loginstatus = $_SESSION['Loggedinuser'] . " is logged in!";
    // This portion of code gets all the ads' categories in one array.
    // The categories, which are strings (sometimes with multiple categories in it),
    // are then put into the array by themselves. The array is imploded into a string and then exploded into an
    // array again. This allows us to split the strings with multiple categories in them.
    // The php array_unique removes duplicate category values and sort orders them by first letter.
    $arrayCategories = Ad::showJustCategories();
    $justCategories = [];
    foreach ($arrayCategories as $key => $value) {
        array_push($justCategories, $value['categories']);
    }
    $justCategoriesString = implode(', ', $justCategories);
    $justCategoriesArray = explode(', ', $justCategoriesString);
    $justCategoriesArrayUnique = array_unique($justCategoriesArray);
    sort($justCategoriesArrayUnique);
    // Through $_SESSION, gets the logged in user.
    $username = Auth::user();
    // Returns an object of the user's data.
    $user = User::finduserbyusername($username);
    // Uses the 'Create an Ad' form to insert the new values to the table and database.
    function insertAd($dbc, $user)
    {
        // Now calls on the Input class's getString and getDate methods with try catches.
        // Try catch create an array of errors for passing to the user in the HTML.
        $errorArray = [];
        try {
            $method = Input::getString('method', 1, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errMethod'] = $error;
        }
        try {
            $title = Input::getString('title', 1, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errTitle'] = $error;
        }
        try {
            $price = Input::getNumber('price', 0, 25000);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errPrice'] = $error;
        }
        try {
            $location = Input::getString('location', 1, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errLoc'] = $error;
        }
        try {
            $description = Input::getString('description', 1, 500);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errDes'] = $error;
        }
        try {
            $categoriesArray = Input::get('categories', 1, 50);
            $categories = implode(', ', $categoriesArray);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errCats'] = $error;
        }
        // This portion allows for image uploads.
        if (Input::has('title')) {
            if ($_FILES) {
                $uploads_directory = 'img/uploads/';
                $filename = $uploads_directory . basename($_FILES['image_url']['name']);
                if (move_uploaded_file($_FILES['image_url']['tmp_name'], $filename)) {
                    // echo 'The file ' . basename($_FILES['image_url']['name']) . ' has been uploaded.';
                } else {
                    $errorArray['errImage'] = 'Sorry, there was an error uploading your file.';
                }
            }
        }
        // If the $errorArray is not empty, this will return out of the method before binding values and executing below. The $errorArray returns with an array of strings.
        if (!empty($errorArray)) {
            return $errorArray;
        }
        $stmt = $dbc->prepare('INSERT INTO ads (user_id, method, image_url, title, price, location, description, categories) VALUES (:user_id, :method, :image_url, :title, :price, :location, :description, :categories)');
        $stmt->bindValue(':user_id', $user->id, PDO::PARAM_STR);
        $stmt->bindValue(':method', $method, PDO::PARAM_STR);
        $stmt->bindValue(':image_url', $filename, PDO::PARAM_STR);
        $stmt->bindValue(':title', $title, PDO::PARAM_STR);
        $stmt->bindValue(':price', $price, PDO::PARAM_INT);
        $stmt->bindValue(':location', $location, PDO::PARAM_STR);
        $stmt->bindValue(':description', $description, PDO::PARAM_STR);
        $stmt->bindValue(':categories', $categories, PDO::PARAM_STR);
        $stmt->execute();
    }
    // Sets each variable for future use in the following 'if else' logic tree.
    $errorArray = [''];
    $formMethod = '';
    $formTitle = '';
    $formPrice = '';
    $formLoc = '';
    $formDes = '';
    $formCat = [''];
    $yellow = false;
    // If none of these are set in the $_POST, then nothing happens. This is the outer most if.
    // If these are empty, then the else on line 143 is tripped. Inner if/else on lines 130 and 143.
    // If these have values, updateAd runs. Line 131.
    // If no errors are tripped then if on line 132 trips and the ad is edited.
    // If errors are tripped, then else on line 134 trips and the errors are displayed and the form is sticky.
    if (!empty($_POST)) {
        if (Input::notEmpty('method') && Input::notEmpty('title') && Input::notEmpty('price') && Input::notEmpty('location') && Input::notEmpty('description') && Input::notEmpty('categories')) {
            $errorArray = insertAd($dbc, $user);
            if ($errorArray == []) {
                $errorArray = ['Ad Submitted!'];
            } else {
                $formMethod = Input::get('method');
                $formTitle = Input::get('title');
                $formPrice = Input::get('price');
                $formLoc = Input::get('location');
                $formDes = Input::get('description');
                $formCat = Input::get('categories');
            }
        } else {
            $errorArray = ['Please submit values for each data field.'];
            $yellow = true;
            $formMethod = Input::get('method');
            $formTitle = Input::get('title');
            $formPrice = Input::get('price');
            $formLoc = Input::get('location');
            $formDes = Input::get('description');
            $formCat = Input::has('categories') ? Input::get('categories') : [''];
        }
    }
    return array('user' => $user, 'errorArray' => $errorArray, 'yellow' => $yellow, 'formMethod' => $formMethod, 'formTitle' => $formTitle, 'formPrice' => $formPrice, 'formLoc' => $formLoc, 'formDes' => $formDes, 'formCat' => $formCat, 'justCategoriesArrayUnique' => $justCategoriesArrayUnique, 'loginstatus' => $loginstatus);
}
function checkValues()
{
    return Input::notEmpty('park') && Input::notEmpty('location') && Input::notEmpty('date_established') && Input::notEmpty('area_in_acres') && Input::notEmpty('description');
}
function checkValues()
{
    return Input::notEmpty('username') && Input::notEmpty('password') && Input::notEmpty('email') && Input::notEmpty('first_name') && Input::notEmpty('last_name') && Input::notEmpty('phone_number');
}
        $delete_park = Input::getNumber('delete_park');
    } catch (Exception $e) {
        $error = $e->getMessage();
        array_push($errorsArray, $error);
    }
    $query = "DELETE FROM national_parks WHERE id = :delete_park";
    $query = $dbc->prepare($query);
    $query->bindValue(':delete_park', $delete_park, PDO::PARAM_INT);
    $query->execute();
    return $errorsArray;
}
var_dump($_POST);
if (Input::notEmpty('name') && Input::notEmpty('location') && Input::notEmpty('date_established') && Input::notEmpty('area') && Input::notEmpty('visitors') && Input::notEmpty('description')) {
    var_dump($errorsArray);
    $errorsArray = insertPark($dbc, $parks);
} elseif (Input::notEmpty('delete_park')) {
    $errorsArray = deletePark($dbc);
}
var_dump($errorsArray);
var_dump($parks);
?>

<script type="text/javascript">
$(document).ready(function() {
	"use strict";

	$(".deletePark").click(function(a) {
		var parkName = $(this).data('name');
		var parkId = $(this).data('id');

		if(confirm("Are you sure you want to delete "+parkName+"?")){
function pageController()
{
    // Login information for db_connect.php.
    require '../park_login.php';
    // How we call to connect to the db via an outside file.
    require '../db_connect.php';
    // Calling file of functions for Input aka $_GET.
    require '../Input.php';
    // "&& is_numeric" prevents letter inputs into browser query string.
    // "round(abs())" prevents decimals and negative numbers as input to browser query string.
    $page = Input::has('page') && is_numeric(Input::get('page')) ? round(abs(Input::get('page'))) : 1;
    // Prevents page numbers less than 1. 0 causes problems by making a negative $offset.
    if ($page < 1) {
        $page = 1;
    }
    // Prevents changes to browser query string for limit value. 'newlimit' is tied to the Change Rows button.
    $limit = Input::has('newlimit') && is_numeric(Input::get('newlimit')) ? abs(intval(Input::get('newlimit'))) : 3;
    $offset = $page * $limit - $limit;
    // Gets the total number of rows of data.
    function getNumRows($dbc)
    {
        $stmt = $dbc->prepare('SELECT * FROM national_parks');
        $stmt->execute();
        $rowTotal = $stmt->rowCount();
        return $rowTotal;
    }
    $rowTotal = getNumRows($dbc);
    // Dividing $rowTotal by $limit gives us the number of pages to hold the data.
    $numOfPages = ceil($rowTotal / $limit);
    // Prevents page numbers more than the total number of pages.
    if ($page > $numOfPages) {
        $page = $numOfPages;
        $offset = $page * $limit - $limit;
    }
    // Uses variables of $limit and $offset to run the SELECT query in a scalable way.
    function getAllParks($dbc, $limit, $offset)
    {
        $stmt = $dbc->prepare('SELECT * FROM national_parks ORDER BY name LIMIT :limit OFFSET :offset');
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        $parksArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $parksArray;
    }
    function getAllAllParks($dbc)
    {
        $stmt = $dbc->prepare('SELECT * FROM national_parks ORDER BY name');
        $stmt->execute();
        $parksAllArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $parksAllArray;
    }
    $parksArray = getAllParks($dbc, $limit, $offset);
    $parksAllArray = getAllAllParks($dbc);
    // Uses the 'Submit A National Park' form to insert new values to the table and database.
    function insertParks($dbc)
    {
        // Now calls on the Input class's getString and getDate methods with try catches.
        // Try catch create an array of errors for passing to the user in the HTML.
        $errorArray = [];
        try {
            $name = Input::getString('name', 0, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errName'] = $error;
        }
        try {
            $location = Input::getString('location', 0, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errLoc'] = $error;
        }
        try {
            $date_established = Input::getDate('date_established', '1776-07-04', 'next month');
            $date_established = $date_established->format('Y-m-d');
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errDate'] = $error;
        }
        try {
            $area_in_acres = Input::getNumber('area_in_acres', 0, 375000000);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errArea'] = $error;
        }
        try {
            $description = Input::getString('description', 0, 500);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errDes'] = $error;
        }
        // If the $errorArray is not empty, this will return out of the method before binding values and executing below. The $errorArray returns with an array of strings.
        if (!empty($errorArray)) {
            return $errorArray;
        }
        $stmt = $dbc->prepare('INSERT INTO national_parks (name, location, date_established, area_in_acres, description) VALUES (:name, :location, :date_established, :area_in_acres, :description)');
        $stmt->bindValue(':name', $name, PDO::PARAM_STR);
        $stmt->bindValue(':location', $location, PDO::PARAM_STR);
        $stmt->bindValue(':date_established', $date_established, PDO::PARAM_STR);
        $stmt->bindValue(':area_in_acres', $area_in_acres, PDO::PARAM_STR);
        $stmt->bindValue(':description', $description, PDO::PARAM_STR);
        $stmt->execute();
    }
    // Uses the 'Delete A Park' form to delete a row of data from the table and database.
    function deletePark($dbc)
    {
        $park_to_delete = Input::get('park_to_delete');
        $stmt = $dbc->prepare('DELETE FROM national_parks WHERE id = :park_to_delete');
        $stmt->bindValue(':park_to_delete', $park_to_delete, PDO::PARAM_INT);
        $stmt->execute();
    }
    // Logic that checks for $_POST values and empty string before running the functions to insert or delete.
    // Additionally, saves a different $noteToUser variable and $errorArray to show the user in the HTML.
    $noteToUser = '';
    $errorArray = [''];
    $formName = '';
    $formLoc = '';
    $formDate = '';
    $formArea = '';
    $formDes = '';
    if (!empty($_POST)) {
        if (Input::notEmpty('name') && Input::notEmpty('location') && Input::notEmpty('date_established') && Input::notEmpty('area_in_acres') && Input::notEmpty('description')) {
            // If insertsParks() throws exceptions, it returns an array of strings. If no exceptions thrown, null.
            $errorArray = insertParks($dbc);
            $parksArray = getAllParks($dbc, $limit, $offset);
            $parksAllArray = getAllAllParks($dbc);
            $rowTotal = getNumRows($dbc);
            // This if checks the $errorArray, if empty insertParks() did not throw exception and it worked.
            if ($errorArray == []) {
                $noteToUser = '******';
                $errorArray = [''];
            } else {
                $formName = Input::get('name');
                $formLoc = Input::get('location');
                $formDate = Input::get('date_established');
                $formArea = Input::get('area_in_acres');
                $formDes = Input::get('description');
            }
        } elseif (Input::notEmpty('park_to_delete')) {
            deletePark($dbc);
            $parksArray = getAllParks($dbc, $limit, $offset);
            $parksAllArray = getAllAllParks($dbc);
            $rowTotal = getNumRows($dbc);
            $noteToUser = '******';
        } else {
            $noteToUser = '******';
        }
    }
    return array('parksArray' => $parksArray, 'parksAllArray' => $parksAllArray, 'page' => $page, 'limit' => $limit, 'offset' => $offset, 'rowTotal' => $rowTotal, 'numOfPages' => $numOfPages, 'noteToUser' => $noteToUser, 'errorArray' => $errorArray, 'formName' => $formName, 'formLoc' => $formLoc, 'formDate' => $formDate, 'formArea' => $formArea, 'formDes' => $formDes);
}
Example #12
0
function pageController()
{
    session_start();
    if (!Auth::check()) {
        header('Location: /auth/login');
        exit;
    }
    $username = Auth::user();
    $user = User::findUserByUsername($username);
    $errors = array();
    if (!empty($_POST)) {
        $item_name = ValidateAd::getItemName();
        $price = ValidateAd::getPrice();
        $description = ValidateAd::getDescription();
        $contact = ValidateAd::getContact();
        $errors = ValidateAd::getErrors();
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        try {
            $ext = array_search($finfo->file($_FILES['image']['tmp_name']), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true);
            if (false === $ext) {
                throw new RuntimeException('Invalid file format.');
            }
        } catch (RunTimeException $e) {
            $error = $e->getMessage();
            array_push($errors, $error);
        }
        $target = "public/upload_images";
        if (Input::notEmpty('item_name') && Input::notEmpty('price') && Input::notEmpty('description') && Input::notEmpty('contact')) {
            if (empty($errors)) {
                if (array_key_exists('image', $_FILES)) {
                    if ($_FILES["image"]["error"] == UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES["image"]["tmp_name"];
                        $name = $_FILES["image"]["name"];
                        try {
                            if ($name != "jpg" && $name != "png" && $name != "jpeg" && $name != "gif") {
                                throw new RuntimeException('Invalid file format.');
                            }
                        } catch (RunTimeException $e) {
                            $error = $e->getMessage();
                            array_push($errors, $error);
                        }
                        move_uploaded_file($tmp_name, "{$target}/{$name}");
                    }
                } else {
                }
                $ad = new Ad();
                $ad->item_name = $item_name;
                $ad->price = $price;
                $ad->description = $description;
                $ad->contact = $contact;
                $ad->user_id = $user->attributes['id'];
                $ad->image_path = "{$target}/{$name}";
                $ad->save();
                // redirect from add to the users profile so they can see what they added
                header('Location: /users');
                exit;
            }
        }
    }
    return array('username' => $username, 'errors' => $errors);
}
Example #13
0
function pageController()
{
    require_once '../db/db_connect.php';
    // Gets the current session and session id for logged in users.
    session_start();
    $sessionId = session_id();
    if (!isset($_SESSION['Loggedinuser'])) {
        header('location: auth.login.php');
        die;
    }
    $loginstatus = $_SESSION['Loggedinuser'] . " is logged in!";
    // This portion of code gets all the ads' categories in one array.
    // The categories, which are strings (sometimes with multiple categories in it),
    // are then put into the array by themselves. The array is imploded into a string and then exploded into an
    // array again. This allows us to split the strings with multiple categories in them.
    // The php array_unique removes duplicate category values and sort orders them by first letter.
    $arrayCategories = Ad::showJustCategories();
    $justCategories = [];
    foreach ($arrayCategories as $key => $value) {
        array_push($justCategories, $value['categories']);
    }
    $justCategoriesString = implode(', ', $justCategories);
    $justCategoriesArray = explode(', ', $justCategoriesString);
    $justCategoriesArrayUnique = array_unique($justCategoriesArray);
    sort($justCategoriesArrayUnique);
    // Through $_SESSION, gets the logged in user.
    $username = Auth::user();
    // Returns an object of the user's data.
    $user = User::finduserbyusername($username);
    // Using the user's id (a foreign key in the ads table), finds all ads by that user.
    $userAds = Ad::findAllAdsByUserId($user->id);
    // The first form "Select an Ad" sets 'ad_to_edit' in $_POST, which is the variable $adToEdit.
    $adToEdit = Input::has('ad_to_edit') ? (int) Input::get('ad_to_edit') : NULL;
    // Using $adToEdit, this returns an object of data about that ad.
    $adToEditObj = Ad::find($adToEdit);
    // Uses the second form of an edited ad to insert the new values into the table and database.
    function updateAd($dbc, $user)
    {
        // Now calls on the Input class's getString and getNumber methods with try catches.
        // Try catch create an array of errors for passing to the user in the HTML.
        $errorArray = [];
        try {
            $method = Input::getString('method', 1, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errMethod'] = $error;
        }
        try {
            $title = Input::getString('title', 1, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errTitle'] = $error;
        }
        try {
            $price = Input::getNumber('price', 0, 25000);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errPrice'] = $error;
        }
        try {
            $location = Input::getString('location', 1, 50);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errLoc'] = $error;
        }
        try {
            $description = Input::getString('description', 1, 500);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errDes'] = $error;
        }
        try {
            $adid = Input::getNumber('adid', 1, 5000000);
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        try {
            $categoriesArray = Input::get('categories', 1, 50);
            $categories = implode(', ', $categoriesArray);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $errorArray['errCats'] = $error;
        }
        // This portion allows for image uploads.
        // If the user does not upload an image, the value in the readonly input of image url is used instead.
        if (!isset($_FILES['image_upload'])) {
            $filename = Input::get('image_url');
        } else {
            if ($_FILES['image_upload']['name'] != '') {
                $uploads_directory = 'img/uploads/';
                $filename = $uploads_directory . basename($_FILES['image_upload']['name']);
                if (move_uploaded_file($_FILES['image_upload']['tmp_name'], $filename)) {
                    // echo 'The file ' . basename($_FILES['image_upload']['name']) . ' has been uploaded.';
                } else {
                    $errorArray['errImage'] = 'Sorry, there was an error uploading your file.';
                    var_dump($_FILES);
                }
            } else {
                $filename = Input::get('image_url');
            }
        }
        // If the $errorArray is not empty, this will return out of the method before binding values and executing below. The $errorArray returns with an array of strings.
        if (!empty($errorArray)) {
            return $errorArray;
        }
        $stmt = $dbc->prepare('UPDATE ads SET user_id = :user_id, method = :method, image_url = :image_url, title = :title, price = :price, location = :location, description = :description, categories = :categories WHERE id = :id');
        $stmt->bindValue(':id', $adid, PDO::PARAM_INT);
        $stmt->bindValue(':user_id', $user->id, PDO::PARAM_STR);
        $stmt->bindValue(':method', $method, PDO::PARAM_STR);
        $stmt->bindValue(':image_url', $filename, PDO::PARAM_STR);
        $stmt->bindValue(':title', $title, PDO::PARAM_STR);
        $stmt->bindValue(':price', $price, PDO::PARAM_INT);
        $stmt->bindValue(':location', $location, PDO::PARAM_STR);
        $stmt->bindValue(':description', $description, PDO::PARAM_STR);
        $stmt->bindValue(':categories', $categories, PDO::PARAM_STR);
        $stmt->execute();
    }
    // Sets each variable for future use in the following 'if else' logic tree.
    $errorArray = [''];
    $formMethod = '';
    $formImage = '';
    $formTitle = '';
    $formPrice = '';
    $formLoc = '';
    $formDes = '';
    $formAdId = '';
    $formCat = [''];
    $yellow = false;
    // If an ad is selected for editing, then this will populate each input with the ad's data from the ads table.
    // If no ad is selected, such as landing on the page at first or trying to submit an empty form, the else on line 152 will display.
    if (isset($_POST['ad_to_edit'])) {
        $errorArray = ['Make your edits.'];
        $yellow = true;
        $formMethod = $adToEditObj->method;
        $formImage = $adToEditObj->image_url;
        $formTitle = $adToEditObj->title;
        $formPrice = $adToEditObj->price;
        $formLoc = $adToEditObj->location;
        $formDes = $adToEditObj->description;
        $formCat = explode(', ', $adToEditObj->categories);
        $formAdId = $adToEdit;
    } else {
        $errorArray = ['Please select an ad to edit.'];
    }
    // If none of these are set in the $_POST, then nothing happens. This is the outer most if.
    // If these are empty, then the else on line 173 is tripped. Inner if/else on lines 158 and 173.
    // If these have values, updateAd runs. Line 159.
    // If no errors are tripped then if on line 161 trips and the ad is edited.
    // If errors are tripped, then else on line 163 trips and the errors are displayed and the form is sticky.
    if (Input::has('method') && Input::has('image_url') && Input::has('title') && Input::has('price') && Input::has('location') && Input::has('description')) {
        if (Input::notEmpty('method') && Input::notEmpty('image_url') && Input::notEmpty('title') && Input::notEmpty('price') && Input::notEmpty('location') && Input::notEmpty('description') && Input::notEmpty('categories')) {
            $errorArray = updateAd($dbc, $user);
            if ($errorArray == []) {
                $errorArray = ['Ad Editted!'];
            } else {
                $formMethod = Input::get('method');
                $formImage = Input::get('image_url');
                $formTitle = Input::get('title');
                $formPrice = Input::get('price');
                $formLoc = Input::get('location');
                $formDes = Input::get('description');
                $formAdId = Input::get('adid');
                $formCat = Input::get('categories');
            }
        } else {
            $errorArray = ['Please submit values for each data field.'];
            $yellow = true;
            $formMethod = Input::get('method');
            $formImage = Input::get('image_url');
            $formTitle = Input::get('title');
            $formPrice = Input::get('price');
            $formLoc = Input::get('location');
            $formDes = Input::get('description');
            $formAdId = Input::get('adid');
            $formCat = Input::get('categories');
        }
    }
    return array('user' => $user, 'userAds' => $userAds, 'errorArray' => $errorArray, 'yellow' => $yellow, 'formMethod' => $formMethod, 'formImage' => $formImage, 'formTitle' => $formTitle, 'formPrice' => $formPrice, 'formLoc' => $formLoc, 'formDes' => $formDes, 'formAdId' => $formAdId, 'formCat' => $formCat, 'justCategoriesArrayUnique' => $justCategoriesArrayUnique, 'loginstatus' => $loginstatus);
}
function insertData($dbc)
{
    $errors = [];
    if (!empty($_POST)) {
        try {
            $userName = Input::getString('username');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $password = Input::getString('pwd');
            $password = password_hash($password, PASSWORD_DEFAULT);
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $firstName = Input::getString('firstname');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $lastName = Input::getString('lastname');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $email = Input::getString('email');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        try {
            $zipCode = Input::getNumber('zipcode');
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
        if (Input::notEmpty('username') && Input::notEmpty('pwd') && Input::notEmpty('firstname') && Input::notEmpty('lastname') && Input::notEmpty('email') && Input::notEmpty('zipcode')) {
            // create new instance of user class
            $user = new User();
            $user->first_name = $firstName;
            $user->last_name = $lastName;
            $user->user_name = $userName;
            $user->password = $password;
            $user->email = $email;
            $user->zipcode = $zipCode;
            $user->save();
            $_SESSION['logInMessage'] = "Thanks for signing up. Please sign in to access your profile!!!";
            header("Location:index.php");
            die;
            // $userData = 'INSERT INTO user_account (first_name, last_name, user_name, password, email, zipcode)
            // 			VALUES (:first_name, :last_name, :user_name, :password, :email, :zipcode)';
            // $userStmt = $dbc->prepare($userData);
            // $userStmt->bindValue(':first_name', $firstName, PDO::PARAM_STR);
            // $userStmt->bindValue(':last_name', $lastName, PDO::PARAM_STR);
            // $userStmt->bindValue(':user_name', $userName, PDO::PARAM_STR);
            // $userStmt->bindValue(':password', password_hash($password, PASSWORD_DEFAULT), PDO::PARAM_STR);
            // $userStmt->bindValue(':email', $email, PDO::PARAM_STR);
            // $userStmt->bindValue(':zipcode', $zipCode, PDO::PARAM_INT);
            // try {
            // 	$userStmt->execute();
            // } catch (Exception $e) {
            // 	$errors[] = $e->getMessage();
            // }
        }
    }
    return $errors;
}