This commit is contained in:
2018-10-17 11:14:36 +03:00
parent 75a35947e5
commit 04d60d7e2c
2716 changed files with 431449 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
<?php
/*
*
*/
function __autoload($class_name){
$array_path = array(
'/models/',
'/controllers/',
'/components/'
);
foreach ($array_path as $path){
$path = ROOT . $path . $class_name . '.php';
if (is_file($path)){
include_once $path;
}
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Date
*
* @author adm_azashchepkin
*/
class Date {
//put your code here
public static function changeDateToUnix($date){
$arr_date = explode("-", $date);
$U_date = mktime(0,0,0,$arr_date[0],$arr_date[1],$arr_date[2]);
return $U_date;
}
public static function changeLocaleDate($date){
$translate = array(
"am" => "дп",
"pm" => "пп",
"AM" => "ДП",
"PM" => "ПП",
"Monday" => "Понедельник",
"Mon" => "Пн",
"Tuesday" => "Вторник",
"Tue" => "Вт",
"Wednesday" => "Среда",
"Wed" => "Ср",
"Thursday" => "Четверг",
"Thu" => "Чт",
"Friday" => "Пятница",
"Fri" => "Пт",
"Saturday" => "Суббота",
"Sat" => "Сб",
"Sunday" => "Воскресенье",
"Sun" => "Вс",
"January" => "Января",
"Jan" => "Янв",
"February" => "Февраля",
"Feb" => "Фев",
"March" => "Марта",
"Mar" => "Мар",
"April" => "Апреля",
"Apr" => "Апр",
"May" => "Мая",
"May" => "Мая",
"June" => "Июня",
"Jun" => "Июн",
"July" => "Июля",
"Jul" => "Июл",
"August" => "Августа",
"Aug" => "Авг",
"September" => "Сентября",
"Sep" => "Сен",
"October" => "Октября",
"Oct" => "Окт",
"November" => "Ноября",
"Nov" => "Ноя",
"December" => "Декабря",
"Dec" => "Дек",
"st" => "ое",
"nd" => "ое",
"rd" => "е",
"th" => "ое"
);
return strtr($date, $translate);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 14.04.16
* Time: 18:33
*/
class Db{
public static function getConnection(){
$paramsPath = ROOT.'/config/db_params.php';
$params = include($paramsPath);
$dsn = "mysql:host={$params['host']};dbname={$params['dbname']}";
$db = new PDO($dsn, $params['user'], $params['password']);
$db->exec('SET NAMES utf8'); //задаём кодировку ввода/вывода БД
return $db;
}
}
?>
+28
View File
@@ -0,0 +1,28 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Icecast
*
* @author adm_azashchepkin
*/
class Icecast {
public static function getConnection(){
$paramsPath = ROOT.'/config/icecast.php';
$params = include($paramsPath);
$radio = [];
$radio['host'] = $params['icecast_host']; // Сервер, на котором висит Icecast
$radio['ip'] = $params['icecast_ip']; // Сервер, на котором висит Icecast
$radio['port'] = $params['icecast_port']; // Порт
return $radio;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Images
*
* @author adm_azashchepkin
*/
class Images {
//put your code here
public static function uploadImg(){
if (!copy($_FILES['img']['tmp_name'], ROOT.IMG_PRN.$_FILES['img']['name']))
echo 'Error upload image';
else
return IMG_PRN.$_FILES['img']['name'];
}
public static function updatePrintImg($id_prn, $link_img){
//формирование запроса и обновление данных в базе
$db = Db::getConnection();
//внесение денных об изменениях принтера в бд
$stmt = $db->prepare("UPDATE print set img=:img WHERE id = :id");
$stmt->bindParam(':id', $id_prn, PDO::PARAM_INT);
$stmt->bindParam(':img', $link_img);
return $stmt->execute();
}
public static function checkAndDeleteImg($id_prn){
$info_prn = Printer::getPrintByIDFullData($id_prn);
if(!$info_prn['img'] == ""){
$filename = $info_prn['img'];
rename(ROOT.$filename, ROOT.$filename."_old"); //переименование старого изображения
//unlink(ROOT.$filename); //удаление старого изображения
//echo $info_prn['img'];
//echo ROOT.$filename."old";
//var_dump($info_prn['img']);
return true;
}else return true;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Ldap
*
* @author azashchepkin
*/
class Ldap {
/*
public function __construct() {
$this->ldaphost = LDAP_HOST;
$this->ldapport = LDAP_PORT;
$this->base = LDAP_BASE;
$this->filter = LDAP_FILTER;
$this->domain = LDAP_DOMAIN;
}*/
//put your code here
public static function LdapAuth($username, $pass){
$paramsPath = ROOT.'/config/ldap_config.php';
$params = include($paramsPath);
$login = $username.$params['ldap_domain'];
$password = $pass;
//подсоединяемся к LDAP серверу
$ldap = ldap_connect($params['ldap_host'], $params['ldap_port']) or die("Cant connect to LDAP Server");
//Включаем LDAP протокол версии 3
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($ldap){
// Пытаемся войти в LDAP при помощи введенных логина и пароля
$bind = ldap_bind($ldap,$login,$password);
if ($bind)
{
// Проверим, является ли пользователь членом указанной группы.
$result = ldap_search($ldap,$params['ldap_base'],$params['ldap_filter'].$username);//"(||(memberOf=".$memberof.")(".$filter.$username."))"
// Получаем количество результатов предыдущей проверки
$result_ent = ldap_get_entries($ldap,$result);
//return $result_ent;
}
else
{
return ('Вы ввели неправильный логин или пароль. попробуйте еще раз<br /> <a href="index.php">Вернуться назад</a>');
}
}
// Если пользователь найден, то пропускаем его дальше и перебрасываем на main.php
if ($result_ent['count'] != 0)
{
$_SESSION['user_id'] = $username;
$_SESSION['name_en'] = $result_ent[0]['cn'][0];
$_SESSION['name'] = $result_ent[0]['extensionattribute1'][0];
$_SESSION['surname'] = $result_ent[0]['extensionattribute2'][0];
$_SESSION['middle_name'] = $result_ent[0]['extensionattribute3'][0];
$_SESSION['full_name'] = $result_ent[0]['extensionattribute4'][0];
$_SESSION['city'] = $result_ent[0]['l'][0];
$_SESSION['position'] = $result_ent[0]['title'][0];
$_SESSION['department'] = $result_ent[0]['extensionattribute7'][0];
$_SESSION['mail'] = $result_ent[0]['mail'][0];
$_SESSION['phone'] = $result_ent[0]['telephonenumber'][0];
$_SESSION['georol'] = $result_ent[0]['renaissancegeorole'][0];
$_SESSION['photo'] = $result_ent[0]['jpegphoto'][0];
/*Фото из ad
$photo = $result_ent[0]['jpegphoto'][0];
$img = imagecreatefromstring($photo);
header("Content-type: image/jpeg");
imagejpeg($img,NULL,100);
echo "<img src=/index.php />";
echo "<pre>";
var_dump($result_ent);
echo "</pre>";*/
//header('Location: main.php');
//exit;
}
else
{
die('К сожалению, вам доступ закрыт<br /> <a href="index.php">Вернуться назад</a>');
}
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Mail
*
* @author adm_azashchepkin
*/
class Mail {
//put your code here
public static function getOrderCartriges($list_print, $from){
//
$message = '<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Заказ картриджей</title>
</head>
<body>
<p>Добрый день.<br />
КБ «Ренессанс Кредит» (ООО)<br />
Адрес: г. Курск, ул. Радищева 5.<br />
Необходимы картриджи для: </p>
<p>';
for($i=0; $i < count($list_print); $i++){
if($list_print[$i]['is_color'] == 1){
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (black) (2 шт.)<br />";
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (blue) (2 шт.)<br />";
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (yellow) (2 шт.)<br />";
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (magenta) (2 шт.)<br />";
}else $message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (2 шт.)<br />";
}
$message .= '</p><p>График работы: Пн-Пт. 9:00 - 18:00. <br />
Контактные номера: <br />
Захаренко Евгений <br />
+7 (495) 783-46-00 доб. 15015 <br />
Защепкин Андрей <br />
+7 (495) 783-46-00 доб. 15000 <br />
Галин Владислав <br />
+7 (495) 783-46-00 доб. 15025 </p>
';
$ord = self::getMail('Заказ картриджей', $message, $from);
(!$ord) ? $mess = "don't geting" : $mess = "OK";
return $mess;
}
private static function getMail($subject, $message, $from){
$paramsPath = ROOT.'/config/unit_information.php';
$params = include($paramsPath);
// отправка нескольким адресатам
$to = $params['email_support'] . ', '; // кому отправляем
//$to .= 'friend2@yourmail.ru' . ', '; // Внимание! Так пишем второй и тд адреса
// не забываем запятую. Даже в последнем контакте лишней не будет
// Для начинающих! $to .= точка в этом случае для Дописывания в переменную
// содержание письма
/*$subject = "Тема сообщения";
$message = '
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Тема страницы</title>
</head>
<body>
<p>А здесь ваше сообщение</p>
</body>
</html>';*/
// устанавливаем тип сообщения Content-type, если хотим
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8 \r\n";
// дополнительные данные
$headers .= "From: ".$from['name']." <".$from['email'].">\r\n"; // от кого
$headers .= "Cc: #ITKursk@rencredit.ru" . "\r\n"; // копия сообщения на этот адрес
//$headers .= "Bcc: yournick-archive@yourmail.ru\r\n"; // скрытая копия сообщения на этот
mail($to, $subject, $message, $headers);
}
public static function getLinkOrd($list_print){
$paramsPath = ROOT.'/config/unit_information.php';
$params = include($paramsPath);
// отправка нескольким адресатам
$to = $params['email_support']; // кому отправляем
$message = "КБ «Ренессанс Кредит» (ООО)%0aАдрес: г. Курск, ул. Радищева 5.%0aНеобходимы картриджи для:%0a%0a";
for($i=0; $i < count($list_print); $i++){
if($list_print[$i]['is_color'] == 1){
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (black) (2 шт.)%0a";
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (blue) (2 шт.)%0a";
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (yellow) (2 шт.)%0a";
$message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (magenta) (2 шт.)%0a";
}else $message .= "".$list_print[$i]['model']." ".$list_print[$i]['unit']." (2 шт.)%0a";
}
$message .= "%0aГрафик работы: Пн-Пт. 9:00 - 18:00.%0aКонтактные номера:%0aЗахаренко Евгений%0a+7 (495) 783-46-00 доб. 15015%0aЗащепкин Андрей%0a+7 (495) 783-46-00 доб. 15000%0aГалин Владислав%0a+7 (495) 783-46-00 доб. 15025";
$ord = self::getLinkMail("Заказ картриджей", $message, $to);
//(!$ord) ? $mess = "don't geting" : $mess = "OK";
return $ord;
}
public static function getRequests($print_id, $description){
$paramsPath = ROOT.'/config/unit_information.php';
$params = include($paramsPath);
$print = Printer::getPrintByID($print_id);
// отправка нескольким адресатам
$to = $params['email_support']; // кому отправляем
$message = "КБ «Ренессанс Кредит» (ООО)%0aАдрес: г. Курск, ул. Радищева 5.%0a%0a";
$message .= "Проблемы с принтером ".$print['model']." ".$print['unit'].". ".$description."%0a";
$message .= "%0aГрафик работы: Пн-Пт. 9:00 - 18:00.%0aКонтактные номера:%0aЗахаренко Евгений%0a+7 (495) 783-46-00 доб. 15015%0aЗащепкин Андрей%0a+7 (495) 783-46-00 доб. 15000%0aГалин Владислав%0a+7 (495) 783-46-00 доб. 15025";
$request = self::getLinkMail("Проблемы с принтером ".$print['model']." ".$print['unit'], $message, $to);
//(!$ord) ? $mess = "don't geting" : $mess = "OK";
return $request;
}
private static function getLinkMail($subject, $body, $to){
$subject = "?subject=".$subject;
$body = "&body=".$body;
$cc = "&cc=%23ITKursk%40rencredit.ru";
$link = "<a href='mailto:".$to.$subject.$body.$cc."'>Link</a>";
return $link;
}
}
/*array(13) {
["link"]=>
string(30) "http://prints.local/cartriges/"
["user_id"]=>
string(12) "azashchepkin"
["name_en"]=>
string(19) "Zashchepkin, Andrey"
["name"]=>
string(16) "Защепкин"
["surname"]=>
string(12) "Андрей"
["middle_name"]=>
string(26) "Александрович"
["full_name"]=>
string(56) "Защепкин Андрей Александрович"
["city"]=>
string(10) "Курск"
["position"]=>
string(62) "Специалист технической поддержки"
["department"]=>
string(60) "Отдел информационных технологий"
["mail"]=>
string(25) "azashchepkin@rencredit.ru"
["phone"]=>
string(5) "15000"
["georol"]=>
string(16) "GR.RC.Курск"
}*/
+196
View File
@@ -0,0 +1,196 @@
<?php
/*
* Класс для генерации постраничной навигации
*/
class Pagination
{
/**
*
* @var Ссылок навигации на страницу
*
*/
private $max = 10;
/**
*
* @var Ключ для GET, в который пишется номер страницы
*
*/
private $index = 'page';
/**
*
* @var Текущая страница
*
*/
private $current_page;
/**
*
* @var Общее количество записей
*
*/
private $total;
/**
*
* @var Записей на страницу
*
*/
private $limit;
/**
* Запуск необходимых данных для навигации
* @param integer $total - общее количество записей
* @param integer $limit - количество записей на страницу
*
* @return
*/
public function __construct($total, $currentPage, $limit, $index)
{
# Устанавливаем общее количество записей
$this->total = $total;
# Устанавливаем количество записей на страницу
$this->limit = $limit;
# Устанавливаем ключ в url
$this->index = $index;
# Устанавливаем количество страниц
$this->amount = $this->amount();
# Устанавливаем номер текущей страницы
$this->setCurrentPage($currentPage);
}
/**
* Для вывода ссылок
*
* @return HTML-код со ссылками навигации
*/
public function get()
{
# Для записи ссылок
$links = null;
# Получаем ограничения для цикла
$limits = $this->limits();
$html = '<ul class="pagination">';
# Генерируем ссылки
for ($page = $limits[0]; $page <= $limits[1]; $page++) {
# Если текущая это текущая страница, ссылки нет и добавляется класс active
if ($page == $this->current_page) {
$links .= '<li class="active"><a href="#">' . $page . '</a></li>';
} else {
# Иначе генерируем ссылку
$links .= $this->generateHtml($page);
}
}
# Если ссылки создались
if (!is_null($links)) {
# Если текущая страница не первая
if ($this->current_page > 1)
# Создаём ссылку "На первую"
$links = $this->generateHtml(1, '&lt;') . $links;
# Если текущая страница не первая
if ($this->current_page < $this->amount)
# Создаём ссылку "На последнюю"
$links .= $this->generateHtml($this->amount, '&gt;');
}
$html .= $links . '</ul>';
# Возвращаем html
return $html;
}
/**
* Для генерации HTML-кода ссылки
* @param integer $page - номер страницы
*
* @return
*/
private function generateHtml($page, $text = null)
{
# Если текст ссылки не указан
if (!$text)
# Указываем, что текст - цифра страницы
$text = $page;
$currentURI = rtrim($_SERVER['REQUEST_URI'], '/') . '/';
$currentURI = preg_replace('~/page-[0-9]+~', '', $currentURI);
# Формируем HTML код ссылки и возвращаем
return
'<li><a href="' . $currentURI . $this->index . $page . '">' . $text . '</a></li>';
}
/**
* Для получения, откуда стартовать
*
* @return массив с началом и концом отсчёта
*/
private function limits()
{
# Вычисляем ссылки слева (чтобы активная ссылка была посередине)
$left = $this->current_page - round($this->max / 2);
# Вычисляем начало отсчёта
$start = $left > 0 ? $left : 1;
# Если впереди есть как минимум $this->max страниц
if ($start + $this->max <= $this->amount)
# Назначаем конец цикла вперёд на $this->max страниц или просто на минимум
$end = $start > 1 ? $start + $this->max : $this->max;
else {
# Конец - общее количество страниц
$end = $this->amount;
# Начало - минус $this->max от конца
$start = $this->amount - $this->max > 0 ? $this->amount - $this->max : 1;
}
# Возвращаем
return
array($start, $end);
}
/**
* Для установки текущей страницы
*
* @return
*/
private function setCurrentPage($currentPage)
{
# Получаем номер страницы
$this->current_page = $currentPage;
# Если текущая страница боле нуля
if ($this->current_page > 0) {
# Если текунщая страница меньше общего количества страниц
if ($this->current_page > $this->amount)
# Устанавливаем страницу на последнюю
$this->current_page = $this->amount;
} else
# Устанавливаем страницу на первую
$this->current_page = 1;
}
/**
* Для получеия общего числа страниц
*
* @return число страниц
*/
private function amount()
{
# Делим и возвращаем
return round($this->total / $this->limit);
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
class Router{
private $routes;
public function __construct(){
$routerPath = ROOT.'/config/routes.php';
$this->routes = require($routerPath);
}
/*
* return request string
*/
private function getURI(){
if(!empty($_SERVER['REQUEST_URI'])){
return trim($_SERVER['REQUEST_URI'], '/');
}
}
public function run(){
//получить строку запроса
$uri = $this->getURI();
//проверить наличие запроса в routes.php
foreach($this->routes as $uriPattern => $path){
//сравниваем $urlPattern и $url
if(preg_match("~$uriPattern~", $uri)){
//получаем внутренний путь из внешнего согласно правилу
$internalRoute = preg_replace("~$uriPattern~", $path, $uri);
//определить контлоллер, экшен и параметры
$segments = explode('/', $internalRoute);
$controllerName = array_shift($segments).'Controller';
$controllerName = ucfirst($controllerName);
$actionName = 'action'.ucfirst(array_shift($segments));
$parameters = $segments;
//подключить файл класса контроллера
$controllerFile = ROOT.'/controllers/'.$controllerName.'.php';
if(file_exists($controllerFile)){
include_once ($controllerFile);
}
$controllerObject = new $controllerName;
if(!method_exists($controllerObject,$actionName)) {
$er = $uri;
require_once (ROOT . TMPL . 'error.php');
return true;
};
$result = call_user_func_array(array($controllerObject, $actionName),$parameters);
if($result != null){
break;
}
}
}
}
}