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
20 changes: 20 additions & 0 deletions config/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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/catalog.php";
include ROOT . "/engine/calculator.php";
include ROOT . "/engine/classSimpleImage.php";
include ROOT . "/engine/feedback.php";
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);
}
}
48 changes: 48 additions & 0 deletions engine/catalog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
function getCatalog():array{
return getAssocResult("SELECT * FROM `catalog` ORDER BY views DESC");
}

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

function addLikes($id){
executeQuery("UPDATE `catalog` SET views = views + 1 WHERE id = {$id}");
}

function uploadImage():string{
$path_big = IMG_BIG . $_FILES['image']['name'];
$path_small = IMG_SMALL . $_FILES['image']['name'];

$image_info = getimagesize($_FILES['image']['tmp_name']);

if ($image_info['mime'] != 'image/png' && $image_info['mime'] != 'image/gif' && $image_info['mime'] != 'image/jpeg') {
return "Можно загружать только jpg/png/gif/jpeg - файлы";
}

if ($_FILES['image']['size'] > 1024 * 5 * 1024) {
return "Размер файла не более 5 Мб";
}

$blacklist = ['.php', '.phtml', '.php3', '.php4'];
foreach ($blacklist as $item) {
if(preg_match("/$item\$/i", $_FILES['image']['name'])){
return "Загрузка php-файлов запрещена";
}
}

if (move_uploaded_file($_FILES['image']['tmp_name'], $path_big)) {

$filename = mysqli_real_escape_string(getDb(), $_FILES['image']['name']);
executeQuery("INSERT INTO `catalog` (`filename`) VALUES ('{$filename}')");

$image = new SimpleImage();
$image->load($path_big);
$image->resizeToWidth(250);
$image->save($path_small);
header("Location: /catalog");
} else {
return "Ошибка ресайза файла";
}
}
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;
}
}
25 changes: 25 additions & 0 deletions engine/db.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

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;
}

function executeQuery($sql):bool{
@mysqli_query(getDb(), $sql) or die(mysqli_error(getDb()));
return !(mysqli_affected_rows(getDb()) === 0);
}
68 changes: 68 additions & 0 deletions engine/feedback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

function getAllFeedback():array{
$sql = "SELECT * FROM `feedback` ORDER BY id";
return getAssocResult($sql);
}

function feedbackAction($action = '') {
switch ($action) {
case 'create':
$data = readFeedback();
$id = createFeedback($data->name, $data->feedback);

$response = [
'id' => $id,
'name' => $data->name,
'feedback' => $data->feedback
];

echo json_encode($response, JSON_UNESCAPED_UNICODE);
break;

case 'read':
echo json_encode(getOneFeedback(), JSON_UNESCAPED_UNICODE);
break;

case 'update':
$data = readFeedback();
$response = updateFeedback($data);
echo json_encode(['updated' => $response]);
break;

case 'delete':
$data = json_decode(file_get_contents('php://input'));
$response = deleteFeedback($data);
echo json_encode(['deleted' => $response]);
break;
}
die();
}

function createFeedback($name, $feedback) {
$name = strip_tags(htmlspecialchars(mysqli_real_escape_string(getDb(), $name)));
$feedback = strip_tags(htmlspecialchars(mysqli_real_escape_string(getDb(), $feedback)));
$sql = "INSERT INTO `feedback` (`name`, `feedback`) VALUES ('{$name}', '{$feedback}');";
executeQuery($sql);
return mysqli_insert_id(getDb());
}

function readFeedback() {
return json_decode(file_get_contents('php://input'));
}

function updateFeedback($data):bool {
return executeQuery("UPDATE `feedback` SET `name` = '{$data->name}', `feedback` = '{$data->feedback}' WHERE `feedback`.`id` = {$data->id}");
}

function deleteFeedback($id):bool {
$id = (INT)$id;
return executeQuery("DELETE FROM `feedback` WHERE `feedback`.`id` = {$id}");
}

function getOneFeedback():array {
$id = (INT)json_decode(file_get_contents('php://input'));
$sql = "SELECT * FROM feedback WHERE id = {$id}";
return getAssocResult($sql)[0];

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

function prepareVariables($page, $action):array{
$params['layout'] = 'main';
switch ($page) {

case 'image':
$params['layout'] = 'catalog';
$params['image'] = getOneImage((int)$_GET['id']);
break;

case 'addLike':
$params['layout'] = 'catalog';
addLikes((int)$_GET['id']);
break;

case 'catalog':
if(isset($_POST['load'])){
$params['errors'] = uploadImage();
}
$params['layout'] = 'catalog';
$params['catalog'] = getCatalog();
break;

case 'feedback':
$params['layout'] = 'feedback';
$params['feedback'] = getAllFeedback();
break;

case 'feedbackapi':
feedbackAction($action);
break;

case 'calculator':
if (!empty($_POST['output'])) {
$params['output'] = parseOperations($_POST['output']);
}
$params['layout'] = 'calculator';
break;

case 'homework_3':
$params['layout'] = 'homework_3';
break;
}
return $params;
}

function render($page, $params){
return renderTemplate(LAYOUTS_DIR . $params['layout'], [
'content' => renderTemplate($page, $params),
'menu' => renderTemplate('menu', $params),
]
);
}

function renderTemplate($page, $params = []){
ob_start();

if (!is_null($params))
extract($params);

$fileName = TEMPLATES_DIR . $page . ".php";

if (file_exists($fileName)) {
include $fileName;
} else {
Die("Страницы {$fileName} не существует.");
}

return ob_get_clean();
}
Empty file added engine/log.php
Empty file.
Loading