Files
kupshop/admin/menulinks.php
2025-08-02 16:30:27 +02:00

316 lines
12 KiB
PHP

<?php
use KupShop\AdminBundle\AdminBlocksTrait;
use KupShop\AdminBundle\Util\BlocksHistory;
use KupShop\ContentBundle\Util\Block;
use KupShop\ContentBundle\Util\BlocksTrait;
use KupShop\ContentBundle\Util\MenuUtil;
use KupShop\I18nBundle\Translations\MenuLinksTranslation;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\KupShopBundle\Util\System\UniqueUrlUtil;
use Query\Operator;
$main_class = 'MenuLinks';
class MenuLinks extends Window
{
use BlocksTrait;
use AdminBlocksTrait;
protected $tableName = 'menu_links';
protected $defaults = ['id_menu' => 1, 'show_in_search' => 'Y'];
protected $show_on_web = 'menu_link';
/** @var BlocksHistory */
private $blocksHistory;
/** @var \KupShop\RewriteBundle\Util\Rewrite */
private $rewrite;
public function __construct()
{
$this->blocksHistory = ServiceContainer::getService(BlocksHistory::class);
$this->rewrite = ServiceContainer::getService(\KupShop\RewriteBundle\Util\Rewrite::class, 2);
$this->blockUtil = ServiceContainer::getService(Block::class);
}
public function get_vars()
{
$vars = parent::get_vars();
$pageVars = getVal('body', $vars);
if ($this->getAction() != 'erased') {
$SQL = sqlQuery('SELECT id, name
FROM '.getTableName('producers')."
WHERE active='Y'
ORDER BY name ASC ");
foreach ($SQL as $row) {
$pageVars['producers'][] = $row;
}
$SQL = sqlQuery('SELECT s.id, s.name
FROM '.getTableName('sections').' AS s, '.getTableName('sections_relation')." AS sr
WHERE s.figure='Y' AND s.id=sr.id_section
ORDER BY s.name ASC ");
foreach ($SQL as $row) {
$pageVars['sections'][] = $row;
}
$SQL = sqlQuery('SELECT s.id, s.name
FROM '.getTableName('articles_branches')." AS s
WHERE s.figure='Y' AND s.top_branch=0
ORDER BY s.name ASC ");
foreach ($SQL as $row) {
$pageVars['articles_branches'][] = $row;
}
$pageVars['data']['parent'] = $pageVars['data']['parent'] ?? 'null';
if ($this->getAction() == 'add') {
$pageVars['data']['figure'] = 'Y';
$pageVars['newMenuRoot'] = getVal('newMenuRoot', null, false);
}
$vars['type'] = 'menulinks';
}
$vars['body'] = $pageVars;
$this->unserializeCustomData($vars['body']['data']);
$type = (int) (($this->getAction() == 'edit' || $this->isDuplicate()) ? $pageVars['data']['type'] : getVal('type', $_GET['data'] ?? [], 1));
$this->setTemplate('window/menuLinks.'.mb_strtolower(MenuUtil::$TYPES[$type]).'.tpl');
$vars['typeName'] = MenuUtil::$TYPES[$type];
$vars['hasChildren'] = sqlQuery('SELECT COUNT(id) FROM menu_links WHERE parent = :id', ['id' => $this->getID()])->fetchColumn();
if (!getVal('Submit') && $this->getAction() == 'edit' && $type === 1) {
$vars['body']['data']['fullLink'] = $GLOBALS['cfg']['Addr']['full'].$vars['body']['data']['link'];
$vars['body']['data']['fullUrl'] = $GLOBALS['cfg']['Addr']['full'].$vars['body']['data']['url'];
}
if ($type === MenuUtil::TYPE_PAGE) {
if (isset($pageVars['data']['id_block'])) {
$vars['body']['data']['blocks'] = $this->getBlocks($pageVars['data']['id_block']);
$vars['body']['data']['blocks_history'] = $this->blocksHistory->getBlocksHistory($pageVars['data']['id_block']);
}
$vars['body']['data']['photos'] = sqlQueryBuilder()->select('id_photo')->from('photos_menu_relation')
->where(\Query\Operator::equals(['id_menu' => $this->getID()]))
->orderBy('position')->execute()->fetchAll();
}
if (in_array($type, [MenuUtil::TYPE_PAGE, MenuUtil::TYPE_GROUP])) {
$vars['body']['labels'] = array_merge([
'leadpage',
'contact',
'shopping-help',
'shopping-rules',
'complaint-rules',
'transport',
'about-shop',
'review-rules',
'consent',
'privacy_policy',
'menu_footer',
'menu_header',
'menu_copyright',
'cookies_policy',
'credit-purchase',
], findModule(\Modules::PAGES, \Modules::SUB_LABELS, []));
if (findModule(\Modules::BONUS_PROGRAM)) {
$vars['body']['labels'][] = 'bonus-program';
}
}
if (findModule(\Modules::TRANSLATIONS)) {
$vars['body']['data']['translation_figure'] = $this->getTranslationUtil()->getTranslationsFigure(
MenuLinksTranslation::class,
$this->getID(),
);
}
return $vars;
}
public function printMenuItems($id_menu, $parent = 0, $level = 0)
{
$SQL = sqlQuery('SELECT id, list_order, name
FROM '.getTableName('menu_links')."
WHERE id_menu='".$id_menu."' AND parent='{$parent}'
ORDER BY list_order ASC ");
$data = [];
foreach ($SQL as $key => $row) {
$data[$key]['id'] = $row['id'];
$data[$key]['title'] = $row['name'];
$data[] = $this->printMenuItems($id_menu, $row['id'], $level + 1);
}
return $data;
}
protected function getFields()
{
parent::getFields();
$this->required['list_order'] = false;
}
public function getSQLFields($data = null, $fields = null, $defaults = null, $types = null)
{
$sqlFields = parent::getSQLFields($data, $fields, $defaults, $types);
$sqlFields['id_menu'] = ($sqlFields['id_menu'] ?? '') === '' ? null : $sqlFields['id_menu'];
$sqlFields['parent'] = $sqlFields['parent'] === 'null' ? null : $sqlFields['parent'];
if (isset($sqlFields['parent'])) {
$parent = $this->selectSQL('menu_links', ['id' => $sqlFields['parent']])->fetch();
$sqlFields['id_menu'] = $parent['id_menu'];
}
if ($this->getAction() === 'edit') {
// fix changing menu (including virtual unclassified menu)
$menu = $this->selectSQL('menu_links', ['id' => $this->getID()])->fetch();
if ($menu['id_menu'] !== $sqlFields['id_menu'] || $menu['parent'] !== (int) $sqlFields['parent']) {
$newPosition = sqlQueryBuilder()->select('COALESCE(MAX(list_order) + 1, 0)')->from('menu_links')
->where(\Query\Operator::equalsNullable([
'id_menu' => $sqlFields['id_menu'],
'parent' => $sqlFields['parent'],
]))
->execute()->fetchColumn();
$sqlFields['list_order'] = $newPosition ?? 0;
}
} elseif ($this->getAction() === 'add') {
$newPosition = sqlQueryBuilder()->select('COALESCE(MAX(list_order) + 1, 0)')->from('menu_links')
->where(\Query\Operator::equalsNullable([
'id_menu' => $sqlFields['id_menu'],
'parent' => $sqlFields['parent'],
]))
->execute()->fetchColumn();
$sqlFields['list_order'] = $newPosition ?? 0;
}
return $sqlFields;
}
public function getData()
{
$data = parent::getData();
$this->serializeCustomData($data);
$blank = ($data['target'] ?? 'N');
$data['target'] = ($blank == 'Y' ? '_blank' : '');
return $data;
}
public function handleUpdate()
{
$data = $this->getData();
$uniqueUrlUtil = ServiceContainer::getService(UniqueUrlUtil::class);
if (!empty($data['url']) && $uniqueTxt = $uniqueUrlUtil->validateUniqueUrl(UniqueUrlUtil::MENULINKS, $this->getID(), $data['url'])) {
$this->returnError($uniqueTxt);
}
$data['name'] = htmlspecialchars(trim($data['name']));
$data['link'] = !empty($data['link']) ? StringUtil::normalizeWhitespace($data['link']) : null;
$data['target'] = StringUtil::normalizeWhitespace($data['target'] ?? '');
clearCache('menu', true);
if ($this->getAction() === 'edit') {
$oldMenu = $this->selectSQL('menu_links', ['id' => $this->getID()])->fetch();
}
$result = parent::handleUpdate();
$newMenuRoot = (bool) getVal('newMenuRoot', null, false);
if ($this->getAction() === 'add' && $newMenuRoot) {
// fix new menu root id_menu
$this->updateSQL('menu_links', ['id_menu' => $this->getID()], ['id' => $this->getID()]);
}
$menu = $this->selectSQL('menu_links', ['id' => $this->getID()])->fetch();
MenuUtil::fixOrderTreeLevelPositions($menu['parent'], $menu['id_menu'], $newMenuRoot);
// fix positions on original level when menu is changed
if ($this->getAction() === 'edit' && ($oldMenu['id_menu'] !== $menu['id_menu'] || $oldMenu['parent'] !== $menu['parent'])) {
MenuUtil::fixOrderTreeLevelPositions($oldMenu['parent'], $oldMenu['id_menu'], $oldMenu['id'] === $oldMenu['id_menu']);
}
$data = getVal('data');
if (!empty($data) && $data['type'] == MenuUtil::TYPE_PAGE) {
// generate url if not present
if (empty($data['url'])) {
$generatedLink = createScriptURL_Text($data['name']).'/';
$this->updateSQL('menu_links', ['url' => $generatedLink], ['id' => $this->getID()]);
}
if ($this->getAction() == 'edit') {
if (!empty($data['original_url']) && $this->rewrite) {
// url is not same, add rewrite
if (trim($data['original_url'], '/') != trim($data['url'], '/')) {
$this->rewrite->addRewrite($data['original_url'], \KupShop\RewriteBundle\Util\Rewrite::TYPE_PAGE, $this->getID());
}
}
// historii je treba ulozit jeste pred ulozenim bloku
$this->blocksHistory->saveBlocksHistory(getVal('blocks', $data, []));
}
$this->saveBlocks($data, $this->getID(), 'menu_links');
if ($this->getAction() == 'add') {
$rootID = sqlQueryBuilder()->select('id_block')->from('menu_links')
->where(Operator::equals(['id' => $this->getID()]))
->execute()->fetchOne();
if (!$rootID) {
// Při vytváření nové stránky automaticky založit jeden prázdný blok
$this->blockUtil->insertFirstBlock('menu_links', $this->getID(), null);
}
}
$this->updateBlocksPhotosPositions($this->getID(), 'menu_links', 'id_menu', 'photos_menu_relation');
}
if (findModule(\Modules::TRANSLATIONS) && !empty($data['translation_figure'])) {
$this->getTranslationUtil()?->updateTranslationsFigure(
MenuLinksTranslation::class,
$this->getID(),
$data['translation_figure'],
);
}
return $result;
}
public function handleDelete()
{
$IDlink = $this->getID();
clearCache('menu', true);
// zjistit jmeno mazaneho odkazu
$menu = $this->selectSQL('menu_links', ['id' => $IDlink])->fetch();
// remove blocks + blocks for all nested items
$this->removeBlocks($menu['id_block']);
$parentIDsBuffer = [$menu['id']];
while ($tmpParentID = array_pop($parentIDsBuffer)) {
$result = sqlQueryBuilder()->select('id, id_block')->from('menu_links')
->where('parent=:parent')->setParameter('parent', $tmpParentID)->execute();
foreach ($result as $row) {
$this->removeBlocks($row['id_block']);
array_push($parentIDsBuffer, $row['id']);
}
}
$this->deleteSQL('menu_links', ['id' => $IDlink]);
writeDownActivity(sprintf(translate('activityDeleted'), $menu['name']));
MenuUtil::fixOrderTreeLevelPositions($menu['parent'], $menu['id_menu']);
// Odkaz v menu byl smazán
$ErrStr = translate('errorDeleted');
redirect('launch.php?s=menulinks.php&acn=erased&ErrStr='.urlencode($ErrStr));
}
}