Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
**/node_modules/
**.DS_Store
**/.vs/
**/dist/
**/.idea
**/node_modules/
**.DS_Store
**/.vs/
**/dist/
**/.idea
**/.sublime-project
**/.sublime-workspace
**/_log
23 changes: 23 additions & 0 deletions config/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php
define('ROOT', dirname(__DIR__));
define('IMG_BIG', $_SERVER['DOCUMENT_ROOT'] . '/images/gallery_img/big/');
define('IMG_SMALL', $_SERVER['DOCUMENT_ROOT'] . '/images/gallery_img/small/');
define('TEMPLATES_DIR', ROOT . '/templates/');
define('LAYOUTS_DIR', 'layouts/');

/* DB config */
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', 'root');
define('DB', 'php1');

include ROOT . "/engine/db.php";
include ROOT . "/engine/functions.php";
include ROOT . "/engine/log.php";
include ROOT . "/engine/gallery.php";
include ROOT . "/engine/catalog.php";
include ROOT . "/engine/calculator.php";
include ROOT . "/engine/classSimpleImage.php";
include ROOT . "/engine/feedback.php";
include ROOT . "/engine/auth.php";
include ROOT . "/engine/service.php";
264 changes: 264 additions & 0 deletions data/php1.sql

Large diffs are not rendered by default.

53 changes: 53 additions & 0 deletions engine/auth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

if (isset($_POST['auth'])) {
$login = $_POST['login'];
$password = $_POST['password'];
if (!auth($login, $password)) {
$_GET['authError'] = "Неверный логин/пароль!";
} else {
if (isset($_POST['cookie'])) {
/** @var Stringable $hash */
$hash = uniqid(rand(), true);
$id = (INT)$_SESSION['id'];
executeQuery("UPDATE `users` SET `hash` = '{$hash}' WHERE id = {$id}");
setcookie("hash", $hash, time() + 36000, '/');
}

header("Location:" . $_SERVER["HTTP_REFERER"]);
}

}

function auth($login, $password):bool {
$login = mysqli_real_escape_string(getDb(), strip_tags(stripcslashes($login)));
$passDb = getAssocResult("SELECT * FROM `users` WHERE login = '{$login}'")[0];

if (password_verify($password, $passDb['password'])) {
$_SESSION['login'] = $login;
$_SESSION['id'] = $passDb['id'];
return true;
}
return false;
}

function isAuth():bool {
if (isset($_COOKIE['hash']) && !isset($_SESSION['login'])) {
$hash = $_COOKIE['hash'];
$user = getAssocResult("SELECT * FROM `users` WHERE `hash` = '{$hash}'")[0]['login'];
if (!empty($user)) {
$_SESSION['login'] = $user;
}
}
return isset($_SESSION['login']);
}

function getUser() {
return $_SESSION['login'];
}

if (isset($_GET['logout'])) {
session_destroy();
setcookie('hash', '', time() - 36000, '/');
header('Location: /');
}
44 changes: 44 additions & 0 deletions engine/calculator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

function parseOperations($str) {

if(strlen($str) < 3) return $str;

$operations = [
'+' => 'sum',
'-' => 'sub',
'*' => 'mul',
'/' => 'div'
];

$arg1 = preg_split('/[\+\-\*\/]+/', $str)[0];
$arg2 = preg_split('/[\+\-\*\/]+/', $str)[1];
$operation = preg_split('/[^\+\-\*\/]+/', $str)[1];

return mathOperation($arg1, $arg2, $operations[$operation]);
}

function sum($arg1, $arg2){
return $arg1 + $arg2;
}

function sub($arg1, $arg2){
return $arg1 - $arg2;
}

function mul($arg1, $arg2){
return $arg1 * $arg2;
}

function div($arg1, $arg2){
if($arg2 == 0) {
return 'Ошибка! На ноль делить нельзя.';
}
return $arg1 / $arg2;
}

function mathOperation($arg1, $arg2, $operation){
if(function_exists($operation)){
return $operation($arg1, $arg2);
}
}
103 changes: 103 additions & 0 deletions engine/catalog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php
function getCatalog():array {
return getAssocResult("SELECT * FROM `catalog`");
}

function getOneGood($id){
return getAssocResult("SELECT * FROM `catalog` WHERE id = {$id}")[0];
}

function cartAction($action, $session_id) {
$id = (INT)$_GET['id'];
switch ($action) {
case 'add':
echo json_encode(
[
'added' => addToCart($id, $session_id),
'count' => getAllCartItemsCount($session_id),
'total' => getTotalPrice(getCart($session_id))
]
);
break;

case 'delete':
echo json_encode(
[
'deleted' => deleteFromCart($id, $session_id),
'count' => getAllCartItemsCount($session_id),
'total' => getTotalPrice(getCart($session_id))
]
);
break;

case 'checkout':

echo json_encode(
[
'ordered' => makeAnOrder($session_id),
]
);
break;
}
die();
}

function makeAnOrder($session_id):bool {
$result = json_decode(file_get_contents('php://input'));
executeQuery("UPDATE `cart` SET `cart_status` = 1 WHERE session_id = '{$session_id}'");
return executeQuery("INSERT INTO `orders` (name, number, mail, session_id) VALUES ('{$result->name}', '{$result->number}', '{$result->email}', '{$session_id}')");
}

function getCart($session_id):array {

$cart = getAssocResult("SELECT cart.id cart_id, catalog.image, catalog.id catalog_id, catalog.name, catalog.price FROM cart, catalog WHERE cart.good_id=catalog.id AND session_id = '{$session_id}' AND cart_status = 0");

$each = getEachCartItemsCount($session_id);

$tmp = [];
$unique = [];

foreach ($cart as $good) {
if (!in_array($good['catalog_id'], $tmp)) {
$unique[] = $good;
$tmp[] = $good['catalog_id'];
}
}

function replace($a, $b) {
if ($a['catalog_id'] === $b['catalog_id']) {
$a['count'] = $b['count'];
}

$a['sub_total'] = (INT)str_replace(' ', '', $a['price']) * $b['count'];
return $a;
}

return array_map('replace', $unique, $each);
}

function getAllCartItemsCount($session_id):string {
return getAssocResult("SELECT COUNT(id) as count FROM `cart` WHERE `session_id`='{$session_id}' AND cart_status = 0")[0]['count'];
}

function getEachCartItemsCount($session_id):array {
// $sql = "SELECT `catalog`.id AS good_id, SUM(`catalog`.price) AS total FROM `cart` INNER JOIN `catalog` ON `catalog`.id = `cart`.good_id GROUP BY `cart`.id";
return getAssocResult("SELECT `good_id` AS `catalog_id` , COUNT(`good_id`) AS count FROM `cart` WHERE `session_id` = '$session_id' AND cart_status = 0 GROUP BY (good_id)");
}

function getTotalPrice($cart) {
$total = 0;
foreach ($cart as $item) {
$total += $item['sub_total'];
}
return $total;
}

function addToCart($id, $session_id):bool {
$sql = "INSERT INTO `cart` (good_id, session_id) VALUES ($id, '$session_id')";
return executeQuery($sql);
}

function deleteFromCart($good_id, $session_id):bool {
return executeQuery("DELETE FROM `cart` WHERE good_id = '{$good_id}' AND session_id = '{$session_id}' AND cart_status = 0 LIMIT 1");
}
85 changes: 85 additions & 0 deletions engine/classSimpleImage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/

class SimpleImage {

var $image;
var $image_type;

function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
41 changes: 41 additions & 0 deletions engine/db.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* Функция, осуществляющая соединение с базой данных и возвращающее его
* static позволяет сохранить состояние и вернуть уже текущее соединение
* чтобы не делать нового
*/
function getDb(){
static $db = null;

if(is_null($db)){
$db = @mysqli_connect(HOST, USER, PASS, DB) or die('Could not connect: ' . mysqli_connect_error());
}
return $db;
}

/*
* Обертка для выполнения запроса на получение данных
* Данные возвращаются в виде ассоциативного массива
* Цикл по получению данных уже реализован в этой функции
*/
function getAssocResult($sql):array{
$result = @mysqli_query(getDb(), $sql) or die(mysqli_error(getDb()));
$array_result = [];
while ($row = mysqli_fetch_assoc($result)) {
$array_result[] = $row;
}

return $array_result;
}

/*
* Обертка для выполнения любого запроса.
* Передаем в параметре текст sql-запроса.
* Возвращаем результат,
* в виде логического значения (выполнился/не выполнился) запрос.
*/
function executeQuery($sql):bool{
@mysqli_query(getDb(), $sql) or die(mysqli_error(getDb()));
return !(mysqli_affected_rows(getDb()) === 0);
}
Loading