-
-';
-} else {
- echo $_SESSION['login'] . ', Welcome to the gallery
-
Upload New Image ';
-}
-if (isset($temp)) {
- if ($temp == 1) {
- echo '';
- }
- if ($temp == 0) {
- echo '';
- }
-}
-};
\ No newline at end of file
diff --git a/src/classes/App.php b/src/classes/App.php
new file mode 100644
index 0000000..960b7ba
--- /dev/null
+++ b/src/classes/App.php
@@ -0,0 +1,47 @@
+get('session');
+ }
+ //application startup
+ public function run()
+ {
+ $page = new Page($_GET);
+ $page->load();
+ }
+ //logging the errors
+ public function errorHandler($errorNo, $errorMessage, $errorFile, $errorLine)
+ {
+ $error = 'Error level: ' . $errorNo . ' Text: ' . $errorMessage . ' in file: ' . $errorFile . ' on line: ' . $errorLine . "\n";
+ App::get('log')->write($error);
+ }
+ //showing the page with errors
+ public function shutDown()
+ {
+ if ($error = error_get_last()) {
+ App::get('log')->write($error['message']);
+ require($_SERVER['DOCUMENT_ROOT'] . 'view/error.php');
+ }
+ }
+ public function exceptionHandler($e)
+ {
+ App::get('log')->write($e->getMessage());
+ require($_SERVER['DOCUMENT_ROOT'] . 'view/error.php');
+ }
+ //getting the classes names
+ public static function get($className)
+ {
+ if (!isset(self::$di[$className])) {
+ $class = ucwords($className);
+ self::$di[$className] = new $class;
+ }
+ return self::$di[$className];
+ }
+ private static $di = [];
+}
\ No newline at end of file
diff --git a/src/classes/Controller.php b/src/classes/Controller.php
new file mode 100644
index 0000000..46be373
--- /dev/null
+++ b/src/classes/Controller.php
@@ -0,0 +1,112 @@
+page = $page;
+ }
+ public function process()
+ {
+ $pageAction = $this->page->getPath() . "Action";
+ if (method_exists($this, $pageAction)) {
+ $this->$pageAction();
+ } else {
+ $this->notFoundAction();
+ }
+ }
+ //show the index page
+ private function indexAction()
+ {
+ $this->_render('view/index.php', [
+ 'title' => 'Image Gallery',
+ 'image' => new Image(),
+ 'pagination' => new Pagination(),
+ ]);
+ }
+ //show the form page
+ private function formAction()
+ {
+ $this->_render('view/form.php', [
+ 'errors' => App::get('session')->messages()
+ ]);
+ }
+ //show the login page
+ private function loginAction()
+ {
+ $this->_render('view/login.php', [
+ 'errors' => App::get('session')->messages()
+ ]);
+ }
+ //show the signup page
+ private function registerAction()
+ {
+ $this->_render('view/register.php', [
+ 'errors' => App::get('session')->messages()
+ ]);
+ }
+ //image validation
+ private function processAction()
+ {
+ $request = $_REQUEST;
+ if (($valid = App::get('form')->imgValidation($request)) === true) {
+ if (App::get('image')->save()) {
+ header('Location: /');
+ } else {
+ header('Location: /form');
+ }
+ } else {
+ header('Location: /');
+ }
+ }
+ /**
+ * authorization process
+ */
+ private function processLoginAction()
+ {
+ $post = $_POST;
+ if (App::get('form')->loginValidation($post) && App::get('user')->auth($post['login'], $post['pass'])) {
+ header('Location: /');
+ } else {
+ header('Location: /login');
+ }
+ }
+ /**
+ * Logout user
+ */
+ private function logoutAction()
+ {
+ App::get('user')->logout();
+ App::get('session')->setMessage('Logged out successfully');
+ $this->page->redirect('/');
+ }
+ //signup process function
+ private function processRegisterAction()
+ {
+ $post = $_POST;
+ $user=new User();
+ if (Form::signupValidation($post) && $user->create($post['login'], $post['pass'])) {
+ header('Location: /');
+ } else {
+ header('Location: /register');
+ }
+ }
+ //image delete function
+ private function removeImageAction()
+ {
+ $id = $_REQUEST['id'];
+ App::get('image')->delete($id);
+ $this->page->redirect('/');
+ }
+ private function notFoundAction()
+ {
+ $this->_render('view/404.php');
+ }
+
+ private function _render($template, $params = [])
+ {
+ extract($params);
+ include($template);
+ }
+}
\ No newline at end of file
diff --git a/src/classes/Database.php b/src/classes/Database.php
new file mode 100644
index 0000000..03a345f
--- /dev/null
+++ b/src/classes/Database.php
@@ -0,0 +1,33 @@
+write($exception->getMessage());
+ echo 'Could not connect to DB';
+ exit;
+ } catch (Exception $exception) {
+ App::get('log')->write($exception->getMessage());
+ echo 'Could not connect to DB';
+ exit;
+ }
+ }
+ return static::$pdo;
+ }
+
+}
\ No newline at end of file
diff --git a/src/classes/Form.php b/src/classes/Form.php
new file mode 100644
index 0000000..61387ef
--- /dev/null
+++ b/src/classes/Form.php
@@ -0,0 +1,75 @@
+ 40) {
+ $errors[] = 'Enter author up to 40 symbols';
+ }
+ if (empty($data['description']) || strlen($data['description']) > 255) {
+ $errors[] = 'Enter description up to 255 symbols';
+ }
+ if (empty($_FILES)) {
+ $errors[] = 'Your forgot to upload the image';
+ }
+ if (!in_array(getimagesize($_FILES['image']['tmp_name'])['mime'], ['image/jpeg', 'image/png', 'image/gif'])) {
+ $errors[] = 'The gallery supports only the JPEG, PNG and GIF images';
+ }
+ if (!empty($errors)) {
+ $_SESSION['fields'] = $data;
+ $_SESSION['errors'] = $errors;
+ return false;
+ } else {
+ return true;
+ }
+ }
+ /** Validate login form field values
+ *
+ * @param $data
+ * @return array|bool
+ */
+ public function loginValidation($data)
+ {
+ $errors = array();
+ if (empty($data['login'])) {
+ $errors[] = 'Login shouldn\'t be empty';
+ }
+ if (empty($data['pass'])) {
+ $errors[] = 'Password shouldn\'t be empty';
+ }
+ if (!empty($errors)) {
+ $_SESSION['errors'] = $errors;
+ $_SESSION['fields'] = $data;
+ return false;
+ } else {
+ return true;
+ }
+ }
+ //signup form validation
+ public function signupValidation($data)
+ {
+ $errors = array();
+ if (empty($data['login'])) {
+ $errors[] = 'Enter your login';
+ }
+ if (empty($data['pass']) || empty($data['repass'])) {
+ $errors[] = 'Enter your password';
+ }
+ if ($data['pass'] != $data['repass']) {
+ $errors[] = 'Check the passwords to be equal';
+ }
+ if (!empty($errors)) {
+ $_SESSION['errors'] = $errors;
+ $_SESSION['fields'] = $data;
+ return false;
+ } else {
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/classes/Image.php b/src/classes/Image.php
new file mode 100644
index 0000000..4e102cd
--- /dev/null
+++ b/src/classes/Image.php
@@ -0,0 +1,198 @@
+database = Database::connect();
+ }
+ protected function request($sql, $params = [])
+ {
+ $query = $this->database->prepare($sql);
+ $result = $query->execute($params);
+ if ($result === false) {
+ error_log($query->errorInfo()[2], 3, $_SERVER['DOCUMENT_ROOT'] . Log::ERRORS_LOG);
+ return false;
+ }
+ return $query;
+ }
+
+ const PLACEHOLDER = 'https://fakeimg.pl/300x200';
+ const THUMBNAIL_PATH = 'pub/media/thumbnails/';
+ const IMAGE_PATH = 'pub/media/images/';
+
+ //sorting the images by date
+ public function sort(&$images)
+ {
+ if (!empty($images)) {
+ //sorting part
+ usort($images, function ($imageA, $imageB) {
+ if ($imageA['created_at'] == $imageB['created_at']) {
+ return 0;
+ }
+ return ($imageA['created_at'] < $imageB['created_at']) ? -1 : 1;
+ });
+ }
+ }
+ //time and date formatting
+ public function getCurrentDate()
+ {
+ return date('d M Y H:i:s', time());
+ }
+ //showing the images
+ public function exists($imagePath)
+ {
+ if (file_exists(self::IMAGE_PATH . $imagePath)) {
+ return self::IMAGE_PATH . $imagePath;
+ } else {
+ return self::PLACEHOLDER;
+ }
+ }
+ //creating the thumbnails
+ public function thumbnail($imagePath, &$width, &$height)
+ {
+ if (!$this->createDir(self::THUMBNAIL_PATH)) {
+ return self::PLACEHOLDER;
+ }
+ $params = $this->getOriginalSize($imagePath);
+ $thumbnailPath = $this->resize($imagePath, $width, $height, $params);
+ list($width, $height) = $params;
+ if ($thumbnailPath) {
+ return $thumbnailPath;
+ } else {
+ return self::PLACEHOLDER;
+ }
+ }
+ //change the images size
+ public function resize($imagePath, $width, $height, $params)
+ {
+ $filename = self::THUMBNAIL_PATH . basename($imagePath);
+ if (file_exists($filename)) {
+ return $filename;
+ }
+ $mime = $params['mime'];
+ //use specific function based on image format
+ switch ($mime) {
+ case 'image/jpeg':
+ $imageCreateFunc = 'imagecreatefromjpeg';
+ $imageSaveFunc = 'imagejpeg';
+ break;
+ case 'image/png':
+ $imageCreateFunc = 'imagecreatefrompng';
+ $imageSaveFunc = 'imagepng';
+ break;
+ case 'image/gif':
+ $imageCreateFunc = 'imagecreatefromgif';
+ $imageSaveFunc = 'imagegif';
+ break;
+ default:
+ throw new Exception('Sorry, we support only JPEG, PNG and GIF images');
+ }
+ //Variable function
+ $img = $imageCreateFunc($imagePath);
+ //list is php construction that allows to set array elements to variables
+ list($originalWidth, $originalHeight) = $params;
+ //calculate height
+ if (!$height) {
+ $height = ($originalHeight / $originalWidth) * $width;
+ }
+ //create new image
+ $bufferImage = imagecreatetruecolor($width, $height);
+ imagecopyresampled($bufferImage, $img, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
+ //return buffer output as string
+ ob_start();
+ $imageSaveFunc($bufferImage);
+ $imageSource = ob_get_clean();
+ if (file_put_contents($filename, $imageSource)) {
+ return $filename;
+ }
+ return false;
+ }
+ //getting the images size
+ public function getOriginalSize($imagePath)
+ {
+ return getimagesize($imagePath);
+ }
+ //showing the images array
+ public function getCollection()
+ {
+ if (isset($_GET['p'])) {
+ $offset = $_GET['p'] - 1;
+ } else {
+ $offset = 0;
+ }
+ //$offset = isset($_GET['p']) ? $_GET['p'] - 1 : 0;
+ $offset = $offset * Pagination::IMAGE_COUNT;
+ $sql = "SELECT images.id, image_path, thumbnail_path, author_name, description, created_at, login FROM images
+LEFT JOIN users on images.user_id = users.id
+LIMIT " . $offset . ", " . Pagination::IMAGE_COUNT;
+ $result = $this->request($sql);
+ $images = [];
+ if ($result->rowCount() > 0) {
+ foreach ($result->fetchAll() as $value) {
+ $images[] = $value;
+ }
+ } else {
+ // set empty array
+ $images = [];
+ }
+ $this->sort($images);
+ return $images;
+ }
+ //delete images
+ public function delete($id)
+ {
+ if (App::get('session')->isLoggedIn()) {
+ $image = $this->request("SELECT image_path, thumbnail_path FROM images WHERE id = :id", [':id' => $id]);
+ $this->request("DELETE FROM images WHERE id = :id", [':id' => $id]);
+ unlink($image->fetchColumn(0));
+ unlink($image->fetchColumn(1));
+ $_SESSION['messages'] = ['You have deleted image'];
+ return true;
+ } else {
+ $_SESSION['errors'] = ['Log in to delete images'];
+ return false;
+ }
+ }
+ //save the images
+ public function save()
+ {
+ $sql = 'INSERT INTO images(id, image_path, thumbnail_path, description, author_name, created_at, user_id)
+VALUES(NULL, :image_path, :thumbnail_path, :description, :author_name, CURRENT_TIMESTAMP(), :user_id)';
+ if ($filename = $this->upload($_FILES['image'])) {
+ $width = 300;
+ $height = 200;
+ $params = [
+ ':image_path' => $filename,
+ ':thumbnail_path' => $this->thumbnail($filename, $width, $height),
+ ':description' => $_REQUEST['description'],
+ ':author_name' => $_REQUEST['authorname'],
+ ':user_id' => $_SESSION['auth'],
+ ];
+ $this->request($sql, $params);
+ App::get('session')->setMessage('You have uploaded new image');
+ unset($_SESSION['fields']);
+ return true;
+ }
+ App::get('session')->setError('Unable to upload image');
+ return false;
+ }
+ public function upload($file)
+ {
+ if (!$this->createDir(self::IMAGE_PATH)) {
+ return false;
+ }
+ $filename = self::IMAGE_PATH . time() . $file['name'];
+ if (move_uploaded_file($file['tmp_name'], $filename)) {
+ return $filename;
+ }
+ return false;
+ }
+ public function createDir($path)
+ {
+ if (!file_exists($path)) {
+ return mkdir($path, 0777);
+ }
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/src/classes/Log.php b/src/classes/Log.php
new file mode 100644
index 0000000..e5ba37b
--- /dev/null
+++ b/src/classes/Log.php
@@ -0,0 +1,9 @@
+path = $get['page']??'index';
+ $this->isAllowedPage();
+ }
+ /**
+ * Load page
+ */
+ public function load()
+ {
+ $controller = new Controller($this);
+ $controller->process();
+ }
+ /**
+ * Check if page is allowed for non logged in users
+ */
+ private function isAllowedPage()
+ {
+ if(!preg_match("~^\w+$~", $this->path)) {
+ die("Page id must be alphanumeric");
+ }
+ if ((!App::get('session')->isLoggedIn() && $this->path == 'form') || (App::get('session')->isLoggedIn() && ($this->path == 'login' || $this->path == 'register'))) {
+ header('Location: /');
+ exit();
+ }
+ }
+ /**
+ * Get page path
+ *
+ * @return string
+ */
+ public function getPath()
+ {
+ return $this->path;
+ }
+ public function redirect($url)
+ {
+ header('Location: ' . $url);
+ }
+}
\ No newline at end of file
diff --git a/src/classes/Pagination.php b/src/classes/Pagination.php
new file mode 100644
index 0000000..c32e03c
--- /dev/null
+++ b/src/classes/Pagination.php
@@ -0,0 +1,107 @@
+database = Database::connect();
+ }
+ /** Process database queries
+ *
+ * @param string $sql
+ * @param array $params
+ * @return bool|int|PDOStatement
+ */
+ protected function request($sql, $params = [])
+ {
+ $query = $this->database->prepare($sql);
+ $result = $query->execute($params);
+ if ($result === false) {
+ error_log($query->errorInfo()[2], 3, $_SERVER['DOCUMENT_ROOT'] . Log::LOG_FILE);
+ return false;
+ }
+ return $query;
+ }
+ const IMAGE_COUNT = 9;
+ /** @var int count of pages */
+ private $pageCount = false;
+ /** Return qty of pages
+ *
+ * @return float|int
+ */
+ private function getPageCount()
+ {
+ if (!$this->pageCount) {
+ $result = $this->request('SELECT COUNT(id) FROM images');
+ return ceil($result->fetchColumn(0) / self::IMAGE_COUNT);
+ } else {
+ return $this->pageCount;
+ }
+ }
+ /** Get last page number
+ *
+ * @return int
+ */
+ private function getLastPage(): int
+ {
+ return $this->getPageCount();
+ }
+ /** Get first page, first page is 1
+ *
+ * @return int
+ */
+ private function getFirstPage()
+ {
+ return 1;
+ }
+ /** Get next page number
+ *
+ * @return bool|int
+ */
+ private function getNextPage()
+ {
+ if (isset($_REQUEST['p']) && $this->getPageCount() <= $_REQUEST['p']) {
+ return false;
+ } elseif (isset($_REQUEST['p'])) {
+ return $_REQUEST['p'] + 1;
+ } else {
+ return 2;
+ }
+ }
+ /** Get previous page number
+ *
+ * @return bool|int
+ */
+ private function getPrevPage()
+ {
+ return isset($_REQUEST['p']) && $_REQUEST['p'] > 1 ? $_REQUEST['p'] - 1 : false;
+ }
+ /** Get current page number
+ *
+ * @return int
+ */
+ private function getCurrentPage()
+ {
+ return isset($_REQUEST['p']) ? $_REQUEST['p'] : 1;
+ }
+ /** Generate pagination HTML
+ *
+ * @return string
+ */
+ public function render()
+ {
+ $html = '';
+ if ($this->getPageCount() > 1) {
+ $html .= "
Go to first page ";
+ if ($prevPage = $this->getPrevPage()) {
+ $html .= "
" . $prevPage . " ";
+ }
+ $html .= "
" . $this->getCurrentPage() . " ";
+ if ($nextPage = $this->getNextPage()) {
+ $html .= "
" . $nextPage . " ";
+ }
+ $html .= "
Go to last page ";
+ }
+ return $html;
+ }
+}
\ No newline at end of file
diff --git a/src/classes/Session.php b/src/classes/Session.php
new file mode 100644
index 0000000..ac5968f
--- /dev/null
+++ b/src/classes/Session.php
@@ -0,0 +1,65 @@
+';
+ }
+ unset($_SESSION['messages']);
+ return $messages;
+ }
+ return false;
+ }
+ //getting the notifications array
+ public function getErrors()
+ {
+ if (isset($_SESSION['errors']) && !empty($_SESSION['errors'])) {
+ $errors = '';
+ foreach ($_SESSION['errors'] as $error) {
+ $errors .= $error . '
';
+ }
+ unset($_SESSION['errors']);
+ return $errors;
+ }
+ return false;
+ }
+
+ public function clear()
+ {
+ $_SESSION = [];
+ }
+ public function setMessage($message)
+ {
+ $_SESSION['messages'][] = $message;
+ }
+ public function setError($error)
+ {
+ $_SESSION['messages'][] = $error;
+ }
+ public function messages()
+ {
+ return $this->getMessages() . $this->getErrors();
+ }
+ public function isLoggedIn()
+ {
+ if (isset($_SESSION['auth']) && !empty($_SESSION['auth'])) {
+ return true;
+ }
+ return false;
+ }
+ public function getFieldValue($field)
+ {
+ if (isset($_SESSION['fields'][$field])) {
+ return $_SESSION['fields'][$field];
+ }
+ return '';
+ }
+}
\ No newline at end of file
diff --git a/src/classes/User.php b/src/classes/User.php
new file mode 100644
index 0000000..7cef4c0
--- /dev/null
+++ b/src/classes/User.php
@@ -0,0 +1,51 @@
+database = Database::connect();
+ }
+ //DB query for logging in
+ protected function request($sql, $params = [])
+ {
+ $query = $this->database->prepare($sql);
+ $result = $query->execute($params);
+ if ($result === false) {
+ error_log($query->errorInfo()[2], 3, $_SERVER['DOCUMENT_ROOT'] . Log::ERRORS_LOG);
+ return false;
+ }
+ return $query;
+ }
+ //user verification
+ public function create($login, $pass)
+ {
+ $pass = crypt($pass, $login);
+ if ($this->request('INSERT INTO users(id, login, password) VALUES(NULL, :login, :pass)', array(':login' => $login, ':pass' => $pass))) {
+ $_SESSION['auth'] = $this->database->lastInsertId();
+ $_SESSION['messages'][] = 'Your account has been created';
+ return true;
+ }
+ $_SESSION['errors'][] = 'Something went wrong';
+ return false;
+ }
+ public function logout()
+ {
+ App::get('session')->clear();
+ }
+ //user verification
+ function auth($postUser, $postPass)
+ {
+ $pass = crypt($postPass, $postUser);
+ $result = $this->request('SELECT id FROM users WHERE login = :login AND password = :pass', [':login' => $postUser, ':pass' => $pass]);
+ if ($result->rowCount() == 1) {
+ $_SESSION['auth'] = $result->fetchColumn(0);
+ $_SESSION['messages'] = ['Logged in successfully'];
+ unset($_SESSION['fields']);
+ return true;
+ }
+ $_SESSION['errors'] = ['Check your login'];
+ $_SESSION['fields'] = $_POST;
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/src/process.php b/src/process.php
deleted file mode 100644
index 41aed83..0000000
--- a/src/process.php
+++ /dev/null
@@ -1,13 +0,0 @@
- 'Something went wrong')));
- }
-} else {
- header('Location: /form?' . http_build_query(array('errors' => $valid)));
-}
\ No newline at end of file
diff --git a/src/registration.php b/src/registration.php
deleted file mode 100644
index d80d341..0000000
--- a/src/registration.php
+++ /dev/null
@@ -1,63 +0,0 @@
-
-
-
-
-
-
-alert(\'Signed up successfully\')' &&
- header ('Location: ../index.php');
- }
-}
- if($temp)
- {
- echo '';
- }
-?>
-
-
>
-
-
diff --git a/src/userdata.txt b/src/userdata.txt
deleted file mode 100644
index b44adea..0000000
--- a/src/userdata.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-sdfdsf||sdfdsf
-1||1
-4||4
-42
\ No newline at end of file
diff --git a/view/.gitignore b/view/.gitignore
new file mode 100644
index 0000000..e69de29
diff --git a/view/404.php b/view/404.php
new file mode 100644
index 0000000..23a5126
--- /dev/null
+++ b/view/404.php
@@ -0,0 +1,14 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/view/enter.php b/view/enter.php
new file mode 100644
index 0000000..4bc3ea4
--- /dev/null
+++ b/view/enter.php
@@ -0,0 +1,89 @@
+
+
+
+