Загрузка списка папок и файлов

parent 62928ae0
.idea
composer.phar
vendor/
src/public/fotos/
...@@ -21,7 +21,7 @@ return [ ...@@ -21,7 +21,7 @@ return [
$acl->deny(null, null); $acl->deny(null, null);
// Admin // Admin
$acl->allow(Roles::ROLE_ADMIN, 'adm.supports') $acl->allow(Roles::ROLE_ADMIN, 'adm.pairs')
->allow(Roles::ROLE_ADMIN, 'adm.index') ->allow(Roles::ROLE_ADMIN, 'adm.index')
; ;
......
...@@ -56,6 +56,13 @@ return [ ...@@ -56,6 +56,13 @@ return [
$container $container
); );
}, },
App\Action\Admin\Main::class => function (ContainerInterface $container) {
return new \App\Action\Admin\Main(
$container->get(\Zend\Expressive\Router\RouterInterface::class),
$container->get(\Zend\Expressive\Template\TemplateRendererInterface::class),
$container
);
},
App\Action\Admin\Init::class => function (ContainerInterface $container) { App\Action\Admin\Init::class => function (ContainerInterface $container) {
return new \App\Action\Admin\Init( return new \App\Action\Admin\Init(
$container->get(\Zend\Expressive\Router\RouterInterface::class), $container->get(\Zend\Expressive\Router\RouterInterface::class),
...@@ -82,6 +89,36 @@ return [ ...@@ -82,6 +89,36 @@ return [
] ]
], ],
], ],
[
'name' => 'adm.main.save',
'path' => '/[:lang/]support/main/save/',
'middleware' => App\Action\Admin\Main::class,
'allowed_methods' => ['POST', 'GET'],
'options' => [
'constraints' => [
'lang' => '[a-z]{2,3}',
],
'defaults' => [
'lang' => \App\Model\Locales::DEFAULT_LANG_ADMIN,
'action' => App\Action\Admin\Main::SAVE_FOLDERS,
]
],
],
[
'name' => 'adm.main.loadfolder',
'path' => '/[:lang/]support/main/loadfolder/',
'middleware' => App\Action\Admin\Main::class,
'allowed_methods' => ['POST', 'GET'],
'options' => [
'constraints' => [
'lang' => '[a-z]{2,3}',
],
'defaults' => [
'lang' => \App\Model\Locales::DEFAULT_LANG_ADMIN,
'action' => App\Action\Admin\Main::LOAD_FOLDER,
]
],
],
[ [
'name' => 'adm.init', 'name' => 'adm.init',
'path' => '/[:lang/]support/init/', 'path' => '/[:lang/]support/init/',
...@@ -125,8 +162,8 @@ return [ ...@@ -125,8 +162,8 @@ return [
], ],
], ],
[ [
'name' => 'adm.supports', 'name' => 'adm.pairs',
'path' => '/[:lang/]support/supports/', 'path' => '/[:lang/]support/pairs/',
'middleware' => App\Action\Admin\Supports::class, 'middleware' => App\Action\Admin\Supports::class,
'allowed_methods' => ['POST', 'GET'], 'allowed_methods' => ['POST', 'GET'],
'options' => [ 'options' => [
......
<?php
return [
'serverdata' => [
// ssp_conf
'ssp' => array(
'providers' => ['admixer', 'admixer_vip', 'marketgid', 'ndsp', 'trafmag'],
),
// dsp_conf
'dsp' => array(
'providers' => ['marketgid_click', 'mixadvert_click', 'recreativ_click'],
'config_names' => array(
'marketgid_click' => array(
'only_goods' => 'только товары',
'elite' => 'elite',
)
)
),
]
];
This diff is collapsed.
/*!
* Bootstrap Reboot v4.5.3 (https://getbootstrap.com/)
* Copyright 2011-2020 The Bootstrap Authors
* Copyright 2011-2020 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus:not(:focus-visible){outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([class]){color:inherit;text-decoration:none}a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto;-ms-overflow-style:scrollbar}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit;text-align:-webkit-match-parent}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.min.css.map */
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
$(document).ready(function(){
var linkToFileLinerChart; // Адресс с данными для графика линейной диаграммы
//******************** Счетчик *************************************
var $counterBlock = $('.b-content__counter-digits');
var startDigits = 540220.00;
var stopDigits = 540248.00;
var widthWindow;
var heightWindow;
// Стратовый плагин счетчика
var easingFn = function (t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
}
var optionsTop = {
  useEasing : true,
  easingFn: easingFn,
  useGrouping : false,
  separator : ',',
  decimal : ',',
  prefix : '',
  suffix : '',
print : false
};
var topTitle = new CountUp($counterBlock, startDigits, stopDigits, 2, 3, optionsTop);
topTitle.start();
var isStart;
// Отследить окончание работы стартового счетчика
var loadCount = setTimeout(function runCount() {
isStart = topTitle.ending;
if(isStart) {
stopTimer();
} else {
setTimeout(runCount, 500);
}
}, 500);
// Стоп таймер отслеживания стартового счетчика и запуск постоянно работающего
function stopTimer() {
clearTimeout(loadCount);
var str = topTitle.outResult;
// var number = parseToNumber(str);
// number = Math.round((number + 1)*100)/100;
// str = parseToString(number);
// startRender($counterBlock, str);
countTimer(str);
}
// Постоянно работающий счетчик
function countTimer(number){
var nowNumber = topTitle.outResult;
nowNumber = parseToNumber(number);
var loadCount = setTimeout(function runTimer() {
nowNumber = Math.round((nowNumber + 1)*100)/100;
startRender($counterBlock, parseToString(nowNumber));
setTimeout(runTimer, 500);
}, 500);
}
// Вывод результата на экран
function startRender(el, number) {
var $target = el.children('p');
$target.remove();
var array;
array = String(number).split('');
for(i = 0 ; i < array.length ; i++) {
var str = '<p>' + array[i] + '</p>';
$(el).append(str);
}
}
// Преобразование числа в строку
function parseToString(number) {
var array = String(number).split('');
var str = '';
var index = 0;
for(i = 0; i < array.length; i++) {
if(index != 0) {
index++;
}
if(array[i] == '.') {
array[i] = ',';
index = 1;
}
str += array[i];
}
// Если были нули после заптой
if(index == 0) {
str += ',00';
}
if(index == 1) {
str += '00';
}
if(index == 2) {
str += '0';
}
return str;
}
// Преобразование строки в число
function parseToNumber(str) {
var array = str.split('');
var number = '';
for(i = 0; i < array.length; i++) {
if(array[i] == ',') {
array[i] = '.';
}
number += array[i];
}
return +number;
}
// *********** /Счетчик *********************************
// *********** График установки блокировщиков ***********
var isAniamtionChartsLine = true;
// Стартовая загрузка графиков / перерисовка при изменении размера экрана
$(window).on('resize orientationchange', function(){
var widthWindow = window.outerWidth;
var heightWindow = window.outerHeight;
var widthWrapp = document.getElementsByClassName('b-content__contact-statistics')[0].offsetWidth;
// $('#chart-line').attr("max-width", widthWrapp-40);
// $('#chart-line').attr("max-height", 370);
loadDataLineChart(linkToFileLinerChart); // Отрисовка линейной диаграммы
});
// Отрисовка и загрузка данных линейного графика
function loadDataLineChart(linkFile){
$.ajax(linkFile, {
type: 'GET',
dataType: 'json',
success: function(res) {
dataLineChart = res.slice();
var widthWindow = window.outerWidth;
var heightWindow = window.outerHeight;
var widthWrapp = document.getElementsByClassName('b-content__contact-statistics')[0].offsetWidth;
var heightCanvas;
heightCanvas = (window.outerWidth <= WIDTH_MOBILE_DEVICE) ? 150 : 200;
if(isCompactDevice) {
$('#chart-line').attr("max-width", widthWrapp-40);
$('#chart-line').attr("width", widthWrapp-40);
} else {
$('#chart-line').attr("max-width", widthWrapp);
$('#chart-line').attr("width", widthWrapp);
}
$('#chart-line').attr("max-height", heightCanvas);
chartsLine(dataLineChart, chartColorChanged, false, false, "#FDEBEA");
isAniamtionChartsLine = false;
},
error: function(req,status,err) {
console.log("Error " + req,status,err);
}
});
}
// Массив цветов линний для линейного графика
var colorLine = [
"rgba(220,220,220,1)",
"rgba(151,187,205,1)",
"rgba(179,179,179,1)"
]
var chartColorChanged = colorLine.slice(); // Дублирующий массив цветов линий
/*
Переключатели 'Фильтров':
В результате клика на элементе фильтра - навешивается класс "m-filter__switch-item_active",
значение выбранного элемента в переменной "resultCaregory"
*/
$('.b-filter__switch-item').on('click', function(){
$(this).siblings().removeClass('m-filter__switch-item_active');
$(this).addClass('m-filter__switch-item_active');
var currentAttr;
if($(this)[0].hasAttribute('data-filter-category')) {
currentAttr = 'data-filter-category';
}
resultCaregory = $(this).attr(currentAttr); // Выбранный вариант
switch(resultCaregory) {
case "year":
case "month":
case "week":
linkToFileLinerChart = dataSource[resultCaregory];
break;
}
loadDataLineChart(linkToFileLinerChart);
return false;
});
/*
При загрузке страницы проверить на наличие классов "m-filter__switch-item_active" на фильтрах, указывающих на то, какая сортировка, соответственно, имеющиие его пропустить
*/
$('.b-filter__switch').each(function(index,el){
if(!$(el).find('.b-filter__switch-item').hasClass('m-filter__switch-item_active')) {
$(el).find('.b-filter__switch-item').eq(0).trigger('click');
}
});
// *********** /График установки блокировщиков ***********
// *********** Cчетчик процетов *************************
if ($('.b-content__contact-percent').length) {
var optionsPercent = {
useEasing : true,
easingFn: easingFn,
useGrouping : false,
separator : ',',
decimal : ',',
prefix : '',
suffix : '%',
};
var percent = new CountUp($('.b-content__contact-percent')[0], 0, 33, 0, 2, optionsPercent);
$(window).on('load scroll', function(){
var $elem = (widthWindow > WIDTH_TABLET_DEVICE) ? $('.b-content__contact') : $('.b-content__contact-percent');
var distanseToBottom = $elem[0].getBoundingClientRect().bottom;
var distanseToTop = $elem[0].getBoundingClientRect().top;
if(distanseToBottom <= heightWindow && distanseToTop >= -10) {
percent.start();
}
});
}
// *********** /Cчетчик процетов *************************
$(window).on('load resize', function(){
widthWindow = $(window).width();
heightWindow = $(window).height();
});
});
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
$(document).ready(function(){
// Клик на папку для загрузки фотографий:
$('.b-list_folders-item').on('click', function(){
var
$foldersContent = $('.b-folder-content'),
$form = $('#load-folder-form'),
action = $form.attr('action'),
method = $form.attr('method'),
folderName = $(this).data('folder'),
data = {
folder: folderName
};
$foldersContent.hide();
if ($('.b-folder-content[data-folder="' + folderName + '"]').length>0) {
console.log('AAA отображаем');
$('.b-folder-content[data-folder="' + folderName + '"]').show();
} else {
console.log('AAA подгружаем');
$.ajax(action, {
type: method,
data: data,
success: function(data) {
//console.log('AAA success', data);
RenderFilesList(folderName, data);
},
error: function(rew, status, err) {
console.log(status, err);
}
});
}
return false;
});
// Клик на "Сохранить" для объявления:
$('.btn.btn-primary.save-folders').on('click', function(){
var
$form = $('#save-folders-form'),
action = $form.attr('action'),
method = $form.attr('method'),
data = {
type: 213
};
data.test = 123;
console.log('AAA data = ', data);
$.ajax(action, {
type: method,
data: data,
success: function(data) {
console.log('AAA success', data);
/*
if(data) {
if(data.result === true && data.redirect) {
document.location.href = data.redirect;
}
if(data.result === false && data.msg) {
$.showMessage('error', data.msg);
}
}
*/
},
error: function(rew, status, err) {
console.log(status, err);
}
});
return false;
});
function RenderFilesList(folderName, data)
{
// Добавляем содержимое папки:
console.log('AAA ', folderName, ' ', data);
var $foldersContentWrap = $('.b-preview');
var templateFolderContent = _.template('' +
'<div class="b-folder-content row" data-folder="<%= folder %>">' +
' <% _.each(files, function(item) { %> \n' +
' <div class="b-foto col-4" data-id="<%= item %>">' +
' <div class="b-foto_inner" style="background-image: url(/fotos/<%= folder %>/<%= item %>)"><%= item %></div>' +
' </div>' +
' <% }) %> \n' +
'</div>'
);
$foldersContentWrap.append(templateFolderContent({folder: folderName, files: data}));
}
});
\ No newline at end of file
This diff is collapsed.
...@@ -32,14 +32,6 @@ use Psr\Http\Message\ServerRequestInterface; ...@@ -32,14 +32,6 @@ use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse; use Zend\Diactoros\Response\HtmlResponse;
use Zend\Expressive\Template\TemplateRendererInterface; use Zend\Expressive\Template\TemplateRendererInterface;
use App\Model\Statistics;
use App\Model\Users;
use App\Model\Sites;
/*
use App\Model\Teasers\Offers;
use App\Model\Teasers\Adds;
use App\Model\Teasers\Partners;
*/
use App\Authentication\SupportService; use App\Authentication\SupportService;
/** /**
...@@ -52,207 +44,33 @@ class Index extends Common ...@@ -52,207 +44,33 @@ class Index extends Common
function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{ {
/** @var Sites $sitesModel */ chdir('public/fotos');
$sitesModel = $this->container->get(Sites::class); $dir = getcwd();
chdir('../..');
$folders = scandir($dir);
/** @var Statistics $stats */ foreach ($folders as $key=>$folder_name) {
$stats = $this->container->get(Statistics::class); if (strpos($folder_name, '.') > -1) {
unset($folders[$key]);
/** @var Users $usersModel */ }
$usersModel = $this->container->get(Users::class);
/** @var \App\Model\Supports $supportModel */
$supportModel = $this->container->get(\App\Model\Supports::class);
/** @var \App\Model\Countries $countryModel */
$countryModel = $this->container->get(\App\Model\Countries::class);
$countries = array();
foreach($countryModel->findAll() as $country) {
$countries[$country->getCode()] = $country->getName();
} }
/** @var SupportService $auth */ /** @var SupportService $auth */
/*
$auth = $this->container->get(SupportService::class); $auth = $this->container->get(SupportService::class);
$role = $auth->getIdentity()->getRoleId(); $role = $auth->getIdentity()->getRoleId();
if (in_array($role, ['admin'])) { if (in_array($role, ['admin'])) {
// Список сайтов админа
$adminSites = $sitesModel->findAllSites();
} else { } else {
// Список сайтов менеджера
$manager_id = $auth->getIdentity()->getId();
$manager_users = $usersModel->findBySupportId($manager_id);
$managerSites = $sitesModel->findByUserId($manager_users)->buffer();
$listDomains = array();
foreach($managerSites as $site) {
if (!in_array($site->getDomain(), $listDomains)) {
$listDomains[] = $site->getDomain();
}
} }
*/
$adminSites = $listDomains;
}
$listSites = array();
$listDomains = array();
foreach($adminSites as $site) {
$listSites[$site] = [$site];
$listDomains[] = $site;
}
$subDomains = $listSites;
if (in_array($role, ['admin'])) {
$allDomains = [];
} else {
$allDomains = $listDomains;
}
// Список актуальных стран, сегментов и менеджеров
$listCountries = array();
$listSegments = array();
$listManagers = array();
$allUsers = $usersModel->findAll();
foreach($allUsers as $userItem) {
$userCountryCode = $userItem->getCountryCode();
$userSegment = $userItem->getSegment();
$userManagerId = $userItem->getSupportId();
if ($userCountryCode != '' && !$listCountries[$userCountryCode]) {
$countryItem = $countryModel->findByCode($userCountryCode);
foreach($countryItem as $c) {
$listCountries[$c->getCode()] = $c->getName();
}
}
if ($userSegment != '' && !in_array($userSegment, $listSegments)) {
$listSegments[] = $userSegment;
}
if ($userManagerId != '' && !$listManagers[$userManagerId]) {
$support = $supportModel->findById($userManagerId);
if ($support) {
$listManagers[$support->getId()] = $support->getFullname();
}
}
}
asort($listCountries);
asort($listSegments);
// Определяем списки сайтов с фильтрами (сегмент/страна):
$listDomainsFilters = array();
foreach($listDomains as $site) {
$sitesItem = $sitesModel->findByDomain($site);
$siteUserId = [];
foreach($sitesItem as $siteItem) {
$siteUserId[] = $siteItem->getUsersId();
}
if (count($siteUserId) == 0) {
$siteSegment = '';
$siteCountry = '';
$siteManager = '';
} else {
$user = $usersModel->findById($siteUserId[0]);
$country = $user->getCountryCode();
$segment = $user->getSegment();
$manager = $user->getSupportId();
$siteSegment = $segment;
$siteCountry = $country;
$siteManager = $manager;
}
$listDomainsFilters[] = array(
'site' => $site,
'segment' => $siteSegment,
'country' => $siteCountry,
'manager' => $siteManager,
);
}
$listSitesFilters = array();
foreach($listSites as $site => $value) {
$sitesItem = $sitesModel->findByDomain($site);
$siteUserId = [];
foreach($sitesItem as $siteItem) {
$siteUserId[] = $siteItem->getUsersId();
}
if (count($siteUserId) == 0) {
$siteSegment = '';
$siteCountry = '';
$siteManager = '';
} else {
$user = $usersModel->findById($siteUserId[0]);
$country = $user->getCountryCode();
$segment = $user->getSegment();
$manager = $user->getSupportId();
$siteSegment = $segment;
$siteCountry = $country;
$siteManager = $manager;
}
$listSitesFilters[] = array(
'site' => $site,
'segment' => $siteSegment,
'country' => $siteCountry,
'manager' => $siteManager,
);
}
$currencyAdmin = (isset($_COOKIE["adminCurrency"])) ? $_COOKIE["adminCurrency"] : 'USD';
$subdomains = true;
$allStat = true;
$group = (in_array($role, ['admin'])) ? 'all' : false;
$dateIterval = new \DateInterval('P1M');
$dateStart = \DateTime::createFromFormat('Y-m-d', $periodDates['min'] ?: date('Y-m-01'));
$dateEnd = \DateTime::createFromFormat('Y-m-d', $periodDates['max'] ?: date('Y-m-01'));
$dateRange = array();
if($dateStart != $dateEnd) {
$_dateRange = new \DatePeriod($dateStart, $dateIterval, $dateEnd);
foreach($_dateRange as $dt) {
$dateRange[] = $dt;
}
}
$dateRange[] = $dateEnd;
$dateRange = array_reverse($dateRange);
$currencyModel = $this->container->get(\App\Model\Currencies::class);
$currencies = array();
foreach($currencyModel->findAll() as $currency) {
$currencies[$currency->getCode()] = $currency->getName();
}
$data = [ $data = [
'sitesFilters' => $listSitesFilters,
'periodStats' => $periodStats,
'sitesStats' => $sitesStats,
'summaryReport' => $summaryReport,
'subDomains' => $subDomains,
'listDomainsFilters' => $listDomainsFilters,
'dateRange' => $dateRange,
'segments' => $listSegments,
'countries' => $listCountries,
'managers' => $listManagers,
'currencies' => $currencies,
'currency' => ['code' => $currencyAdmin, 'name' => $currencies[$currencyAdmin]],
'lang' => $request->getAttribute('layoutInfo')->getLang(), 'lang' => $request->getAttribute('layoutInfo')->getLang(),
'role' => $role, 'folders' => $folders,
'dir' => $dir,
]; ];
return new HtmlResponse($this->template->render('adm::index', $data)); return new HtmlResponse($this->template->render('app::main', $data));
} }
} }
\ No newline at end of file
...@@ -23,36 +23,27 @@ ...@@ -23,36 +23,27 @@
* *
*/ */
namespace App\Action; namespace App\Action\Admin;
use App\Service\Mailer;
use App\Entity\Feedback;
use App\Validator\Feedback as FeedbackValidator;
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Slim\Flash\Messages;
use Zend\Diactoros\Response\HtmlResponse; use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router\RouterInterface; use Zend\Diactoros\Response\RedirectResponse;
use Zend\Expressive\Template\TemplateRendererInterface;
use Zend\Hydrator\DelegatingHydrator; use Zend\Hydrator\DelegatingHydrator;
use Zend\Validator\ValidatorInterface;
/** /**
* Class Contacts * Class SystemAction
* @package App\Action * @package App\Action\Admin
*/ */
class Contacts extends Common class Main extends Common
{ {
/** const SAVE_FOLDERS = 'save_folders';
* @var Mailer const LOAD_FOLDER = 'load_folder';
*/
protected $mailer;
/**
* @var DelegatingHydrator
*/
protected $hydrator;
/** /**
* @param ServerRequestInterface $request * @param ServerRequestInterface $request
...@@ -62,51 +53,71 @@ class Contacts extends Common ...@@ -62,51 +53,71 @@ class Contacts extends Common
*/ */
function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{ {
$this->initInfo($request);
if ($this->isXmlHttpRequest($request)) { if($request->getMethod() == 'POST') {
$postData = $request->getParsedBody(); try {
$feedback = $this->hydrator->hydrate($postData, new Feedback()); switch ($request->getAttribute('action')) {
case self::SAVE_FOLDERS:
/** @var ValidatorInterface $validator */ $response = $this->saveFolders($request);
$validator = new FeedbackValidator($this->hydrator); break;
if ($validator->isValid($feedback)) { case self::LOAD_FOLDER:
$this->mailer->sendFeedback($feedback); $response = $this->loadFolder($request);
$result = true; break;
$messages = []; default:
} else { }
$result = false; } catch(\Exception $e) {
$messages = $validator->getMessages(); $data = [
'result' => false,
'msg' => $e->getMessage(),
];
$response = new JsonResponse($data);
}
return $response;
} }
$response = new JsonResponse(
[
'result' => $result,
'msg' => $messages,
]
);
} else {
$response = new HtmlResponse($this->template->render('app::contacts', [
'lang' => $request->getAttribute('layoutInfo')->getLang(),
'layoutInfo' => $request->getAttribute('layoutInfo'),
]));
} }
return $response; private function saveFolders(ServerRequestInterface $request)
{
$data = $request->getParsedBody();
return new JsonResponse($data);
// Сформировать тестовые данные для статистики по фидам:
if ($data['feedTestData']) {
return $this->renderFeedTestData($request);
}
} }
/**
* Contacts constructor. private function loadFolder(ServerRequestInterface $request)
* @param RouterInterface $router
* @param null|TemplateRendererInterface $template
* @param ContainerInterface $container
*/
public function __construct(RouterInterface $router, $template = null, ContainerInterface $container)
{ {
parent::__construct($router, $template, $container); $data = $request->getParsedBody();
$this->mailer = $this->container->get(Mailer::class); if ($data['folder']) {
$this->hydrator = $this->container->get(DelegatingHydrator::class);
chdir('public/fotos/'.$data['folder']);
$dir = getcwd();
chdir('../../..');
$entries = scandir($dir);
$filelist = array();
foreach($entries as $entry) {
if ((strpos($entry, ".jpg") > 0) || (strpos($entry, ".jpeg") > 0) || (strpos($entry, ".webp") > 0)) {
$filelist[] = $entry;
} }
}
$data = $filelist;
$response = new JsonResponse($data);
} else {
$data = [
'result' => false,
];
$response = new JsonResponse($data);
}
return $response;
}
} }
\ No newline at end of file
<?php
/**
* Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
*/
namespace App\Action;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
/**
* Class EmailCounter
* @package App\Action
*/
class EmailCounter extends Common
{
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
*/
function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
throw new \Exception('not implemented');
//return new HtmlResponse($this->template->render('app::examples', []));
}
}
\ No newline at end of file
<?php
/**
* Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
*/
namespace App\Action;
use App\Entity\FAQ\Category;
use App\Model\FAQ\Categories;
use App\Model\FAQ\Items;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
/**
* Class FAQ
* @package App\Action
*/
class FAQ extends Common
{
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @return HtmlResponse
*/
function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
$this->initInfo($request);
/** @var Categories $categoriesModel */
$categoriesModel = $this->container->get(Categories::class);
/** @var Items $itemsModel */
$itemsModel = $this->container->get(Items::class);
$categoriesTmp = $categoriesModel->findAll();
$categories = [];
/** @var Category $category */
foreach ($categoriesTmp as $category) {
$categories[$category->getId()] = $category;
}
$items = $itemsModel->findAll(['faq_categories_id' => array_keys($categories)], 'faq_categories_id ASC, id ASC');
$itemsGrouped = $itemsModel->makeGrouped($items);
$data = [
'categories' => $categories,
'items' => $itemsGrouped,
'lang' => $request->getAttribute('layoutInfo')->getLang(),
];
return new HtmlResponse($this->template->render("app::faq", $data));
}
}
\ No newline at end of file
...@@ -47,17 +47,19 @@ class Index extends Common ...@@ -47,17 +47,19 @@ class Index extends Common
{ {
$this->initInfo($request); $this->initInfo($request);
// Временно пока нет регистрации
return new RedirectResponse($this->router->generateUri('adm.index'));
/** @var UserService $auth */ /** @var UserService $auth */
$auth = $this->container->get(UserService::class); $auth = $this->container->get(UserService::class);
if ($auth->getIdentity()) { if ($auth->getIdentity()) {
return new RedirectResponse($this->router->generateUri('user.cabinet')); return new RedirectResponse($this->router->generateUri('user.cabinet'));
} }
$data = [ $data = [
'lang' => $request->getAttribute('layoutInfo')->getLang(), 'lang' => $request->getAttribute('layoutInfo')->getLang(),
]; ];
return new HtmlResponse($this->template->render('app::index', $data)); return new HtmlResponse($this->template->render('app::index', $data));
} }
} }
\ No newline at end of file
<?php
/**
* Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
*/
namespace App\Action;
use App\Authentication\UserService;
use App\Entity\Site as SiteEntity;
use App\Model\Sites;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
/**
* Class InstallCounter
* @package App\Action
*/
class InstallCounter extends Common
{
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @return HtmlResponse
*/
function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
$this->initInfo($request);
$siteId = $request->getAttribute('siteId');
$site = null;
if ($siteId) {
/** @var Sites $sitesModel */
$sitesModel = $this->container->get(Sites::class);
/** @var UserService $auth */
$auth = $this->container->get(UserService::class);
/** @var SiteEntity $site */
$site = $sitesModel->findByIdAndUserId($siteId, $auth->getIdentity()->getId());
}
if (!$site) {
$site = new SiteEntity();
$site->setDomain(_t('Domain not found'));
}
return new HtmlResponse($this->template->render('app::install-counter', [
'lang' => $request->getAttribute('layoutInfo')->getLang(),
'site' => $site
]));
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -4,4 +4,4 @@ ...@@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php'; require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit::getLoader(); return ComposerAutoloaderInit1ddf57666a27a7293c527057884f2925::getLoader();
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer // autoload_real.php @generated by Composer
class ComposerAutoloaderInit class ComposerAutoloaderInit1ddf57666a27a7293c527057884f2925
{ {
private static $loader; private static $loader;
...@@ -19,9 +19,9 @@ class ComposerAutoloaderInit ...@@ -19,9 +19,9 @@ class ComposerAutoloaderInit
return self::$loader; return self::$loader;
} }
spl_autoload_register(array('ComposerAutoloaderInit', 'loadClassLoader'), true, true); spl_autoload_register(array('ComposerAutoloaderInit1ddf57666a27a7293c527057884f2925', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(); self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit', 'loadClassLoader')); spl_autoload_unregister(array('ComposerAutoloaderInit1ddf57666a27a7293c527057884f2925', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) { if ($useStaticLoader) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment