<?php
namespace App\Controller;
use App\Repository\NewsRepository;
use App\Repository\NewsGroupRepository;
use App\Repository\ProductArticleRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\Session;
class ApplicationController extends AbstractController
{
/**
* @var String
*/
private $path = '/files/';
/**
* @var String
*/
private $frontPath = '../../frontend';
/**
* @Route("/", name="app_index",)
*/
public function index(): Response
{
return $this->redirect('/admin');
}
/**
* @Route("/{url}", name="app_pages", requirements={"url" = "^(?!api|action|manual|import).*\/$"})
* @Route("/admin", name="app_admin")
*/
public function admin(): Response
{
return $this->render('app.html.twig');
}
/**
* @Route("/manual", name="manual")
* */
public function manual(Request $request)
{
$user = $this->getUser();
$download = $request->query->get('download');
$download = filter_var($download, FILTER_VALIDATE_BOOLEAN);
$subject = 'Руководство использования Soft99.pdf';
if ($user) {
$filename = "manual.pdf";
$directory = dirname($request->server->get('DOCUMENT_ROOT')).'/assets/doc';
if ($download) {
$response = new Response();
$response->headers->set('Content-type', 'application/octet-stream');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $subject));
$response->setContent(file_get_contents($directory.'/'.$filename));
$response->setStatusCode(200);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
return $response;
}
header('Content-type: application/pdf');
header(sprintf('Content-Disposition: inline; filename="%s"', $subject));
header('Content-Length: ' . filesize($directory.'/'.$filename));
@readfile($directory.'/'.$filename);
exit;
}
return $this->redirect('/admin');
}
/**
* @Route("/action/upload", name="upload")
* */
public function uploadGallery(Request $request) {
$public = $this->path.'gallery';
$file = $request->files->get('upload');
$images_exts = [
IMAGETYPE_GIF => 'gif',
IMAGETYPE_JPEG => 'jpg',
IMAGETYPE_PNG => 'png'
];
$directory = $request->server->get('DOCUMENT_ROOT').$public;
$gallery = '';
$message = '';
$separator = '/';
if(!isset($file) && !is_uploaded_file($file->getRealPath())) {
$message = 'Вы не указали файл для загрузки';
} else {
$filepath = $file->getRealPath();
$filename = $file->getClientOriginalName();
$is = @getimagesize($filepath);
if ($is) {
if (!isset($images_exts[$is[2]])) {
$message = 'Необходимо указать файл формата ' . implode(', ', $images_exts);
} else {
$name = transliterator_transliterate('Russian-Latin/BGN', $filename);
$download = $directory . $separator . $name;
if (file_exists($download)) {
$message = 'Файл с именем ' . $filename . ' уже существует';
} elseif (!@move_uploaded_file($filepath, $download)) {
$message = 'Невозможно сохранить файл, проверьте настройки папки для файлов ' . $filename;
} else {
$gallery = '//backend.soft99.ru'.$public . $separator . $name;
//$gallery = $request->getSchemeAndHttpHost().$gallery;
$message = 'Файл успешно загружен';
}
}
}
}
$callback = $_GET['CKEditorFuncNum'];
$response = ["message" => $message];
echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction("'.$callback.'", "'.$gallery.'", "'.$message.'" );</script>';
return new Response(json_encode($response));
}
/**
* @Route("/action/upload/dropped", name="dropped", methods={"post"})
* */
function droppedGallery(Request $request) {
$public = $this->path.'gallery';
$file = $request->files->get('upload');
$directory = $request->server->get('DOCUMENT_ROOT').$public;
$filename = $file->getClientOriginalName();
$gallery = '';
$separator = '/';
$name = transliterator_transliterate('Russian-Latin/BGN', $filename);
$download = $directory . $separator . $name;
if (!@move_uploaded_file($file->getRealPath(), $download)) {
$message = 'Невозможно сохранить файл, проверьте настройки папки для файлов '.$filename;
$jsonForPasteMode = array("uploaded" => 0, "error" => $message);
return new JsonResponse($jsonForPasteMode);
} else {
// Если все успешно сохранилось отправляем ответ в CKEditor
$gallery = $public. $separator .$name;
//$gallery = $request->getSchemeAndHttpHost().$gallery;
$jsonForPasteMode = array("uploaded" => 1, "fileName" => $name, "url" => $gallery);
return new JsonResponse($jsonForPasteMode);
}
}
/**
* @Route("/action/browse", name="browse")
* */
public function browseGallery(Request $request) {
$directory = $request->server->get('DOCUMENT_ROOT').$this->path.'gallery';
$files = array_diff(scandir($directory), array('..', '.'));
return $this->render('browse.html.twig', [
'files' => $files
]);
}
/**
* @Route("/action/gallery/del/{file}", name="deleteImgBrowse")
* */
public function deleteImgBrowse(string $file, Request $request) {
$directory = $request->server->get('DOCUMENT_ROOT').$this->path.'gallery/';
$path_file = $directory.$file;
if (file_exists($path_file)) unlink($path_file);
$files = array_diff(scandir($directory), array('..', '.'));
return $this->render('browse.html.twig', [
'files' => $files
]);
}
/**
* @Route("/action/search", methods={"get"})
*/
public function search(Request $request): Response
{
$session = new Session();
$session->start();
$query = $request->query->get('query');
$page = $request->query->get('page');
$ref = $request->query->get('ref');
$array = [
'query' => $query,
'page' => $page
];
if ($query) {
$session->set('search', $array);
}
if ($ref) {
return $this->redirect($ref);
}
$referer = $request->headers->get('referer');
return $this->redirect($referer);
}
/**
* @Route("/action/search/get", methods={"get"})
*/
public function getSearch(): JsonResponse {
$session = new Session();
$search = $session->get('search') ?? [];
return new JsonResponse($search, Response::HTTP_OK);
}
/**
* @Route("/action/search/del", methods={"get"})
*/
public function delSearch(Request $request): RedirectResponse {
$session = new Session();
$session->remove('search');
$referer = $request->headers->get('referer');
return $this->redirect($referer);
}
/**
* @Route("/action/sorted", methods={"get"})
*/
public function sorted(Request $request): Response
{
$session = new Session();
$session->start();
$field = $request->query->get('field');
$page = $request->query->get('page');
$sort = 'ASC';
if ($field) {
$sorted = $session->get('sorted');
if ($sorted && $sorted['field'] === $field) {
$sort = $sorted['sort'] !== 'ASC' ? 'ASC' : 'DESC';
}
$sorted['sort'] = $sort;
$sorted['field'] = $field;
$sorted['page'] = $page;
$session->set('sorted', $sorted);
}
$referer = $request->headers->get('referer');
return $this->redirect($referer);
}
/**
* @Route("/action/sorted/del", methods={"get"})
*/
public function delSorted(Request $request): RedirectResponse {
$session = new Session();
$session->remove('sorted');
$referer = $request->headers->get('referer');
return $this->redirect($referer);
}
public function getFiles($page, $src = '/') {
$path = $this->path . $page . $src;
$directory = $_SERVER['DOCUMENT_ROOT'].$path;
if (!file_exists($directory)) return null;
$files = array_diff(scandir($directory), array('..', '.'));
return array_values($files);
}
public function uploadFile($files, $page, $src = '/', $group = false) {
if ($group) {
$filenames = [];
foreach ($files as $index => $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . $this->path . $page . $src;
$filename = $file->getClientOriginalName();
$prefix = substr(sha1($index + time()), 0, 5);
if (!file_exists($path)) mkdir($path, $mode = 0777, true);
move_uploaded_file($file, $path . $prefix .$filename);
array_push($filenames, $prefix .$filename);
}
return $filenames;
} else {
$path = $_SERVER['DOCUMENT_ROOT'] . $this->path . $page . '/';
$filename = $files->getClientOriginalName();
$prefix = substr(sha1(time()), 0, 5);
if (!file_exists($path)) mkdir($path, $mode = 0777, true);
move_uploaded_file($files, $path . $prefix . $filename);
return $prefix . $filename;
}
}
public function removeFile($filename, $page, $src = '/') {
if ($filename) {
$path = $_SERVER['DOCUMENT_ROOT'] . $this->path . $page . $src;
if (file_exists($path . $filename)) unlink($path . $filename);
}
return true;
}
public function dropFiles($page, $src = '/') {
$directory = $_SERVER['DOCUMENT_ROOT'].$this->path.$page.$src;
if (file_exists($directory)) {
$files = array_diff(
scandir($directory),
array('..', '.')
);
foreach ($files as $file) {
unlink($directory .'/'. $file);
}
rmdir($directory);
return true;
}
return false;
}
public function updateSitemap(?string $link, ?string $oldLink, string $page):void {
$path = $_SERVER['DOCUMENT_ROOT'].'/'.$this->frontPath.'/public/sitemap-'.$page.'.xml';
$dist = $_SERVER['DOCUMENT_ROOT'].'/'. $this->frontPath.'/dist/sitemap-'.$page.'.xml';
if (!file_exists($path) || (file_exists($path) && !is_writable($dist))) {
return;
}
$host = $this->getParameter('front.host');
$sitemap = file_get_contents($path);
if ($oldLink) {
$thisItem = '<loc>'.$host.'/'.$page.'/'.$oldLink.'</loc>';
$hasItem = strripos($sitemap, $thisItem);
if ($hasItem) {
//removing the old item
$itemStart = strripos(substr($sitemap, 0, $hasItem), '<url>') - 1;
$itemEol = strpos($sitemap, '</url>', $hasItem) + 6;
$sitemap = substr($sitemap, 0, $itemStart).substr($sitemap, $itemEol);
}
}
if ($link) {
//adding a new item
$template = '<url>'.PHP_EOL;
$template .= ' <loc>'.$host.'/'.$page.'/'.$link.'</loc>'.PHP_EOL;
$template .= ' <lastmod>'.(new \DateTimeImmutable())->format('c').'</lastmod>'.PHP_EOL;
$template .= '</url>'.PHP_EOL;
$eol = strripos($sitemap, '</urlset>');
$sitemap = substr($sitemap, 0, $eol).$template.substr($sitemap, $eol);
}
if (file_exists($dist) && is_writable($dist)) {
file_put_contents($dist, $sitemap);
}
file_put_contents($path, $sitemap);
}
public function clearSitemap(string $page) {
$path = $_SERVER['DOCUMENT_ROOT'].'/'.$this->frontPath.'/public/sitemap-'.$page.'.xml';
$dist = $_SERVER['DOCUMENT_ROOT'].'/'. $this->frontPath.'/dist/sitemap-'.$page.'.xml';
if (!file_exists($path) || (file_exists($path) && !is_writable($dist))) {
return;
}
$host = $this->getParameter('front.host');
$sitemap = file_get_contents($path);
$itemStart = stripos($sitemap, '<url>') - 1;
$itemEol = strrpos($sitemap, '</url>') + 6;
$sitemap = substr($sitemap, 0, $itemStart).substr($sitemap, $itemEol);
if (file_exists($dist) && is_writable($dist)) {
file_put_contents($dist, $sitemap);
}
file_put_contents($path, $sitemap);
}
/**
* @Route("/action/reindexing-sitemap", methods={"get"})
*/
public function reindexingSitemap(
Request $request,
ProductArticleRepository $productRepository,
NewsRepository $newsRepository,
NewsGroupRepository $newsGroupRepository
) {
$pages = $request->query->get('page') ?? ['news', 'product' , 'newsGroup'];
$result = [
'success' => false,
'message' => 'The value of some query parameters is undefined',
'errors' => []
];
if (is_string($pages)) $pages = [$pages];
foreach ($pages as $page) {
$repository = $page . 'Repository';
if (isset($$repository)) {
$this->clearSitemap($page);
$items = $$repository->findAll();
foreach($items as $item) {
$this->updateSitemap($item->getLink(), null, $page);
}
$result = [
'success' => true,
'message' => 'Links in the sitemap were successfully indexed',
'errors' => []
];
}
}
$this->addFlash('notice', $result);
$referer = $request->headers->get('referer') ?? '/admin';
return $this->redirect($referer);
}
public function validMessage($result, $message, $error) {
$result['success'] = false;
$result['message'] = $message;
$result['errors'][] = $error;
return $result;
}
}