Added in ability to add a new project with and without an image

Signed-off-by: rodude123 <rodude123@gmail.com>
This commit is contained in:
Rohit Pai 2023-02-06 01:26:35 +00:00
parent db7c12857e
commit fd64eb92b0
10 changed files with 413 additions and 91 deletions

41
dist/api/index.php vendored
View File

@ -1,6 +1,5 @@
<?php /** @noinspection PhpIncludeInspection */
session_start();
////////////////// Index file //////////////
/// Creates base routes and runs ///
/// respective functions ///
@ -216,16 +215,17 @@ $app->get("/projectData", function (Request $request, Response $response)
$app->patch("/projectData/{id}", function (Request $request, Response $response, array $args)
{
global $projectData;
if (empty($args["id"] != "undefined"))
$data = $request->getParsedBody();
if ($args["id"] != "undefined")
{
if (empty($args["title"]) || empty($args["isMainProject"]) || empty($args["information"]) || empty($args["projectLink"]) || empty($args["githubLink"]))
if (empty($data["title"]) || empty($data["isMainProject"]) || empty($data["information"]) || empty($data["projectLink"]) || empty($data["gitLink"]))
{
// uh oh sent some empty data
$response->getBody()->write(json_encode(array("error" => "Only some of the data was sent")));
return $response->withStatus(400);
}
if (!$projectData->updateProjectData($args["title"], $args["isMainProject"], $args["information"], $args["projectLink"], $args["githubLink"], $args["id"]))
if (!$projectData->updateProjectData($args["id"], $data["title"], $data["isMainProject"], $data["information"], "", $data["projectLink"], $data["gitLink"]))
{
// uh oh something went wrong
$response->getBody()->write(json_encode(array("error" => "Something went wrong")));
@ -261,14 +261,14 @@ $app->post("/projectData", function (Request $request, Response $response)
{
global $projectData;
$data = $request->getParsedBody();
if (empty($data["title"]) || empty($data["isMainProject"]) || empty($data["information"]) || empty($data["projectLink"]) || empty($data["githubLink"]))
if (empty($data["title"]) || empty($data["isMainProject"]) || empty($data["information"]) || empty($data["projectLink"]) || empty($data["gitLink"]))
{
// uh oh sent some empty data
$response->getBody()->write(json_encode(array("error" => "Only some of the data was sent")));
return $response->withStatus(400);
}
$insertedID = $projectData->addProjectData($data["title"], $data["isMainProject"], $data["information"], $data["projectLink"], $data["githubLink"]);
$insertedID = $projectData->addProjectData($data["title"], $data["isMainProject"], $data["information"], $data["projectLink"], $data["gitLink"]);
if (!is_int($insertedID))
{
// uh oh something went wrong
@ -280,6 +280,29 @@ $app->post("/projectData", function (Request $request, Response $response)
return $response;
});
$app->post("/projectImage/{id}", function (Request $request, Response $response, array $args)
{
global $projectData;
$files = $request->getUploadedFiles();
if (empty($args["id"]) || empty($files))
{
// uh oh only some of the data was sent
$response->getBody()->write(json_encode(array("error" => "Only some of the data was sent")));
return $response->withStatus(400);
}
$message = $projectData->uploadImage($args["id"], $files["img"]);
if (!is_array($message))
{
// uh oh something went wrong
$response->getBody()->write(json_encode(array("error" => $message)));
return $response->withStatus(500);
}
$response->getBody()->write(json_encode($message));
return $response;
});
$app->post("/contact", function (Request $request, Response $response)
{
$data = $request->getParsedBody();
@ -479,6 +502,12 @@ $app->post("/user/login", function (Request $request, Response $response)
return $response->withStatus(401);
});
$app->get("/user/logout", function (Request $request, Response $response)
{
session_unset();
return $response;
});
$app->get("/user/isLoggedIn", function (Request $request, Response $response)
{
global $user;

View File

@ -2,11 +2,14 @@
// middleware
namespace api;
session_start();
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\App;
use Selective\SameSiteCookie\SameSiteCookieConfiguration;
use Selective\SameSiteCookie\SameSiteCookieMiddleware;
use Slim\Exception\HttpInternalServerErrorException;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Slim\Psr7\Response;
@ -76,7 +79,7 @@ class middleware
$app->add(new JwtAuthentication([
"rules" => [
new RequestPathRule([
"path" => ["/api/projectData", "/api/timeline/[a-z]*", "/api/user/testMethod"],
"path" => ["/api/projectData", "/api/timeline/[a-z]*", "/api/logout"],
"ignore" => ["/api/contact", "/api/user/login", "/api/user/changePassword"]
]),
new RequestMethodRule([
@ -114,6 +117,12 @@ class middleware
$response->getBody()->write(json_encode(array("status" => "405", "message" => "Method not allowed")));
return $response;
}
catch (HttpInternalServerErrorException $exception)
{
$response = (new Response())->withStatus(500);
$response->getBody()->write(json_encode(array("status" => "500", "message" => $exception->getMessage())));
return $response;
}
});
$app->addErrorMiddleware(true, true, true);

View File

@ -1,6 +1,7 @@
<?php
namespace api;
use PDO;
use Psr\Http\Message\UploadedFileInterface;
require_once "./config.php";
@ -17,7 +18,7 @@ class projectData
function getProjectData(): array
{
$conn = dbConn();
$stmt = $conn->prepare("SELECT title, isMainProject, information, imgLocation, projectLink, gitLink FROM projects order by date LIMIT 4;");
$stmt = $conn->prepare("SELECT ID, title, isMainProject, information, imgLocation, projectLink, gitLink FROM projects;");
$stmt->execute();
// set the resulting array to associative
@ -27,57 +28,141 @@ class projectData
{
return $result;
}
return array("errorMessage" => "Error, project data not found");
}
function updateProjectData(string $title, string $isMainProject, string $information, string $projectLink, string $githubLink, string $id): bool
/**
* Update project data in the database with the given ID
* @param string $ID - ID of the project in the database to update
* @param string $title - Title of the project
* @param bool $isMainProject - Is the project a main project or not
* @param string $information - Information about the project
* @param string $imgLocation - Location of the image
* @param string $projectLink - Link to the project
* @param string $gitLink - Link to the github repository
* @return bool - True if project was updated, false if not and there was an error
*/
function updateProjectData(string $ID, string $title, bool $isMainProject, string $information, string $imgLocation, string $projectLink, string $gitLink): bool
{
$conn = dbConn();
$stmt = $conn->prepare("UPDATE projects SET title = :title, isMainProject = :isMainProject, information = :information, projectLink = :projectLink, githubLink = :githubLink WHERE ID = :id");
$stmt = $conn->prepare("UPDATE projects SET title = :title, isMainProject = :isMainProject, information = :information, imgLocation = :imgLocation, projectLink = :projectLink, gitLink = :gitLink WHERE ID = :ID");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":isMainProject", $isMainProject);
$stmt->bindParam(":information", $information);
$stmt->bindParam(":imgLocation", $imgLocation);
$stmt->bindParam(":projectLink", $projectLink);
$stmt->bindParam(":gitLink", $gitLink);
$stmt->bindParam(":ID", $ID);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return true;
}
return false;
}
/**
* Delete project data from the database
* @param int $ID - ID of the project in the database to delete
* @return bool - True if project was deleted, false if not and there was an error
*/
function deleteProjectData(int $ID): bool
{
$conn = dbConn();
$stmt = $conn->prepare("DELETE FROM projects WHERE ID = :ID");
$stmt->bindParam(":ID", $ID);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return true;
}
return false;
}
/**
* Add project data to the database
* @param string $title - Title of the project
* @param string $isMainProject - Is the project a main project or not
* @param string $information - Information about the project
* @param string $projectLink - Link to the project
* @param string $gitLink - Link to the github repository
* @return int|bool - ID of the project if it was added, false if not and there was an error
*/
function addProjectData(string $title, string $isMainProject, string $information, string $projectLink, string $gitLink): int|bool
{
$conn = dbConn();
$stmt = $conn->prepare("INSERT INTO projects (title, isMainProject, information, projectLink, gitLink) VALUES (:title, :isMainProject, :information, :projectLink, :gitLink)");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":isMainProject", $isMainProject);
$stmt->bindParam(":information", $information);
$stmt->bindParam(":projectLink", $projectLink);
$stmt->bindParam(":githubLink", $githubLink);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":gitLink", $gitLink);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return true;
return $conn->lastInsertId();
}
return false;
}
function deleteProjectData(int $id): bool
/**
* Upload the image to the server and update the database with the new image location
* @param int $ID - ID of the project in the database to update
* @param UploadedFileInterface $img - Image preview of the project
* @return string|array - String with error message or array with the new image location
*/
public function uploadImage(int $ID, UploadedFileInterface $img): string | array
{
$conn = dbConn();
$stmt = $conn->prepare("DELETE FROM projects WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$targetDir = "../imgs/projects/";
$targetFile = $targetDir . basename($img->getClientFilename());
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if ($stmt->rowCount() > 0)
// Check if file already exists
if (file_exists($targetFile))
{
return true;
return "The file already exists";
}
return false;
}
function addProjectData(string $title, string $isMainProject, string $information, string $projectLink, string $githubLink): bool
{
$conn = dbConn();
$stmt = $conn->prepare("INSERT INTO projects (title, isMainProject, information, projectLink, githubLink) VALUES (:title, :isMainProject, :information, :projectLink, :githubLink)");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":isMainProject", $isMainProject);
$stmt->bindParam(":information", $information);
$stmt->bindParam(":projectLink", $projectLink);
$stmt->bindParam(":githubLink", $githubLink);
$stmt->execute();
if ($stmt->rowCount() > 0)
// Check file size
if ($img->getSize() > 2000000)
{
return true;
return "The file is too large, max 2MB";
}
return false;
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif")
{
return "Only JPG, JPEG, PNG & GIF files are allowed";
}
$img->moveTo($targetFile);
if (file_exists($targetFile))
{
// update the database with the new image location
$conn = dbConn();
$stmt = $conn->prepare("UPDATE projects SET imgLocation = :imgLocation WHERE ID = :ID");
$stmt->bindParam(":imgLocation", $targetFile);
$stmt->bindParam(":ID", $ID);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return array("imgLocation" => $targetFile);
}
return "Couldn't update the database";
}
return "Couldn't upload the image";
}
}

View File

@ -1 +1 @@
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Editor</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="css/main.css"><script src="https://kit.fontawesome.com/ed3c25598e.js" crossorigin="anonymous"></script></head><body><nav class="sideNav"><a href="#" class="closeBtn" id="navClose">&times;</a><ul><li><a href="#" id="goToCV"><span>&lt;</span>CV<span>&gt;</span></a></li><li><a href="#" id="goToProjects" class="active"><span>&lt;</span>Projects<span>&gt;</span></a></li><li><a href="#" id="goToSettings"><span>&lt;</span>Settings<span>&gt;</span></a></li><li><a href="#" id="logout"><span>&lt;</span>Logout<span>&gt;</span></a></li></ul></nav><main class="editor" style="margin-left: 250px;"><div class="title"><span id="navOpen">&#9776;</span><h1>Editor</h1></div><section id="curriculumVitae"><h2>curriculum vitae</h2><div class="cvGrid"><div><h3>Education</h3><div class="editorContainer"><form action="" method="POST" id="addEdu"><div class="formControl"><label for="dateFromE">Date From</label> <input type="date" id="dateFromE" name="dateFromE" required></div><div class="formControl"><label for="dateToE">Date To</label> <input type="date" id="dateToE" name="dateToE" required></div><div class="formControl"><label for="grade">Grade</label> <input type="text" id="grade" name="grade" required></div><div class="formControl"><label for="courseTitle">Course Title</label> <input type="text" id="courseTitle" name="courseTitle" required></div><div class="error hidden" id="eduError"><button class="close" type="button">&times;</button><div></div></div><input type="submit" class="btn btnPrimary boxShadowIn boxShadowOut" value="Add new course"></form><div class="timeline" id="edu"></div></div></div><div><h3>Work</h3><div class="editorContainer"><form action="" method="POST" id="addWork"><div class="formControl"><label for="dateFromW">Date From</label> <input type="date" id="dateFromW" name="dateFromW" required></div><div class="formControl"><label for="dateToW">Date To</label> <input type="date" id="dateToW" name="dateToW"></div><div class="formControl"><label for="company">Company</label> <input type="text" id="company" name="company" required></div><div class="formControl"><label for="area">Area</label> <input type="text" id="area" name="area" required></div><div class="formControl"><label for="jobTitle">Job Title</label> <input type="text" id="jobTitle" name="jobTitle" required></div><div class="error hidden" id="workError"><button class="close" type="button">&times;</button><div></div></div><input type="submit" class="btn btnPrimary boxShadowIn boxShadowOut" value="Add new job"></form><div class="timeline" id="work"></div></div></div></div></section><section id="projects"><h2>projects</h2><div class="projectsGrid"><form action="" id="addProj"><div class="formControl"><label for="projTitle">Title</label> <input type="text" name="projTitle" id="projTitle" required></div><div class="formControl"><label class="checkContainer" for="isMainProject">Is It The Main Project <input type="checkbox" id="isMainProject" name="isMainProject" required> <span class="checkmark"></span></label></div><div class="formControl"><label for="img">Image</label> <input type="file" name="img" id="img"></div><div class="formControl"><label for="projectInfo">Description</label> <textarea name="projectInfo" id="projectInfo"></textarea></div><div class="formControl"><label for="projectLink">Project Link</label> <input type="text" name="projectLink" id="projectLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)"></div><div class="formControl"><label for="gitLink">Git Link</label> <input type="text" name="gitLink" id="gitLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)" required></div><input type="submit" value="Add new Project" class="btn btnPrimary boxShadowIn boxShadowOut"></form><div id="projList"></div></div></section></main><script src="js/editor.js"></script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Editor</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="css/main.css"><script src="https://kit.fontawesome.com/ed3c25598e.js" crossorigin="anonymous"></script></head><body><nav class="sideNav"><a href="#" class="closeBtn" id="navClose">&times;</a><ul><li><a href="#" id="goToCV"><span>&lt;</span>CV<span>&gt;</span></a></li><li><a href="#" id="goToProjects" class="active"><span>&lt;</span>Projects<span>&gt;</span></a></li><li><a href="#" id="goToSettings"><span>&lt;</span>Settings<span>&gt;</span></a></li><li><a href="#" id="logout"><span>&lt;</span>Logout<span>&gt;</span></a></li></ul></nav><main class="editor" style="margin-left: 250px;"><div class="title"><span id="navOpen">&#9776;</span><h1>Editor</h1></div><section id="curriculumVitae"><h2>curriculum vitae</h2><div class="cvGrid"><div><h3>Education</h3><div class="editorContainer"><form action="" method="POST" id="addEdu"><div class="formControl"><label for="dateFromE">Date From</label> <input type="date" id="dateFromE" name="dateFromE" required></div><div class="formControl"><label for="dateToE">Date To</label> <input type="date" id="dateToE" name="dateToE" required></div><div class="formControl"><label for="grade">Grade</label> <input type="text" id="grade" name="grade" required></div><div class="formControl"><label for="courseTitle">Course Title</label> <input type="text" id="courseTitle" name="courseTitle" required></div><div class="error hidden" id="eduError"><button class="close" type="button">&times;</button><div></div></div><input type="submit" class="btn btnPrimary boxShadowIn boxShadowOut" value="Add new course"></form><div class="timeline" id="edu"></div></div></div><div><h3>Work</h3><div class="editorContainer"><form action="" method="POST" id="addWork"><div class="formControl"><label for="dateFromW">Date From</label> <input type="date" id="dateFromW" name="dateFromW" required></div><div class="formControl"><label for="dateToW">Date To</label> <input type="date" id="dateToW" name="dateToW"></div><div class="formControl"><label for="company">Company</label> <input type="text" id="company" name="company" required></div><div class="formControl"><label for="area">Area</label> <input type="text" id="area" name="area" required></div><div class="formControl"><label for="jobTitle">Job Title</label> <input type="text" id="jobTitle" name="jobTitle" required></div><div class="error hidden" id="workError"><button class="close" type="button">&times;</button><div></div></div><input type="submit" class="btn btnPrimary boxShadowIn boxShadowOut" value="Add new job"></form><div class="timeline" id="work"></div></div></div></div></section><section id="projects"><h2>projects</h2><div class="projectsGrid"><form action="" id="addProj"><div class="formControl"><label for="projTitle">Title</label> <input type="text" name="projTitle" id="projTitle" required></div><div class="formControl"><label class="checkContainer" for="isMainProject">Is It The Main Project <input type="checkbox" id="isMainProject" name="isMainProject"> <span class="checkmark"></span></label></div><div class="formControl"><label for="projImg">Image</label> <input type="file" name="projImg" id="projImg"></div><div class="formControl"><label for="projInfo">Description</label> <textarea name="projInfo" id="projInfo" required></textarea></div><div class="formControl"><label for="projLink">Project Link</label> <input type="text" name="projLink" id="projLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)"></div><div class="formControl"><label for="gitLink">Git Link</label> <input type="text" name="gitLink" id="gitLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)" required></div><div class="error hidden" id="projError"><button class="close" type="button">&times;</button><div></div></div><input type="submit" value="Add new Project" class="btn btnPrimary boxShadowIn boxShadowOut"></form><div id="projList"></div></div></section></main><script src="js/editor.js"></script></body></html>

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,5 @@
<?php /** @noinspection PhpIncludeInspection */
session_start();
////////////////// Index file //////////////
/// Creates base routes and runs ///
/// respective functions ///
@ -216,16 +215,17 @@ $app->get("/projectData", function (Request $request, Response $response)
$app->patch("/projectData/{id}", function (Request $request, Response $response, array $args)
{
global $projectData;
if (empty($args["id"] != "undefined"))
$data = $request->getParsedBody();
if ($args["id"] != "undefined")
{
if (empty($args["title"]) || empty($args["isMainProject"]) || empty($args["information"]) || empty($args["projectLink"]) || empty($args["githubLink"]))
if (empty($data["title"]) || empty($data["isMainProject"]) || empty($data["information"]) || empty($data["projectLink"]) || empty($data["gitLink"]))
{
// uh oh sent some empty data
$response->getBody()->write(json_encode(array("error" => "Only some of the data was sent")));
return $response->withStatus(400);
}
if (!$projectData->updateProjectData($args["title"], $args["isMainProject"], $args["information"], $args["projectLink"], $args["githubLink"], $args["id"]))
if (!$projectData->updateProjectData($args["id"], $data["title"], $data["isMainProject"], $data["information"], "", $data["projectLink"], $data["gitLink"]))
{
// uh oh something went wrong
$response->getBody()->write(json_encode(array("error" => "Something went wrong")));
@ -261,14 +261,14 @@ $app->post("/projectData", function (Request $request, Response $response)
{
global $projectData;
$data = $request->getParsedBody();
if (empty($data["title"]) || empty($data["isMainProject"]) || empty($data["information"]) || empty($data["projectLink"]) || empty($data["githubLink"]))
if (empty($data["title"]) || empty($data["isMainProject"]) || empty($data["information"]) || empty($data["projectLink"]) || empty($data["gitLink"]))
{
// uh oh sent some empty data
$response->getBody()->write(json_encode(array("error" => "Only some of the data was sent")));
return $response->withStatus(400);
}
$insertedID = $projectData->addProjectData($data["title"], $data["isMainProject"], $data["information"], $data["projectLink"], $data["githubLink"]);
$insertedID = $projectData->addProjectData($data["title"], $data["isMainProject"], $data["information"], $data["projectLink"], $data["gitLink"]);
if (!is_int($insertedID))
{
// uh oh something went wrong
@ -280,6 +280,29 @@ $app->post("/projectData", function (Request $request, Response $response)
return $response;
});
$app->post("/projectImage/{id}", function (Request $request, Response $response, array $args)
{
global $projectData;
$files = $request->getUploadedFiles();
if (empty($args["id"]) || empty($files))
{
// uh oh only some of the data was sent
$response->getBody()->write(json_encode(array("error" => "Only some of the data was sent")));
return $response->withStatus(400);
}
$message = $projectData->uploadImage($args["id"], $files["img"]);
if (!is_array($message))
{
// uh oh something went wrong
$response->getBody()->write(json_encode(array("error" => $message)));
return $response->withStatus(500);
}
$response->getBody()->write(json_encode($message));
return $response;
});
$app->post("/contact", function (Request $request, Response $response)
{
$data = $request->getParsedBody();
@ -479,6 +502,12 @@ $app->post("/user/login", function (Request $request, Response $response)
return $response->withStatus(401);
});
$app->get("/user/logout", function (Request $request, Response $response)
{
session_unset();
return $response;
});
$app->get("/user/isLoggedIn", function (Request $request, Response $response)
{
global $user;

View File

@ -2,11 +2,14 @@
// middleware
namespace api;
session_start();
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\App;
use Selective\SameSiteCookie\SameSiteCookieConfiguration;
use Selective\SameSiteCookie\SameSiteCookieMiddleware;
use Slim\Exception\HttpInternalServerErrorException;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Slim\Psr7\Response;
@ -76,7 +79,7 @@ class middleware
$app->add(new JwtAuthentication([
"rules" => [
new RequestPathRule([
"path" => ["/api/projectData", "/api/timeline/[a-z]*", "/api/user/testMethod"],
"path" => ["/api/projectData", "/api/timeline/[a-z]*", "/api/logout"],
"ignore" => ["/api/contact", "/api/user/login", "/api/user/changePassword"]
]),
new RequestMethodRule([
@ -114,6 +117,12 @@ class middleware
$response->getBody()->write(json_encode(array("status" => "405", "message" => "Method not allowed")));
return $response;
}
catch (HttpInternalServerErrorException $exception)
{
$response = (new Response())->withStatus(500);
$response->getBody()->write(json_encode(array("status" => "500", "message" => $exception->getMessage())));
return $response;
}
});
$app->addErrorMiddleware(true, true, true);

View File

@ -1,6 +1,7 @@
<?php
namespace api;
use PDO;
use Psr\Http\Message\UploadedFileInterface;
require_once "./config.php";
@ -17,7 +18,7 @@ class projectData
function getProjectData(): array
{
$conn = dbConn();
$stmt = $conn->prepare("SELECT title, isMainProject, information, imgLocation, projectLink, gitLink FROM projects order by date LIMIT 4;");
$stmt = $conn->prepare("SELECT ID, title, isMainProject, information, imgLocation, projectLink, gitLink FROM projects;");
$stmt->execute();
// set the resulting array to associative
@ -27,57 +28,141 @@ class projectData
{
return $result;
}
return array("errorMessage" => "Error, project data not found");
}
function updateProjectData(string $title, string $isMainProject, string $information, string $projectLink, string $githubLink, string $id): bool
/**
* Update project data in the database with the given ID
* @param string $ID - ID of the project in the database to update
* @param string $title - Title of the project
* @param bool $isMainProject - Is the project a main project or not
* @param string $information - Information about the project
* @param string $imgLocation - Location of the image
* @param string $projectLink - Link to the project
* @param string $gitLink - Link to the github repository
* @return bool - True if project was updated, false if not and there was an error
*/
function updateProjectData(string $ID, string $title, bool $isMainProject, string $information, string $imgLocation, string $projectLink, string $gitLink): bool
{
$conn = dbConn();
$stmt = $conn->prepare("UPDATE projects SET title = :title, isMainProject = :isMainProject, information = :information, projectLink = :projectLink, githubLink = :githubLink WHERE ID = :id");
$stmt = $conn->prepare("UPDATE projects SET title = :title, isMainProject = :isMainProject, information = :information, imgLocation = :imgLocation, projectLink = :projectLink, gitLink = :gitLink WHERE ID = :ID");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":isMainProject", $isMainProject);
$stmt->bindParam(":information", $information);
$stmt->bindParam(":imgLocation", $imgLocation);
$stmt->bindParam(":projectLink", $projectLink);
$stmt->bindParam(":gitLink", $gitLink);
$stmt->bindParam(":ID", $ID);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return true;
}
return false;
}
/**
* Delete project data from the database
* @param int $ID - ID of the project in the database to delete
* @return bool - True if project was deleted, false if not and there was an error
*/
function deleteProjectData(int $ID): bool
{
$conn = dbConn();
$stmt = $conn->prepare("DELETE FROM projects WHERE ID = :ID");
$stmt->bindParam(":ID", $ID);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return true;
}
return false;
}
/**
* Add project data to the database
* @param string $title - Title of the project
* @param string $isMainProject - Is the project a main project or not
* @param string $information - Information about the project
* @param string $projectLink - Link to the project
* @param string $gitLink - Link to the github repository
* @return int|bool - ID of the project if it was added, false if not and there was an error
*/
function addProjectData(string $title, string $isMainProject, string $information, string $projectLink, string $gitLink): int|bool
{
$conn = dbConn();
$stmt = $conn->prepare("INSERT INTO projects (title, isMainProject, information, projectLink, gitLink) VALUES (:title, :isMainProject, :information, :projectLink, :gitLink)");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":isMainProject", $isMainProject);
$stmt->bindParam(":information", $information);
$stmt->bindParam(":projectLink", $projectLink);
$stmt->bindParam(":githubLink", $githubLink);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":gitLink", $gitLink);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return true;
return $conn->lastInsertId();
}
return false;
}
function deleteProjectData(int $id): bool
/**
* Upload the image to the server and update the database with the new image location
* @param int $ID - ID of the project in the database to update
* @param UploadedFileInterface $img - Image preview of the project
* @return string|array - String with error message or array with the new image location
*/
public function uploadImage(int $ID, UploadedFileInterface $img): string | array
{
$conn = dbConn();
$stmt = $conn->prepare("DELETE FROM projects WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$targetDir = "../imgs/projects/";
$targetFile = $targetDir . basename($img->getClientFilename());
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if ($stmt->rowCount() > 0)
// Check if file already exists
if (file_exists($targetFile))
{
return true;
return "The file already exists";
}
return false;
}
function addProjectData(string $title, string $isMainProject, string $information, string $projectLink, string $githubLink): bool
{
$conn = dbConn();
$stmt = $conn->prepare("INSERT INTO projects (title, isMainProject, information, projectLink, githubLink) VALUES (:title, :isMainProject, :information, :projectLink, :githubLink)");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":isMainProject", $isMainProject);
$stmt->bindParam(":information", $information);
$stmt->bindParam(":projectLink", $projectLink);
$stmt->bindParam(":githubLink", $githubLink);
$stmt->execute();
if ($stmt->rowCount() > 0)
// Check file size
if ($img->getSize() > 2000000)
{
return true;
return "The file is too large, max 2MB";
}
return false;
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif")
{
return "Only JPG, JPEG, PNG & GIF files are allowed";
}
$img->moveTo($targetFile);
if (file_exists($targetFile))
{
// update the database with the new image location
$conn = dbConn();
$stmt = $conn->prepare("UPDATE projects SET imgLocation = :imgLocation WHERE ID = :ID");
$stmt->bindParam(":imgLocation", $targetFile);
$stmt->bindParam(":ID", $ID);
$stmt->execute();
if ($stmt->rowCount() > 0)
{
return array("imgLocation" => $targetFile);
}
return "Couldn't update the database";
}
return "Couldn't upload the image";
}
}

View File

@ -121,26 +121,30 @@
</div>
<div class="formControl">
<label class="checkContainer" for="isMainProject">Is It The Main Project
<input type="checkbox" id="isMainProject" name="isMainProject" required>
<input type="checkbox" id="isMainProject" name="isMainProject">
<span class="checkmark"></span>
</label>
</div>
<div class="formControl">
<label for="img">Image</label>
<input type="file" name="img" id="img">
<label for="projImg">Image</label>
<input type="file" name="projImg" id="projImg">
</div>
<div class="formControl">
<label for="projectInfo">Description</label>
<textarea name="projectInfo" id="projectInfo"></textarea>
<label for="projInfo">Description</label>
<textarea name="projInfo" id="projInfo" required></textarea>
</div>
<div class="formControl">
<label for="projectLink">Project Link</label>
<input type="text" name="projectLink" id="projectLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)">
<label for="projLink">Project Link</label>
<input type="text" name="projLink" id="projLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)">
</div>
<div class="formControl">
<label for="gitLink">Git Link</label>
<input type="text" name="gitLink" id="gitLink" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)" required>
</div>
<div class="error hidden" id="projError">
<button class="close" type="button">&times;</button>
<div></div>
</div>
<input type="submit" value="Add new Project" class="btn btnPrimary boxShadowIn boxShadowOut">
</form>
<div id="projList">

View File

@ -56,7 +56,7 @@ document.addEventListener('DOMContentLoaded', () =>
{
json.forEach(item =>
{
addProject(item["ID"], item["title"], item["information"], item["projectLink"], item["gitLink"]);
addProject(item["ID"], (item["imgLocation"] === "") ? "../imgs/placeholder.png" : item["imgLocation"], item["title"], item["information"], item["projectLink"], item["gitLink"]);
})
return;
}
@ -114,7 +114,7 @@ document.querySelector("#addEdu").addEventListener("submit", e =>
method: "POST",
body: data,
headers: {
"Authentication": localStorage.getItem("token")
"Authorization": "Bearer " + localStorage.getItem("token")
}
}).then(res => res.json().then(json =>
{
@ -149,7 +149,7 @@ document.querySelector("#addWork").addEventListener("submit", e =>
method: "POST",
body: data,
headers: {
"Authentication": localStorage.getItem("token")
"Authorization": "Bearer " + localStorage.getItem("token")
}
}).then(res => res.json().then(json =>
{
@ -170,6 +170,75 @@ document.querySelector("#addWork").addEventListener("submit", e =>
}));
});
document.querySelector("#addProj").addEventListener("submit", e =>
{
e.preventDefault();
let data = new FormData();
data.append("title", document.querySelector("#projTitle").value);
data.append("isMainProject", document.querySelector("#isMainProject").checked ? "true" : "false");
data.append("information", document.querySelector("#projInfo").value);
data.append("projectLink", document.querySelector("#projLink").value);
data.append("gitLink", document.querySelector("#gitLink").value);
let imgData = new FormData();
imgData.append("img", document.querySelector("#projImg").files[0]);
let newProjectID = 0;
fetch("/api/projectData", {
method: "POST",
body: data,
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}).then(res => res.json().then(newProjectData =>
{
if (res.ok)
{
if (imgData.get("img") === "undefined")
{
addProject(newProjectData.ID, "../imgs/placeholder.png", data.get("title"), data.get("information"), data.get("projectLink"), data.get("gitLink"));
document.querySelector("#addProj").reset();
return;
}
newProjectID = newProjectData.ID;
return fetch("/api/projectImage/" + newProjectData.ID, {
method: "POST",
body: imgData,
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
});
}
if (res.status === 401)
{
window.location.href = "./";
return;
}
showErrorMessage(newProjectData.error, "proj");
}).then(res => res.json().then(newProjectImage =>
{
if (res.ok)
{
addProject(newProjectID, newProjectImage.imgLocation, data.get("title"), data.get("information"), data.get("projectLink"), data.get("gitLink"));
document.querySelector("#addProj").reset();
return;
}
if (res.status === 401)
{
window.location.href = "./";
return;
}
showErrorMessage(newProjectImage.error, "proj");
})));
});
document.querySelector("#goToCV").addEventListener("click", () =>
{
@ -195,7 +264,6 @@ document.querySelector("#logout").addEventListener("click", () =>
{
if (res.ok)
{
localStorage.removeItem("token");
window.location.reload();
}
});
@ -207,6 +275,9 @@ document.querySelector("#eduError .close").addEventListener("click", () =>
document.querySelector("#workError .close").addEventListener("click", () =>
document.querySelector("#workError").classList.toggle("hidden"));
document.querySelector("#projError .close").addEventListener("click", () =>
document.querySelector("#projError").classList.toggle("hidden"));
/**
* Shows respective error message for form
* @param {string} message The error message to show
@ -534,8 +605,8 @@ function updateProjectItem(id, e)
res.json().then(json =>
{
document.querySelector(`#projectError${id}`).classList.remove("hidden");
document.querySelector(`#projectError${id} div`).innerHTML = json.error;
document.querySelector(`#projError${id}`).classList.remove("hidden");
document.querySelector(`#projError${id} div`).innerHTML = json.error;
});
});
@ -584,12 +655,13 @@ function deleteProjectItem(id)
/**
* Adds a new project to the page
* @param {number} id the id of the project from the database
* @param {string} imgLocation the relative path of the image
* @param {string} title the title of the project
* @param {string} information the information about the project
* @param {string} projectLink the link to the project
* @param {string} gitLink the link to the git repository
*/
function addProject(id, title, information, projectLink, gitLink)
function addProject(id, imgLocation, title, information, projectLink, gitLink)
{
let projectItem = document.createElement("form");
projectItem.id = "projectItem" + id;
@ -600,7 +672,7 @@ function addProject(id, title, information, projectLink, gitLink)
<button class="edit" type="button" id="edit${id}" onclick="editProjectItem(${id})"><i class="fa-solid fa-pen-to-square"></i></button>
<button class="delete" type="button" id="delete${id}" onclick="deleteProjectItem(${id})"><i class="fa-solid fa-trash"></i></button>
</div>
<img class="displayedImage" src="../imgs/500x400.jpg" alt="image preivew of the project">
<img class="displayedImage" src="${(imgLocation === "N/A") ? "../imgs/500x400.jpg" : imgLocation}" alt="image preivew of the project">
<div class="formControl imageContainer">
<input type="file" name="img${id}" id="img${id}">
</div>