first commit

This commit is contained in:
2024-11-05 12:22:50 +01:00
commit e5682a3912
19641 changed files with 2948548 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Adapter;
use PrestaShop\Module\LinkList\Model\LinkBlock;
use PrestaShop\PrestaShop\Adapter\Domain\AbstractObjectModelHandler;
class ObjectModelHandler extends AbstractObjectModelHandler
{
/**
* @param int $linkBlockId
* @param array $associatedShops
* @param bool $forceAssociate
*/
public function handleMultiShopAssociation(
int $linkBlockId,
array $associatedShops,
bool $forceAssociate = false
): void {
$objectModel = new LinkBlock($linkBlockId);
/*
* Why we want to force association?
* It's easier to work on multi-store tables even when feature is disabled
* This way we can force association to store as legacy ObjectModel does
* We need to remember that multi-store is always there, shop tables are always there
*
* @todo: this should be part of AbstractObjectModelHandler
*/
if ($forceAssociate) {
$objectModel->associateTo($associatedShops);
return;
}
$this->associateWithShops($objectModel, $associatedShops);
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Cache;
use PrestaShop\PrestaShop\Core\Addon\Module\ModuleRepository;
use Ps_Linklist;
/**
* Class LegacyBlockCache.
*/
final class LegacyLinkBlockCache implements LinkBlockCacheInterface
{
/**
* @var ModuleRepository
*/
private $moduleRepository;
/**
* LegacyLinkBlockCache constructor.
*
* @param ModuleRepository $moduleRepository
*/
public function __construct(ModuleRepository $moduleRepository)
{
$this->moduleRepository = $moduleRepository;
}
/**
* {@inheritdoc}
*/
public function clearModuleCache()
{
/** @var Ps_Linklist $module */
$module = $this->moduleRepository->getInstanceByName(Ps_Linklist::MODULE_NAME);
$module->_clearCache($module->templateFile);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Cache;
/**
* Interface LinkBlockCacheInterface.
*/
interface LinkBlockCacheInterface
{
/**
* Clear module cache.
*/
public function clearModuleCache();
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,302 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Controller\Admin\Improve\Design;
use PrestaShop\Module\LinkList\Core\Grid\LinkBlockGridFactory;
use PrestaShop\Module\LinkList\Core\Search\Filters\LinkBlockFilters;
use PrestaShop\Module\LinkList\Form\LinkBlockFormDataProvider;
use PrestaShop\Module\LinkList\Repository\LinkBlockRepository;
use PrestaShop\PrestaShop\Core\Exception\DatabaseException;
use PrestaShop\PrestaShop\Core\Form\FormHandlerInterface;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use PrestaShopBundle\Security\Annotation\AdminSecurity;
use PrestaShopBundle\Security\Annotation\ModuleActivated;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class LinkBlockController.
*
* @ModuleActivated(moduleName="ps_linklist", redirectRoute="admin_module_manage")
*/
class LinkBlockController extends FrameworkBundleAdminController
{
/**
* @AdminSecurity("is_granted('read', request.get('_legacy_controller'))", message="Access denied.")
*
* @param Request $request
*
* @return Response
*/
public function listAction(Request $request)
{
//Get hook list, then loop through hooks setting it in in the filter
/** @var LinkBlockRepository $repository */
$repository = $this->get('prestashop.module.link_block.repository');
$hooks = $repository->getHooksWithLinks();
$filtersParams = $this->buildFiltersParamsByRequest($request);
/** @var LinkBlockGridFactory $linkBlockGridFactory */
$linkBlockGridFactory = $this->get('prestashop.module.link_block.grid.factory');
$grids = $linkBlockGridFactory->getGrids($hooks, $filtersParams);
$presentedGrids = [];
foreach ($grids as $grid) {
$presentedGrids[] = $this->presentGrid($grid);
}
$presentedGrids = array_filter(
$presentedGrids,
function ($grid) {
return $grid['data']['records_total'] > 0;
}
);
return $this->render('@Modules/ps_linklist/views/templates/admin/link_block/list.html.twig', [
'grids' => $presentedGrids,
'enableSidebar' => true,
'layoutHeaderToolbarBtn' => $this->getToolbarButtons(),
'help_link' => $this->generateSidebarLink($request->attributes->get('_legacy_controller')),
]);
}
/**
* @AdminSecurity("is_granted('create', request.get('_legacy_controller'))", message="Access denied.")
*
* @param Request $request
*
* @return Response
*
* @throws \Exception
*/
public function createAction(Request $request)
{
$this->get('prestashop.module.link_block.form_provider')->setIdLinkBlock(null);
$form = $this->get('prestashop.module.link_block.form_handler')->getForm();
return $this->render('@Modules/ps_linklist/views/templates/admin/link_block/form.html.twig', [
'linkBlockForm' => $form->createView(),
'enableSidebar' => true,
'layoutHeaderToolbarBtn' => $this->getToolbarButtons(),
'help_link' => $this->generateSidebarLink($request->attributes->get('_legacy_controller')),
]);
}
/**
* @AdminSecurity("is_granted('update', request.get('_legacy_controller'))", message="Access denied.")
*
* @param Request $request
* @param int $linkBlockId
*
* @return Response
*
* @throws \Exception
*/
public function editAction(Request $request, $linkBlockId)
{
$this->get('prestashop.module.link_block.form_provider')->setIdLinkBlock($linkBlockId);
$form = $this->get('prestashop.module.link_block.form_handler')->getForm();
return $this->render('@Modules/ps_linklist/views/templates/admin/link_block/form.html.twig', [
'linkBlockForm' => $form->createView(),
'enableSidebar' => true,
'layoutHeaderToolbarBtn' => $this->getToolbarButtons(),
'help_link' => $this->generateSidebarLink($request->attributes->get('_legacy_controller')),
]);
}
/**
* @AdminSecurity("is_granted('create', request.get('_legacy_controller'))", message="Access denied.")
*
* @param Request $request
*
* @return RedirectResponse|Response
*
* @throws \Exception
*/
public function createProcessAction(Request $request)
{
return $this->processForm($request, 'Successful creation.');
}
/**
* @AdminSecurity("is_granted('update', request.get('_legacy_controller'))", message="Access denied.")
*
* @param Request $request
* @param int $linkBlockId
*
* @return RedirectResponse|Response
*
* @throws \Exception
*/
public function editProcessAction(Request $request, $linkBlockId)
{
return $this->processForm($request, 'Successful update.', $linkBlockId);
}
/**
* @AdminSecurity("is_granted('delete', request.get('_legacy_controller'))", message="Access denied.")
*
* @param int $linkBlockId
*
* @return RedirectResponse
*/
public function deleteAction($linkBlockId)
{
$repository = $this->get('prestashop.module.link_block.repository');
$errors = [];
try {
$repository->delete($linkBlockId);
} catch (DatabaseException $e) {
$errors[] = [
'key' => 'Could not delete #%i',
'domain' => 'Admin.Catalog.Notification',
'parameters' => [$linkBlockId],
];
}
if (0 === count($errors)) {
$this->clearModuleCache();
$this->addFlash('success', $this->trans('Successful deletion.', 'Admin.Notifications.Success'));
} else {
$this->flashErrors($errors);
}
return $this->redirectToRoute('admin_link_block_list');
}
/**
* @AdminSecurity("is_granted('update', request.get('_legacy_controller'))", message="Access denied.")
*
* @param Request $request
* @param int $hookId
*
* @throws \Exception
*
* @return RedirectResponse
*/
public function updatePositionsAction(Request $request, $hookId)
{
$positionsData = [
'positions' => $request->request->get('positions', null),
'parentId' => $hookId,
];
/** @var LinkBlockRepository $repository */
$repository = $this->get('prestashop.module.link_block.repository');
try {
$repository->updatePositions($this->getContext()->shop->id, $positionsData);
$this->clearModuleCache();
$this->addFlash('success', $this->trans('Successful update.', 'Admin.Notifications.Success'));
} catch (DatabaseException $e) {
$errors = [$e->getMessage()];
$this->flashErrors($errors);
}
return $this->redirectToRoute('admin_link_block_list');
}
/**
* @param Request $request
* @param string $successMessage
* @param int|null $linkBlockId
*
* @return Response|RedirectResponse
*
* @throws \Exception
*/
private function processForm(Request $request, $successMessage, $linkBlockId = null)
{
/** @var LinkBlockFormDataProvider $formProvider */
$formProvider = $this->get('prestashop.module.link_block.form_provider');
$formProvider->setIdLinkBlock($linkBlockId);
/** @var FormHandlerInterface $formHandler */
$formHandler = $this->get('prestashop.module.link_block.form_handler');
$form = $formHandler->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$saveErrors = $formHandler->save($form->getData());
if (0 === count($saveErrors)) {
$this->addFlash('success', $this->trans($successMessage, 'Admin.Notifications.Success'));
return $this->redirectToRoute('admin_link_block_list');
}
$this->flashErrors($saveErrors);
}
$formErrors = [];
foreach ($form->getErrors(true) as $error) {
$formErrors[] = $error->getMessage();
}
$this->flashErrors($formErrors);
}
return $this->render('@Modules/ps_linklist/views/templates/admin/link_block/form.html.twig', [
'linkBlockForm' => $form->createView(),
'enableSidebar' => true,
'layoutHeaderToolbarBtn' => $this->getToolbarButtons(),
'help_link' => $this->generateSidebarLink($request->attributes->get('_legacy_controller')),
]);
}
/**
* @param Request $request
*
* @return array
*/
protected function buildFiltersParamsByRequest(Request $request)
{
$filtersParams = array_merge(LinkBlockFilters::getDefaults(), $request->query->all());
$filtersParams['filters']['id_lang'] = $this->getContext()->language->id;
return $filtersParams;
}
/**
* Gets the header toolbar buttons.
*
* @return array
*/
private function getToolbarButtons()
{
return [
'add' => [
'href' => $this->generateUrl('admin_link_block_create'),
'desc' => $this->trans('New block', 'Modules.Linklist.Admin'),
'icon' => 'add_circle_outline',
],
];
}
/**
* Clear module cache.
*/
private function clearModuleCache()
{
$this->get('prestashop.module.link_block.cache')->clearModuleCache();
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,162 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Core\Grid\Definition\Factory;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\RowActionCollection;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\Type\LinkRowAction;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\Type\SubmitRowAction;
use PrestaShop\PrestaShop\Core\Grid\Column\ColumnCollection;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\ActionColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\PositionColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn;
use PrestaShop\PrestaShop\Core\Grid\Definition\Factory\AbstractGridDefinitionFactory;
use PrestaShop\PrestaShop\Core\Multistore\MultistoreContextCheckerInterface;
/**
* Class LinkBlockDefinitionFactory.
*/
final class LinkBlockDefinitionFactory extends AbstractGridDefinitionFactory
{
const FACTORY_ID = 'link_widget_grid_';
/**
* @var array
*/
private $hook;
/**
* @var MultistoreContextCheckerInterface
*/
private $multistoreContextChecker;
/**
* LinkBlockDefinitionFactory constructor.
*
* @param array $hook
* @param MultistoreContextCheckerInterface $multistoreContextChecker
*/
public function __construct(
array $hook,
MultistoreContextCheckerInterface $multistoreContextChecker
) {
$this->hook = $hook;
$this->multistoreContextChecker = $multistoreContextChecker;
}
/**
* {@inheritdoc}
*/
protected function getId()
{
return self::FACTORY_ID . $this->hook['id_hook'];
}
/**
* {@inheritdoc}
*/
protected function getName()
{
return $this->hook['name'] . ' ' . $this->hook['title'];
}
/**
* {@inheritdoc}
*/
protected function getColumns()
{
$columns = (new ColumnCollection())
->add(
(new DataColumn('id_link_block'))
->setName($this->trans('ID', [], 'Modules.Linklist.Admin'))
->setOptions([
'field' => 'id_link_block',
])
)
->add(
(new DataColumn('block_name'))
->setName($this->trans('Name of the block', [], 'Modules.Linklist.Admin'))
->setOptions([
'field' => 'block_name',
])
)
->add(
(new ActionColumn('actions'))
->setOptions([
'actions' => (new RowActionCollection())
->add(
(new LinkRowAction('edit'))
->setIcon('edit')
->setOptions([
'route' => 'admin_link_block_edit',
'route_param_name' => 'linkBlockId',
'route_param_field' => 'id_link_block',
])
)
->add(
(new SubmitRowAction('delete'))
->setName($this->trans('Delete', [], 'Admin.Actions'))
->setIcon('delete')
->setOptions([
'method' => 'POST',
'route' => 'admin_link_block_delete',
'route_param_name' => 'linkBlockId',
'route_param_field' => 'id_link_block',
'confirm_message' => $this->trans(
'Delete selected item?',
[],
'Admin.Notifications.Warning'
),
])
),
])
)
;
if ($this->multistoreContextChecker->isSingleShopContext()) {
$columns->addBefore(
'actions',
(new PositionColumn('position'))
->setName($this->trans('Position', [], 'Admin.Global'))
->setOptions([
'id_field' => 'id_link_block',
'position_field' => 'position',
'update_route' => 'admin_link_block_update_positions',
'update_method' => 'POST',
'record_route_params' => [
'id_hook' => 'hookId',
],
])
);
} else {
$columns->addBefore(
'actions',
(new DataColumn('shop_name'))
->setName($this->trans('Shop', [], 'Admin.Global'))
->setOptions([
'field' => 'shop_name',
'sortable' => false,
])
);
}
return $columns;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,129 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Core\Grid;
use PrestaShop\Module\LinkList\Core\Grid\Definition\Factory\LinkBlockDefinitionFactory;
use PrestaShop\Module\LinkList\Core\Search\Filters\LinkBlockFilters;
use PrestaShop\PrestaShop\Adapter\Shop\Context;
use PrestaShop\PrestaShop\Core\Grid\Data\Factory\GridDataFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\Filter\GridFilterFormFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\GridFactory;
use PrestaShop\PrestaShop\Core\Grid\GridInterface;
use PrestaShop\PrestaShop\Core\Hook\HookDispatcherInterface;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Class LinkBlockGridFactory.
*/
final class LinkBlockGridFactory
{
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var HookDispatcherInterface
*/
private $hookDispatcher;
/**
* @var GridDataFactoryInterface
*/
private $dataFactory;
/**
* @var GridFilterFormFactoryInterface
*/
private $filterFormFactory;
/**
* @var Context
*/
private $shopContext;
/**
* HookGridFactory constructor.
*
* @param TranslatorInterface $translator
* @param HookDispatcherInterface $hookDispatcher
* @param GridDataFactoryInterface $dataFactory
* @param GridFilterFormFactoryInterface $filterFormFactory
* @param Context $shopContext
*/
public function __construct(
TranslatorInterface $translator,
GridDataFactoryInterface $dataFactory,
HookDispatcherInterface $hookDispatcher,
GridFilterFormFactoryInterface $filterFormFactory,
Context $shopContext
) {
$this->translator = $translator;
$this->hookDispatcher = $hookDispatcher;
$this->dataFactory = $dataFactory;
$this->filterFormFactory = $filterFormFactory;
$this->shopContext = $shopContext;
}
/**
* @param array $hooks
* @param array $filtersParams
*
* @return GridInterface[]
*/
public function getGrids(array $hooks, array $filtersParams)
{
$grids = [];
foreach ($hooks as $hook) {
$hookParams = $filtersParams;
$hookParams['filters']['id_hook'] = $hook['id_hook'];
$hookParams['filters']['id_shop'] = $this->shopContext->getContextListShopID();
$filters = new LinkBlockFilters($hookParams);
$gridFactory = $this->buildGridFactoryByHook($hook);
$grids[] = $gridFactory->getGrid($filters);
}
return $grids;
}
/**
* Each definition depends on the hook, therefore each factory also
* depends on the hook.
*
* @param array $hook
*
* @return GridFactory
*/
private function buildGridFactoryByHook(array $hook)
{
$definitionFactory = new LinkBlockDefinitionFactory($hook, $this->shopContext);
$definitionFactory->setTranslator($this->translator);
$definitionFactory->setHookDispatcher($this->hookDispatcher);
return new GridFactory(
$definitionFactory,
$this->dataFactory,
$this->filterFormFactory
);
}
}

View File

@@ -0,0 +1,133 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Core\Grid\Query;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use PrestaShop\PrestaShop\Core\Grid\Query\AbstractDoctrineQueryBuilder;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;
/**
* Class LinkBlockQueryBuilder.
*/
final class LinkBlockQueryBuilder extends AbstractDoctrineQueryBuilder
{
/**
* @param SearchCriteriaInterface|null $searchCriteria
*
* @return QueryBuilder
*/
public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria = null)
{
$qb = $this->getQueryBuilder($searchCriteria->getFilters());
$qb->select('
lb.id_link_block,
lbl.name AS block_name,
lb.id_hook,
h.name as hook_name,
h.title as hook_title,
h.description as hook_description,
lbs.position as position,
GROUP_CONCAT(s.name SEPARATOR ", ") as shop_name
')
->groupBy('lb.id_link_block')
->orderBy(
$searchCriteria->getOrderBy(),
$searchCriteria->getOrderWay()
)
;
if ($searchCriteria->getLimit() > 0) {
$qb
->setFirstResult($searchCriteria->getOffset())
->setMaxResults($searchCriteria->getLimit())
;
}
return $qb;
}
/**
* @param SearchCriteriaInterface|null $searchCriteria
*
* @return QueryBuilder
*/
public function getCountQueryBuilder(SearchCriteriaInterface $searchCriteria = null)
{
$qb = $this->getQueryBuilder($searchCriteria->getFilters());
$qb->select('COUNT(lb.id_link_block)');
return $qb;
}
/**
* Get generic query builder.
*
* @param array $filters
*
* @return QueryBuilder
*/
private function getQueryBuilder(array $filters)
{
$qb = $this->connection
->createQueryBuilder()
->from($this->dbPrefix . 'link_block', 'lb')
->innerJoin('lb', $this->dbPrefix . 'link_block_lang', 'lbl', 'lb.id_link_block = lbl.id_link_block')
->leftJoin('lb', $this->dbPrefix . 'link_block_shop', 'lbs', 'lb.id_link_block = lbs.id_link_block')
->leftJoin('lb', $this->dbPrefix . 'hook', 'h', 'lb.id_hook = h.id_hook')
->leftJoin('lb', $this->dbPrefix . 'shop', 's', 's.id_shop = lbs.id_shop');
foreach ($filters as $name => $value) {
if ('id_lang' === $name) {
$qb
->andWhere("lbl.id_lang = :$name")
->setParameter($name, $value)
;
continue;
}
if ('id_hook' === $name) {
$qb
->andWhere("h.id_hook = :$name")
->setParameter($name, $value)
;
continue;
}
if ('id_shop' === $name) {
$qb
->andWhere("lbs.id_shop IN (:$name)")
->setParameter($name, $value, Connection::PARAM_STR_ARRAY);
continue;
}
$qb
->andWhere(sprintf('lbl.%s LIKE :%s', $name, $name))
->setParameter($name, '%' . $value . '%')
;
}
return $qb;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,44 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Core\Search\Filters;
use PrestaShop\PrestaShop\Core\Search\Filters;
/**
* Class LinkBlockFilters.
*/
final class LinkBlockFilters extends Filters
{
/**
* {@inheritdoc}
*/
public static function getDefaults()
{
return [
'id_shop' => null,
'limit' => 0,
'offset' => 0,
'orderBy' => 'position',
'sortOrder' => 'asc',
'filters' => [],
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,186 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList;
use Configuration;
use Db;
use Hook;
use Language;
use PrestaShop\Module\LinkList\Model\LinkBlock;
/**
* Class used to migrate data from the 1.6 module
*/
class DataMigration
{
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* Retrieve content from 1.6 module, then cleanup
*/
public function migrateData()
{
// Copy first table
$this->db->execute(
'INSERT INTO `' . _DB_PREFIX_ . 'link_block`
(`id_link_block`, `id_hook`, `position`)
SELECT `id_cms_block`, `location`, `position`
FROM `' . _DB_PREFIX_ . 'cms_block`'
);
// Update hook IDs (Got from BlockCMSModel in 1.6 module)
$relationBetweenOldLocationsAndHooks = [
0 => 'displayLeftColumn', // LEFT_COLUMN
1 => 'displayRightColumn', // RIGHT_COLUMN
2 => 'displayFooter', // FOOTER
];
foreach ($relationBetweenOldLocationsAndHooks as $oldLocation => $newHookLocation) {
// Retrieve the cms page IDs linked in the old module
$content = $this->generateJsonForBlockContent([
'cms' => $this->getCmsIdsFromBlock($oldLocation),
]);
$this->db->execute(
'UPDATE `' . _DB_PREFIX_ . 'link_block`
SET `id_hook` = ' . (int) Hook::getIdByName($newHookLocation) . ",
`content` = '" . pSQL($content) . "'
WHERE `id_hook` = " . $oldLocation
);
}
// Copy second table (lang)
$this->db->execute(
'INSERT INTO `' . _DB_PREFIX_ . 'link_block_lang`
(`id_link_block`, `id_lang`, `name`)
SELECT `id_cms_block`, `id_lang`, `name`
FROM `' . _DB_PREFIX_ . 'cms_block_lang`'
);
// Copy third table (shop)
$this->db->execute(
'INSERT INTO `' . _DB_PREFIX_ . 'link_block_shop`
(`id_link_block`, `id_shop`)
SELECT `id_cms_block`, `id_shop`
FROM `' . _DB_PREFIX_ . 'cms_block_shop`'
);
$this->migrateBlockFooter();
// Drop old tables
$this->db->execute(
'DROP TABLE `' . _DB_PREFIX_ . 'cms_block`,
`' . _DB_PREFIX_ . 'cms_block_lang`,
`' . _DB_PREFIX_ . 'cms_block_page`,
`' . _DB_PREFIX_ . 'cms_block_shop`'
);
}
private function migrateBlockFooter()
{
if (!Configuration::get('FOOTER_BLOCK_ACTIVATION')) {
return;
}
$linkBlock = new LinkBlock();
$data = [];
$footerCMS = Configuration::get('FOOTER_CMS');
if (!empty($footerCMS)) {
foreach (explode('|', $footerCMS) as $val) {
list(, $cmsId) = explode('_', $val);
$data['cms'][] = $cmsId;
}
}
if (Configuration::get('FOOTER_PRICE-DROP')) {
$data['product'][] = 'prices-drop';
}
if (Configuration::get('FOOTER_NEW-PRODUCTS')) {
$data['product'][] = 'new-products';
}
if (Configuration::get('FOOTER_BEST-SALES')) {
$data['product'][] = 'best-sales';
}
if (Configuration::get('FOOTER_CONTACT')) {
$data['static'][] = 'contact';
}
if (Configuration::get('FOOTER_SITEMAP')) {
$data['static'][] = 'sitemap';
}
if (Configuration::get('PS_STORES_DISPLAY_FOOTER')) {
$data['static'][] = 'stores';
}
$linkBlock->content = $this->generateJsonForBlockContent($data);
$linkBlock->id_hook = (int) Hook::getIdByName('displayFooter');
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
$linkBlock->name[$lang['id_lang']] = 'Footer content (Migrated)';
$linkBlock->custom_content[$lang['id_lang']] = json_encode([[
'title' => Configuration::get('FOOTER_CMS_TEXT_' . $lang['id_lang']),
'url' => '#',
]]);
}
$linkBlock->save();
}
/**
* Generate a JSON for the column `content` of link_block
*
* @param array $data
*
* @return string
*/
private function generateJsonForBlockContent(array $data)
{
return json_encode([
'cms' => empty($data['cms']) ? [false] : $data['cms'],
'static' => empty($data['static']) ? [false] : $data['static'],
'product' => empty($data['product']) ? [false] : $data['product'],
]);
}
/**
* Get list of cms IDs from database for a given old cms_block_page
*
* @param int $oldLocation
*
* @return array
*/
private function getCmsIdsFromBlock($oldLocation)
{
$request = $this->db->executeS(
'SELECT id_cms FROM `' . _DB_PREFIX_ . 'cms_block_page`
WHERE id_cms_block = ' . (int) $oldLocation . '
AND is_category = 0'
);
$ids = [];
foreach ($request as $row) {
$ids[] = $row['id_cms'];
}
return $ids;
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\ChoiceProvider;
use Doctrine\DBAL\Connection;
use PrestaShop\PrestaShop\Core\Form\FormChoiceProviderInterface;
/**
* Class AbstractDatabaseChoiceProvider.
*/
abstract class AbstractDatabaseChoiceProvider implements FormChoiceProviderInterface
{
/**
* @var Connection
*/
protected $connection;
/**
* @var string
*/
protected $dbPrefix;
/**
* @var int
*/
protected $idLang;
/**
* @var array
*/
protected $shopIds;
/**
* AbstractDatabaseChoiceProvider constructor.
*
* @param Connection $connection
* @param string $dbPrefix
* @param int|null $idLang
* @param array|null $shopIds
*/
public function __construct(Connection $connection, $dbPrefix, $idLang = null, array $shopIds = null)
{
$this->connection = $connection;
$this->dbPrefix = $dbPrefix;
$this->idLang = $idLang;
$this->shopIds = $shopIds;
}
/**
* {@inheritdoc}
*/
abstract public function getChoices();
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\ChoiceProvider;
/**
* Class CMSCategoryChoiceProvider.
*/
final class CMSCategoryChoiceProvider extends AbstractDatabaseChoiceProvider
{
/**
* @return array
*/
public function getChoices()
{
$qb = $this->connection->createQueryBuilder();
$qb
->select('cc.id_cms_category, ccl.name')
->from($this->dbPrefix . 'cms_category', 'cc')
->innerJoin('cc', $this->dbPrefix . 'cms_category_lang', 'ccl', 'cc.id_cms_category = ccl.id_cms_category')
->innerJoin('cc', $this->dbPrefix . 'cms_category_shop', 'ccs', 'cc.id_cms_category = ccs.id_cms_category')
->andWhere('cc.active = 1')
->andWhere('ccl.id_lang = :idLang')
->andWhere('ccs.id_shop IN (:shopIds)')
->setParameter('idLang', $this->idLang)
->setParameter('shopIds', implode(',', $this->shopIds))
->orderBy('ccl.name')
;
$categories = $qb->execute()->fetchAll();
$choices = [];
foreach ($categories as $category) {
$choices[$category['name']] = $category['id_cms_category'];
}
return $choices;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\ChoiceProvider;
use Doctrine\DBAL\Connection;
/**
* Class CMSPageChoiceProvider.
*/
final class CMSPageChoiceProvider extends AbstractDatabaseChoiceProvider
{
/**
* @var array
*/
private $categories;
/**
* CMSPageChoiceProvider constructor.
*
* @param Connection $connection
* @param string $dbPrefix
* @param array $categories
* @param int $idLang
* @param array $shopIds
*/
public function __construct(
Connection $connection,
$dbPrefix,
array $categories,
$idLang,
$shopIds
) {
parent::__construct($connection, $dbPrefix, $idLang, $shopIds);
$this->categories = $categories;
}
/**
* @return array
*/
public function getChoices()
{
$choices = [];
foreach ($this->categories as $categoryName => $categoryId) {
$qb = $this->connection->createQueryBuilder();
$qb
->select('c.id_cms, cl.meta_title')
->from($this->dbPrefix . 'cms', 'c')
->innerJoin('c', $this->dbPrefix . 'cms_lang', 'cl', 'c.id_cms = cl.id_cms')
->innerJoin('c', $this->dbPrefix . 'cms_shop', 'cs', 'c.id_cms = cs.id_cms')
->andWhere('c.active = 1')
->andWhere('cl.id_lang = :idLang')
->andWhere('cs.id_shop IN (:shopIds)')
->andWhere('c.id_cms_category = :idCmsCategory')
->setParameter('idCmsCategory', $categoryId)
->setParameter('idLang', $this->idLang)
->setParameter('shopIds', implode(',', $this->shopIds))
->orderBy('c.position')
;
$pages = $qb->execute()->fetchAll();
foreach ($pages as $page) {
$choices[$categoryName][$page['id_cms'] . ' ' . $page['meta_title']] = $page['id_cms'];
}
}
return $choices;
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\ChoiceProvider;
/**
* Class CategoryChoiceProvider.
*/
final class CategoryChoiceProvider extends AbstractDatabaseChoiceProvider
{
/**
* @return array
*/
public function getChoices()
{
$qb = $this->connection->createQueryBuilder();
$qb
->select('cc.id_category, ccl.name')
->from($this->dbPrefix . 'category', 'cc')
->innerJoin('cc', $this->dbPrefix . 'category_lang', 'ccl', 'cc.id_category = ccl.id_category')
->innerJoin('cc', $this->dbPrefix . 'category_shop', 'ccs', 'cc.id_category = ccs.id_category')
->andWhere('cc.active = 1')
->andWhere('ccl.id_lang = :idLang')
->andWhere('ccs.id_shop IN (:shopIds)')
->setParameter('idLang', $this->idLang)
->setParameter('shopIds', implode(',', $this->shopIds))
->orderBy('ccl.name')
;
$categories = $qb->execute()->fetchAll();
$choices = [];
foreach ($categories as $category) {
$choices[$category['name']] = $category['id_category'];
}
return $choices;
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\ChoiceProvider;
/**
* Class HookChoiceProvider.
*/
final class HookChoiceProvider extends AbstractDatabaseChoiceProvider
{
/**
* @return mixed
*/
public function getChoices()
{
$qb = $this->connection->createQueryBuilder();
$qb
->select('h.id_hook, h.name')
->from($this->dbPrefix . 'hook', 'h')
->andWhere('h.name LIKE :displayHook')
->setParameter('displayHook', 'display%')
->orderBy('h.name')
;
$hooks = $qb->execute()->fetchAll();
$choices = [];
foreach ($hooks as $hook) {
$choices[$hook['name']] = $hook['id_hook'];
}
return $choices;
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\ChoiceProvider;
use Doctrine\DBAL\Connection;
use PrestaShop\PrestaShop\Core\Foundation\Database\EntityNotFoundException;
use Tools;
/**
* Class PageChoiceProvider.
*/
final class PageChoiceProvider extends AbstractDatabaseChoiceProvider
{
/**
* @var array
*/
private $pageNames;
/**
* PageChoiceProvider constructor.
*
* @param Connection $connection
* @param string $dbPrefix
* @param int $idLang
* @param array $shopIds
* @param array $pageNames
*/
public function __construct(
Connection $connection,
$dbPrefix,
$idLang,
array $shopIds,
array $pageNames
) {
parent::__construct($connection, $dbPrefix, $idLang, $shopIds);
$this->pageNames = $pageNames;
}
/**
* @return array
*
* @throws EntityNotFoundException
*/
public function getChoices()
{
$choices = [];
foreach ($this->pageNames as $pageName) {
$qb = $this->connection->createQueryBuilder();
$qb
->select('m.id_meta, ml.title')
->from($this->dbPrefix . 'meta', 'm')
->leftJoin('m', $this->dbPrefix . 'meta_lang', 'ml', 'm.id_meta = ml.id_meta')
->andWhere($qb->expr()->orX('m.page = :page', 'm.page = :pageSlug'))
->andWhere('ml.id_lang = :idLang')
->andWhere('ml.id_shop IN (:shopIds)')
->setParameter('idLang', $this->idLang)
->setParameter('shopIds', implode(',', $this->shopIds))
->setParameter('page', $pageName)
->setParameter('pageSlug', str_replace('-', '', Tools::strtolower($pageName)))
;
$meta = $qb->execute()->fetchAll();
if (!empty($meta)) {
$choices[$meta[0]['title']] = $pageName;
}
}
return $choices;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,340 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form;
use Hook;
use Language;
use PrestaShop\Module\LinkList\Cache\LinkBlockCacheInterface;
use PrestaShop\Module\LinkList\Model\LinkBlock;
use PrestaShop\Module\LinkList\Repository\LinkBlockRepository;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Adapter\Shop\Context;
use PrestaShop\PrestaShop\Core\Addon\Module\ModuleRepository;
use PrestaShop\PrestaShop\Core\Form\FormDataProviderInterface;
use Ps_Linklist;
/**
* Class LinkBlockFormDataProvider.
*/
class LinkBlockFormDataProvider implements FormDataProviderInterface
{
/**
* @var int|null
*/
private $idLinkBlock;
/**
* @var LinkBlockRepository
*/
private $repository;
/**
* @var LinkBlockCacheInterface
*/
private $cache;
/**
* @var ModuleRepository
*/
private $moduleRepository;
/**
* @var array
*/
private $languages;
/**
* @var Context
*/
private $shopContext;
/**
* @var Configuration
*/
private $configuration;
/**
* LinkBlockFormDataProvider constructor.
*
* @param LinkBlockRepository $repository
* @param LinkBlockCacheInterface $cache
* @param ModuleRepository $moduleRepository
* @param array $languages
* @param Context $shopContext
* @param Configuration $configuration
*/
public function __construct(
LinkBlockRepository $repository,
LinkBlockCacheInterface $cache,
ModuleRepository $moduleRepository,
array $languages,
Context $shopContext,
Configuration $configuration
) {
$this->repository = $repository;
$this->cache = $cache;
$this->moduleRepository = $moduleRepository;
$this->languages = $languages;
$this->shopContext = $shopContext;
$this->configuration = $configuration;
}
/**
* @return array
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function getData()
{
if (null === $this->idLinkBlock) {
return [
'link_block' => [
'shop_association' => $this->shopContext->getContextListShopID(),
],
];
}
$linkBlock = new LinkBlock($this->idLinkBlock);
$arrayLinkBlock = $linkBlock->toArray();
//The form and the database model don't have the same data hierarchy
//Transform array $custom[en][1][name] to $custom[1][en][name]
$arrayCustom = [];
foreach ($arrayLinkBlock['custom_content'] as $idLang => $customs) {
if (!is_array($customs)) {
continue;
}
foreach ($customs as $i => $custom) {
$arrayCustom[$i][$idLang] = $custom;
}
}
return ['link_block' => [
'id_link_block' => $arrayLinkBlock['id'],
'block_name' => $arrayLinkBlock['name'],
'id_hook' => $arrayLinkBlock['id_hook'],
'cms' => isset($arrayLinkBlock['content']['cms']) ? $arrayLinkBlock['content']['cms'] : [],
'product' => isset($arrayLinkBlock['content']['product']) ? $arrayLinkBlock['content']['product'] : [],
'static' => isset($arrayLinkBlock['content']['static']) ? $arrayLinkBlock['content']['static'] : [],
'category' => isset($arrayLinkBlock['content']['category']) ? $arrayLinkBlock['content']['category'] : [],
'custom' => $arrayCustom,
'shop_association' => $arrayLinkBlock['shop_association'],
]];
}
/**
* Make sure to fill empty multilang fields if value for default is available
*
* @param array $linkBlock
*
* @return array
*/
public function prepareData(array $linkBlock): array
{
$defaultLanguageId = (int) $this->configuration->get('PS_LANG_DEFAULT');
if (!empty($linkBlock['block_name'])) {
foreach ($this->languages as $language) {
if (empty($linkBlock['block_name'][$language['id_lang']])) {
$linkBlock['block_name'][$language['id_lang']] = $linkBlock['block_name'][$defaultLanguageId];
}
}
}
if (!empty($linkBlock['custom'])) {
foreach ($linkBlock['custom'] as $key => $customLanguages) {
if ($this->isEmptyCustom($customLanguages)) {
continue;
}
foreach ($customLanguages as $idLang => $custom) {
$linkBlock['custom'][$key][$idLang] = [
'title' => $custom['title'] ?? $customLanguages[$defaultLanguageId]['title'],
'url' => $custom['url'] ?? $customLanguages[$defaultLanguageId]['url'],
];
}
}
}
return $linkBlock;
}
/**
* @param array $data
*
* @return array
*
* @throws \PrestaShop\PrestaShop\Adapter\Entity\PrestaShopDatabaseException
*/
public function setData(array $data)
{
$linkBlock = $this->prepareData($data['link_block']);
$errors = $this->validateLinkBlock($linkBlock);
if (!empty($errors)) {
return $errors;
}
$customContent = [];
if (!empty($linkBlock['custom'])) {
foreach ($linkBlock['custom'] as $customLanguages) {
if ($this->isEmptyCustom($customLanguages)) {
continue;
}
foreach ($customLanguages as $idLang => $custom) {
$customContent[$idLang][] = $custom;
}
}
}
$linkBlock['custom_content'] = $customContent;
$linkBlock['id_shop'] = $this->shopContext->getContextShopID();
if (empty($linkBlock['id_link_block'])) {
$linkBlockId = $this->repository->create($linkBlock);
$this->setIdLinkBlock((int) $linkBlockId);
} else {
$linkBlockId = $linkBlock['id_link_block'];
$this->repository->update($linkBlockId, $linkBlock);
}
$this->updateHook($linkBlock['id_hook']);
$this->cache->clearModuleCache();
return [];
}
/**
* @return int
*/
public function getIdLinkBlock()
{
return $this->idLinkBlock;
}
/**
* @param int $idLinkBlock
*
* @return LinkBlockFormDataProvider
*/
public function setIdLinkBlock($idLinkBlock)
{
$this->idLinkBlock = $idLinkBlock;
return $this;
}
/**
* @param array $data
*
* @return array
*/
private function validateLinkBlock(array $data)
{
$errors = [];
if (!isset($data['id_hook'])) {
$errors[] = [
'key' => 'Missing id_hook',
'domain' => 'Admin.Catalog.Notification',
'parameters' => [],
];
}
if (!isset($data['block_name'])) {
$errors[] = [
'key' => 'Missing block_name',
'domain' => 'Admin.Catalog.Notification',
'parameters' => [],
];
} else {
foreach ($this->languages as $language) {
if (empty($data['block_name'][$language['id_lang']])) {
$errors[] = [
'key' => 'Missing block_name value for language %s',
'domain' => 'Admin.Catalog.Notification',
'parameters' => [$language['iso_code']],
];
}
}
}
if (!isset($data['custom'])) {
return $errors;
}
foreach ($data['custom'] as $customIndex => $custom) {
if ($this->isEmptyCustom($custom)) {
continue;
}
$defaultLanguageId = (int) $this->configuration->get('PS_LANG_DEFAULT');
$fields = ['title', 'url'];
foreach ($fields as $field) {
if (empty($custom[$defaultLanguageId][$field])) {
$errors[] = [
'key' => 'Missing %s value in custom[%s] for language %s',
'domain' => 'Admin.Catalog.Notification',
'parameters' => [$field, $customIndex, Language::getIsoById($defaultLanguageId)],
];
}
}
}
return $errors;
}
/**
* @param array $custom
*
* @return bool
*/
private function isEmptyCustom(array $custom)
{
$fields = ['title', 'url'];
foreach ($custom as $langCustom) {
foreach ($fields as $field) {
if (!empty($langCustom[$field])) {
return false;
}
}
}
return true;
}
/**
* Register the selected hook to this module if it was not registered yet.
*
* @param int $hookId
*
* @throws \PrestaShopException
*/
private function updateHook($hookId)
{
$hookName = Hook::getNameById($hookId);
$module = $this->moduleRepository->getInstanceByName(Ps_Linklist::MODULE_NAME);
if (!Hook::isModuleRegisteredOnHook($module, $hookName, $this->shopContext->getContextShopID())) {
Hook::registerHook($module, $hookName);
}
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\Type;
use PrestaShopBundle\Form\Admin\Type\TranslatorAwareType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;
class CustomUrlType extends TranslatorAwareType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, [
'label' => $this->trans('Title', 'Modules.Linklist.Admin'),
'required' => true,
])
->add('url', TextType::class, [
'label' => $this->trans('URL', 'Modules.Linklist.Admin'),
'required' => true,
'constraints' => [new Assert\Url()],
])
;
}
}

View File

@@ -0,0 +1,214 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\Type;
use PrestaShop\PrestaShop\Core\ConstraintValidator\Constraints\DefaultLanguage;
use PrestaShopBundle\Form\Admin\Type\ShopChoiceTreeType;
use PrestaShopBundle\Form\Admin\Type\TranslateTextType;
use PrestaShopBundle\Form\Admin\Type\TranslatorAwareType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class LinkBlockType extends TranslatorAwareType
{
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var array
*/
private $hookChoices;
/**
* @var array
*/
private $cmsPageChoices;
/**
* @var array
*/
private $productPageChoices;
/**
* @var array
*/
private $staticPageChoices;
/**
* @var array
*/
private $categoryChoices;
/**
* @var bool
*/
private $isMultiStoreUsed;
/**
* LinkBlockType constructor.
*
* @param TranslatorInterface $translator
* @param array $locales
* @param array $hookChoices
* @param array $cmsPageChoices
* @param array $productPageChoices
* @param array $staticPageChoices
* @param array $categoryChoices
*/
public function __construct(
TranslatorInterface $translator,
array $locales,
array $hookChoices,
array $cmsPageChoices,
array $productPageChoices,
array $staticPageChoices,
array $categoryChoices,
bool $isMultiStoreUsed
) {
parent::__construct($translator, $locales);
$this->hookChoices = $hookChoices;
$this->cmsPageChoices = $cmsPageChoices;
$this->productPageChoices = $productPageChoices;
$this->staticPageChoices = $staticPageChoices;
$this->categoryChoices = $categoryChoices;
$this->translator = $translator;
$this->isMultiStoreUsed = $isMultiStoreUsed;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id_link_block', HiddenType::class)
->add('block_name', TranslateTextType::class, [
'locales' => $this->locales,
'required' => true,
'label' => $this->trans('Name of the block', 'Modules.Linklist.Admin'),
'constraints' => [
new DefaultLanguage(),
],
'options' => [
'constraints' => [
new Length([
'max' => 40,
'maxMessage' => $this->translator->trans(
'Name of the block cannot be longer than %limit% characters',
[
'%limit%' => 40,
],
'Modules.Linklist.Admin'
),
]),
],
],
])
->add('id_hook', ChoiceType::class, [
'choices' => $this->hookChoices,
'attr' => [
'data-toggle' => 'select2',
'data-minimumResultsForSearch' => '7',
],
'label' => $this->trans('Hook', 'Admin.Global'),
])
->add('cms', ChoiceType::class, [
'choices' => $this->cmsPageChoices,
'label' => $this->trans('Content pages', 'Modules.Linklist.Admin'),
'multiple' => true,
'expanded' => true,
])
->add('product', ChoiceType::class, [
'choices' => $this->productPageChoices,
'label' => $this->trans('Product pages', 'Modules.Linklist.Admin'),
'multiple' => true,
'expanded' => true,
])
->add('category', ChoiceType::class, [
'choices' => $this->categoryChoices,
'label' => $this->trans('Categories', 'Modules.Linklist.Admin'),
'multiple' => true,
'expanded' => true,
])
->add('static', ChoiceType::class, [
'choices' => $this->staticPageChoices,
'label' => $this->trans('Static content', 'Modules.Linklist.Admin'),
'multiple' => true,
'expanded' => true,
])
->add('custom', CollectionType::class, [
'entry_type' => TranslateCustomUrlType::class,
'entry_options' => [
'locales' => $this->locales,
'label' => false,
],
'attr' => [
'class' => 'custom_collection',
'data-delete-button-label' => $this->trans('Delete', 'Admin.Global'),
],
'allow_add' => true,
'allow_delete' => true,
'label' => $this->trans('Custom content', 'Modules.Linklist.Admin'),
])
;
if ($this->isMultiStoreUsed) {
$builder->add('shop_association', ShopChoiceTreeType::class, [
'label' => $this->trans('Shop association', 'Admin.Global'),
'required' => false,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'You have to select at least one shop to associate this item with',
'Admin.Notifications.Error'
),
]),
],
]);
}
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'label' => false,
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'module_link_block';
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Form\Type;
use PrestaShopBundle\Form\Admin\Type\TranslateTextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class TranslatableUrlType.
*/
class TranslateCustomUrlType extends TranslateTextType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($options['locales'] as $locale) {
$localeOptions = $options['options'];
$localeOptions['label'] = $locale['iso_code'];
if (!isset($localeOptions['required'])) {
$localeOptions['required'] = false;
}
$builder->add($locale['id_lang'], CustomUrlType::class, $localeOptions);
}
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,176 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList;
use Context;
use Db;
use Hook;
use Language;
use PrestaShop\Module\LinkList\Model\LinkBlock;
use Shop;
use Symfony\Component\Translation\TranslatorInterface as Translator;
/**
* Class LegacyLinkBlockRepository.
*/
class LegacyLinkBlockRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Shop
*/
private $shop;
/**
* @var string
*/
private $db_prefix;
/**
* @var Translator
*/
private $translator;
/**
* @param Db $db
* @param Shop $shop
* @param Translator $translator
*/
public function __construct(Db $db, Shop $shop, Translator $translator)
{
$this->db = $db;
$this->shop = $shop;
$this->db_prefix = $db->getPrefix();
$this->translator = $translator;
}
/**
* @param int $id_hook
*
* @return array
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function getByIdHook($id_hook)
{
$id_hook = (int) $id_hook;
$sql = "SELECT lb.`id_link_block`
FROM {$this->db_prefix}link_block lb
INNER JOIN {$this->db_prefix}link_block_shop lbs ON lbs.`id_link_block` = lb.`id_link_block`
WHERE lb. `id_hook` = $id_hook AND lbs.`id_shop` = {$this->shop->id}
ORDER by lbs.`position`
";
$ids = $this->db->executeS($sql);
$cmsBlock = [];
foreach ($ids as $id) {
$cmsBlock[] = new LinkBlock((int) $id['id_link_block']);
}
return $cmsBlock;
}
/**
* @return bool
*/
public function createTables()
{
$engine = _MYSQL_ENGINE_;
$success = true;
$this->dropTables();
$queries = [
"CREATE TABLE IF NOT EXISTS `{$this->db_prefix}link_block`(
`id_link_block` int(10) unsigned NOT NULL auto_increment,
`id_hook` int(1) unsigned DEFAULT NULL,
`position` int(10) unsigned NOT NULL default '0',
`content` text default NULL,
PRIMARY KEY (`id_link_block`)
) ENGINE=$engine DEFAULT CHARSET=utf8",
"CREATE TABLE IF NOT EXISTS `{$this->db_prefix}link_block_lang`(
`id_link_block` int(10) unsigned NOT NULL,
`id_lang` int(10) unsigned NOT NULL,
`name` varchar(40) NOT NULL default '',
`custom_content` text default NULL,
PRIMARY KEY (`id_link_block`, `id_lang`)
) ENGINE=$engine DEFAULT CHARSET=utf8",
"CREATE TABLE IF NOT EXISTS `{$this->db_prefix}link_block_shop` (
`id_link_block` int(10) unsigned NOT NULL auto_increment,
`id_shop` int(10) unsigned NOT NULL,
`position` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`id_link_block`, `id_shop`)
) ENGINE=$engine DEFAULT CHARSET=utf8",
];
foreach ($queries as $query) {
$success &= $this->db->execute($query);
}
return (bool) $success;
}
public function dropTables()
{
$sql = "DROP TABLE IF EXISTS
`{$this->db_prefix}link_block`,
`{$this->db_prefix}link_block_lang`,
`{$this->db_prefix}link_block_shop`";
return $this->db->execute($sql);
}
/**
* @return bool
*/
public function installFixtures()
{
$success = true;
$id_hook = (int) Hook::getIdByName('displayFooter');
$queries = [
'INSERT INTO `' . $this->db_prefix . 'link_block` (`id_link_block`, `id_hook`, `position`, `content`) VALUES
(1, ' . $id_hook . ', 0, \'{"cms":[false],"product":["prices-drop","new-products","best-sales"],"static":[false]}\'),
(2, ' . $id_hook . ', 1, \'{"cms":["1","2","3","4","5"],"product":[false],"static":["contact","sitemap","stores"]}\');',
];
foreach (Language::getLanguages(true, Context::getContext()->shop->id) as $lang) {
$queries[] = 'INSERT INTO `' . $this->db_prefix . 'link_block_lang` (`id_link_block`, `id_lang`, `name`) VALUES
(1, ' . (int) $lang['id_lang'] . ', "' . pSQL($this->translator->trans('Products', [], 'Modules.Linklist.Shop', $lang['locale'])) . '"),
(2, ' . (int) $lang['id_lang'] . ', "' . pSQL($this->translator->trans('Our company', [], 'Modules.Linklist.Shop', $lang['locale'])) . '");'
;
}
foreach ($this->shop::getContextListShopID() as $shopId) {
$queries[] = 'INSERT INTO `' . $this->db_prefix . 'link_block_shop` (`id_link_block`, `id_shop`, `position`) VALUES
(1, ' . (int) $shopId . ', 0),
(2, ' . (int) $shopId . ', 1);'
;
}
foreach ($queries as $query) {
$success &= $this->db->execute($query);
}
return $success;
}
}

View File

@@ -0,0 +1,145 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Model;
use Shop;
/**
* Class LinkBlock.
*/
class LinkBlock extends \ObjectModel
{
/**
* @var int
*/
public $id_link_block;
/**
* @var string
*/
public $name;
/**
* @var int
*/
public $id_hook;
/**
* @var int
*/
public $position;
/**
* @var array|string|null
*/
public $content;
/**
* @var array
*/
public $custom_content;
/**
* @see ObjectModel::$definition
*/
public static $definition = [
'table' => 'link_block',
'primary' => 'id_link_block',
'multilang' => true,
'fields' => [
'name' => ['type' => self::TYPE_STRING, 'lang' => true, 'required' => true, 'size' => 40],
'id_hook' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true],
'position' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true],
'content' => ['type' => self::TYPE_STRING, 'validate' => 'isJson'],
'custom_content' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isJson'],
],
];
public function __construct($id = null, $id_lang = null, $id_shop = null)
{
Shop::addTableAssociation('link_block', ['type' => 'shop']);
parent::__construct($id, $id_lang, $id_shop);
if ($this->id) {
$this->content = json_decode($this->content, true);
if ($this->custom_content) {
$this->custom_content = array_map(
function ($el) {
return json_decode($el, true);
},
$this->custom_content
);
}
}
if (is_null($this->content)) {
$this->content = [
'cms' => [],
'product' => [],
'static' => [],
'category' => [],
];
}
}
public function add($auto_date = true, $null_values = false)
{
if (is_array($this->content)) {
$this->content = json_encode($this->content);
}
if (!$this->position) {
$this->position = 1;
}
$return = parent::add($auto_date, $null_values);
$this->content = json_decode($this->content, true);
return $return;
}
public function update($auto_date = true, $null_values = false)
{
if (is_array($this->content)) {
$this->content = json_encode($this->content);
}
$return = parent::update($null_values);
$this->content = json_decode($this->content, true);
return $return;
}
public function toArray()
{
return [
'id' => $this->id,
'id_link_block' => $this->id,
'name' => $this->name,
'id_hook' => $this->id_hook,
'position' => $this->position,
'content' => $this->content,
'custom_content' => $this->custom_content,
'shop_association' => $this->getAssociatedShops(),
];
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Model;
use DataLangCore;
/**
* Class LinkBlockLang.
*/
class LinkBlockLang extends DataLangCore
{
// Don't replace domain in init() with $this->domain for translation parsing
protected $domain = 'Modules.Linklist.Shop';
protected $keys = ['id_link_block'];
protected $fieldsToUpdate = ['name'];
/**
* @var array<string, array<string, string>>
*/
public $fieldNames = [];
protected function init()
{
$this->fieldNames = [
'name' => [
md5('Products') => $this->translator->trans('Products', [], 'Modules.Linklist.Shop', $this->locale),
md5('Our company') => $this->translator->trans('Our company', [], 'Modules.Linklist.Shop', $this->locale),
],
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,257 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Presenter;
use Meta;
use PrestaShop\Module\LinkList\Model\LinkBlock;
use Tools;
/**
* Class LinkBlockPresenter.
*/
class LinkBlockPresenter
{
private $link;
private $language;
/**
* LinkBlockPresenter constructor.
*
* @param \Link $link
* @param \Language $language
*/
public function __construct(\Link $link, \Language $language)
{
$this->link = $link;
$this->language = $language;
}
/**
* @param LinkBlock $cmsBlock
*
* @return array
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function present(LinkBlock $cmsBlock)
{
return [
'id' => (int) $cmsBlock->id,
'title' => $cmsBlock->name[(int) $this->language->id],
'hook' => (new \Hook((int) $cmsBlock->id_hook))->name,
'position' => $cmsBlock->position,
'links' => $this->makeLinks($cmsBlock->content, $cmsBlock->custom_content),
];
}
/**
* Check the url if is an external link.
*
* @param string $url
*
* @return bool
*/
public function isExternalLink($url)
{
$baseLink = preg_replace('#^(http)s?://#', '', $this->link->getBaseLink());
$url = Tools::strtolower($url);
if (preg_match('#^(http)s?://#', $url) && !preg_match('#^(http)s?://' . preg_quote(rtrim($baseLink, '/'), '/') . '#', $url)) {
return true;
}
return false;
}
/**
* @param array $content
* @param array $custom_content
*
* @return array
*/
private function makeLinks($content, $custom_content)
{
$cmsLinks = $productLinks = $staticsLinks = $customLinks = $categoryLinks = [];
if (isset($content['cms'])) {
$cmsLinks = $this->makeCmsLinks($content['cms']);
}
if (isset($content['product'])) {
$productLinks = $this->makeProductLinks($content['product']);
}
if (isset($content['static'])) {
$staticsLinks = $this->makeStaticLinks($content['static']);
}
if (isset($content['category'])) {
$categoryLinks = $this->makeCategoryLinks($content['category']);
}
$customLinks = $this->makeCustomLinks($custom_content);
return array_merge(
$cmsLinks,
$productLinks,
$staticsLinks,
$customLinks,
$categoryLinks
);
}
/**
* @param array $cmsIds
*
* @return array
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
private function makeCmsLinks($cmsIds)
{
$cmsLinks = [];
foreach ($cmsIds as $cmsId) {
$cms = new \CMS((int) $cmsId);
if (null !== $cms->id && $cms->active) {
$cmsLinks[] = [
'id' => 'link-cms-page-' . $cms->id,
'class' => 'cms-page-link',
'title' => $cms->meta_title[(int) $this->language->id],
'description' => $cms->meta_description[(int) $this->language->id],
'url' => $this->link->getCMSLink($cms),
];
}
}
return $cmsLinks;
}
/**
* @param array $productIds
*
* @return array
*/
private function makeProductLinks($productIds)
{
$productLinks = [];
foreach ($productIds as $productId) {
if (false === $productId) {
continue;
}
$meta = \Meta::getMetaByPage($productId, (int) $this->language->id);
$productLinks[] = [
'id' => 'link-product-page-' . $productId,
'class' => 'cms-page-link',
'title' => $meta['title'],
'description' => $meta['description'],
'url' => $this->link->getPageLink($productId, true),
];
}
return $productLinks;
}
/**
* @param array $staticIds
*
* @return array
*/
private function makeStaticLinks($staticIds)
{
$staticLinks = [];
foreach ($staticIds as $staticId) {
if (false === $staticId) {
continue;
}
$meta = \Meta::getMetaByPage($staticId, (int) $this->language->id);
$staticLinks[] = [
'id' => 'link-static-page-' . $staticId,
'class' => 'cms-page-link',
'title' => $meta['title'],
'description' => $meta['description'],
'url' => $this->link->getPageLink($staticId, true),
];
}
return $staticLinks;
}
/**
* @param array $customContent
*
* @return array
*/
private function makeCustomLinks($customContent)
{
$customLinks = [];
if (!isset($customContent[$this->language->id])) {
return $customLinks;
}
$customLinks = $customContent[$this->language->id];
$self = $this;
$customLinks = array_map(function ($el) use ($self) {
return [
'id' => 'link-custom-page-' . Tools::link_rewrite($el['title']),
'class' => 'custom-page-link',
'title' => $el['title'],
'description' => '',
'url' => $el['url'],
'target' => $self->isExternalLink($el['url']) ? '_blank' : '',
];
}, array_filter($customLinks));
return $customLinks;
}
/**
* @param array $categoryIds
*
* @return array
*/
private function makeCategoryLinks($categoryIds)
{
$categoryLinks = [];
foreach ($categoryIds as $categoryId) {
if (false === $categoryId) {
continue;
}
$meta = Meta::getCategoryMetas($categoryId, (int) $this->language->id, '', null);
$categoryLinks[] = [
'id' => 'link-category-' . $categoryId,
'class' => 'category-link',
'title' => $meta['name'],
'description' => strip_tags($meta['description']),
'url' => $this->link->getCategoryLink((int) $categoryId),
];
}
return $categoryLinks;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,515 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\LinkList\Repository;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\Exception\ConnectionException;
use Doctrine\DBAL\Query\QueryBuilder;
use Hook;
use PrestaShop\Module\LinkList\Adapter\ObjectModelHandler;
use PrestaShop\PrestaShop\Adapter\Shop\Context;
use PrestaShop\PrestaShop\Core\Exception\DatabaseException;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Class LinkBlockRepository.
*/
class LinkBlockRepository
{
/**
* @var Connection
*/
private $connection;
/**
* @var string
*/
private $dbPrefix;
/**
* @var array
*/
private $languages;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var bool
*/
private $isMultiStoreUsed;
/**
* @var Context
*/
private $multiStoreContext;
/**
* @var ObjectModelHandler
*/
private $objectModelHandler;
/**
* LinkBlockRepository constructor.
*
* @param Connection $connection
* @param string $dbPrefix
* @param array $languages
* @param TranslatorInterface $translator
*/
public function __construct(
Connection $connection,
$dbPrefix,
array $languages,
TranslatorInterface $translator,
bool $isMultiStoreUsed,
Context $multiStoreContext,
ObjectModelHandler $objectModelHandler
) {
$this->connection = $connection;
$this->dbPrefix = $dbPrefix;
$this->languages = $languages;
$this->translator = $translator;
$this->isMultiStoreUsed = $isMultiStoreUsed;
$this->objectModelHandler = $objectModelHandler;
$this->multiStoreContext = $multiStoreContext;
}
/**
* Returns the list of hook with associated Link blocks.
*
* @return array
*/
public function getHooksWithLinks()
{
$qb = $this->connection->createQueryBuilder();
$qb
->select('h.id_hook, h.name, h.title')
->from($this->dbPrefix . 'link_block', 'lb')
->leftJoin('lb', $this->dbPrefix . 'hook', 'h', 'lb.id_hook = h.id_hook')
->groupBy('h.id_hook')
->orderBy('h.name')
;
return $qb->execute()->fetchAll();
}
/**
* @param array $data
*
* @return string
*
* @throws DatabaseException
*/
public function create(array $data)
{
$idHook = $data['id_hook'];
$qb = $this->connection->createQueryBuilder();
$qb
->insert($this->dbPrefix . 'link_block')
->values([
'id_hook' => ':idHook',
'content' => ':content',
])
->setParameters([
'idHook' => $idHook,
'content' => json_encode([
'cms' => empty($data['cms']) ? [false] : $data['cms'],
'static' => empty($data['static']) ? [false] : $data['static'],
'product' => empty($data['product']) ? [false] : $data['product'],
'category' => empty($data['category']) ? [false] : $data['category'],
]),
]);
$this->executeQueryBuilder($qb, 'Link block error');
$linkBlockId = $this->connection->lastInsertId();
$this->updateLanguages((int) $linkBlockId, $data['block_name'], $data['custom_content']);
$this->objectModelHandler->handleMultiShopAssociation(
(int) $linkBlockId,
$data['shop_association'],
!$this->isMultiStoreUsed
);
$this->updateMaxPosition((int) $linkBlockId, $idHook, $data['shop_association']);
return $linkBlockId;
}
/**
* @param int $linkBlockId
* @param array $data
*
* @throws DatabaseException
*/
public function update($linkBlockId, array $data)
{
$qb = $this->connection->createQueryBuilder();
$qb
->update($this->dbPrefix . 'link_block', 'lb')
->andWhere('lb.id_link_block = :linkBlockId')
->set('id_hook', ':idHook')
->set('content', ':content')
->setParameters([
'linkBlockId' => $linkBlockId,
'idHook' => $data['id_hook'],
'content' => json_encode([
'cms' => empty($data['cms']) ? [false] : $data['cms'],
'static' => empty($data['static']) ? [false] : $data['static'],
'product' => empty($data['product']) ? [false] : $data['product'],
'category' => empty($data['category']) ? [false] : $data['category'],
]),
])
;
$this->executeQueryBuilder($qb, 'Link block error');
$this->updateLanguages($linkBlockId, $data['block_name'], $data['custom_content']);
if ($this->isMultiStoreUsed) {
$this->objectModelHandler->handleMultiShopAssociation(
$linkBlockId,
$data['shop_association']
);
}
}
/**
* @param int $idLinkBlock
*
* @throws DatabaseException
*/
public function delete($idLinkBlock): void
{
if (count($this->multiStoreContext->getAllShopIds()) === count($this->multiStoreContext->getContextListShopID())) {
$tableNames = [
'link_block_lang',
'link_block',
'link_block_shop',
];
foreach ($tableNames as $tableName) {
$qb = $this->connection->createQueryBuilder();
$qb
->delete($this->dbPrefix . $tableName)
->andWhere('id_link_block = :idLinkBlock')
->setParameter('idLinkBlock', $idLinkBlock)
;
$this->executeQueryBuilder($qb, 'Delete error');
}
} else {
// Delete only from specific stores
if (!$this->multiStoreContext->isAllShopContext()) {
$qb = $this->connection->createQueryBuilder();
$qb
->delete($this->dbPrefix . 'link_block_shop')
->andWhere('id_link_block = :idLinkBlock')
->andWhere('id_shop IN (:shopIds)')
->setParameter('shopIds', $this->multiStoreContext->getContextListShopID(), Connection::PARAM_STR_ARRAY)
->setParameter('idLinkBlock', $idLinkBlock);
$this->executeQueryBuilder($qb, 'Delete from multi-store tables error');
}
}
}
/**
* @return array
*
* @throws \Doctrine\DBAL\DBALException
*/
public function createTables()
{
$errors = [];
$engine = _MYSQL_ENGINE_;
$this->dropTables();
$queries = [
"CREATE TABLE IF NOT EXISTS `{$this->dbPrefix}link_block`(
`id_link_block` int(10) unsigned NOT NULL auto_increment,
`id_hook` int(1) unsigned DEFAULT NULL,
`position` int(10) unsigned NOT NULL default '0',
`content` text default NULL,
PRIMARY KEY (`id_link_block`)
) ENGINE=$engine DEFAULT CHARSET=utf8",
"CREATE TABLE IF NOT EXISTS `{$this->dbPrefix}link_block_lang`(
`id_link_block` int(10) unsigned NOT NULL,
`id_lang` int(10) unsigned NOT NULL,
`name` varchar(40) NOT NULL default '',
`custom_content` text default NULL,
PRIMARY KEY (`id_link_block`, `id_lang`)
) ENGINE=$engine DEFAULT CHARSET=utf8",
"CREATE TABLE IF NOT EXISTS `{$this->dbPrefix}link_block_shop` (
`id_link_block` int(10) unsigned NOT NULL auto_increment,
`id_shop` int(10) unsigned NOT NULL,
`position` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`id_link_block`, `id_shop`)
) ENGINE=$engine DEFAULT CHARSET=utf8",
];
foreach ($queries as $query) {
$statement = $this->connection->executeQuery($query);
if ($statement instanceof Statement && 0 != (int) $statement->errorCode()) {
$errors[] = [
'key' => json_encode($statement->errorInfo()),
'parameters' => [],
'domain' => 'Admin.Modules.Notification',
];
}
}
return $errors;
}
/**
* @return array
*
* @throws \Doctrine\DBAL\DBALException
*/
public function installFixtures()
{
$errors = [];
$id_hook = (int) Hook::getIdByName('displayFooter');
$queries = [
'INSERT INTO `' . $this->dbPrefix . 'link_block` (`id_link_block`, `id_hook`, `position`, `content`) VALUES
(1, ' . $id_hook . ', 0, \'{"cms":[false],"product":["prices-drop","new-products","best-sales"],"static":[false],"category":[false]}\'),
(2, ' . $id_hook . ', 1, \'{"cms":["1","2","3","4","5"],"product":[false],"static":["contact","sitemap","stores"],"category":[false]}\');',
];
foreach ($this->languages as $lang) {
$queries[] = 'INSERT INTO `' . $this->dbPrefix . 'link_block_lang` (`id_link_block`, `id_lang`, `name`) VALUES
(1, ' . (int) $lang['id_lang'] . ', "' . pSQL($this->translator->trans('Products', [], 'Modules.Linklist.Shop', $lang['locale'])) . '"),
(2, ' . (int) $lang['id_lang'] . ', "' . pSQL($this->translator->trans('Our company', [], 'Modules.Linklist.Shop', $lang['locale'])) . '");'
;
}
foreach ($this->multiStoreContext->getShops(true, true) as $shopId) {
$queries[] = 'INSERT INTO `' . $this->dbPrefix . 'link_block_shop` (`id_link_block`, `id_shop`, `position`) VALUES
(1, ' . (int) $shopId . ', 0),
(2, ' . (int) $shopId . ', 1);'
;
}
foreach ($queries as $query) {
$statement = $this->connection->executeQuery($query);
if ($statement instanceof Statement && 0 != (int) $statement->errorCode()) {
$errors[] = [
'key' => json_encode($statement->errorInfo()),
'parameters' => [],
'domain' => 'Admin.Modules.Notification',
];
}
}
return $errors;
}
/**
* @return array
*
* @throws \Doctrine\DBAL\DBALException
*/
public function dropTables()
{
$errors = [];
$tableNames = [
'link_block_shop',
'link_block_lang',
'link_block',
];
foreach ($tableNames as $tableName) {
$sql = 'DROP TABLE IF EXISTS ' . $this->dbPrefix . $tableName;
$statement = $this->connection->executeQuery($sql);
if ($statement instanceof Statement && 0 != (int) $statement->errorCode()) {
$errors[] = [
'key' => json_encode($statement->errorInfo()),
'parameters' => [],
'domain' => 'Admin.Modules.Notification',
];
}
}
return $errors;
}
/**
* @param int $linkBlockId
* @param array $blockName
* @param array $custom
*
* @throws DatabaseException
*/
private function updateLanguages($linkBlockId, array $blockName, array $custom)
{
foreach ($this->languages as $language) {
$qb = $this->connection->createQueryBuilder();
$qb
->select('lbl.id_link_block')
->from($this->dbPrefix . 'link_block_lang', 'lbl')
->andWhere('lbl.id_link_block = :linkBlockId')
->andWhere('lbl.id_lang = :langId')
->setParameter('linkBlockId', $linkBlockId)
->setParameter('langId', $language['id_lang'])
;
$foundRows = $qb->execute()->rowCount();
$qb = $this->connection->createQueryBuilder();
if (!$foundRows) {
$qb
->insert($this->dbPrefix . 'link_block_lang')
->values([
'id_link_block' => ':linkBlockId',
'id_lang' => ':langId',
'name' => ':name',
'custom_content' => ':customContent',
])
;
} else {
$qb
->update($this->dbPrefix . 'link_block_lang', 'lbl')
->set('name', ':name')
->set('custom_content', ':customContent')
->andWhere('lbl.id_link_block = :linkBlockId')
->andWhere('lbl.id_lang = :langId')
;
}
$qb
->setParameters([
'linkBlockId' => $linkBlockId,
'langId' => $language['id_lang'],
'name' => $blockName[$language['id_lang']],
'customContent' => empty($custom) ? null : json_encode($custom[$language['id_lang']]),
]);
$this->executeQueryBuilder($qb, 'Link block language error');
}
}
/**
* @param QueryBuilder $qb
* @param string $errorPrefix
*
* @return Statement|int
*
* @throws DatabaseException
*/
private function executeQueryBuilder(QueryBuilder $qb, $errorPrefix = 'SQL error')
{
$statement = $qb->execute();
if ($statement instanceof Statement && !empty($statement->errorInfo())) {
throw new DatabaseException($errorPrefix . ': ' . var_export($statement->errorInfo(), true));
}
return $statement;
}
/**
* @param int $idHook
* @param int $idShop
*
* @return int
*/
private function getHookMaxPosition(int $idHook, int $idShop): int
{
$qb = $this->connection->createQueryBuilder();
$qb->select('MAX(lbs.position)')
->from($this->dbPrefix . 'link_block_shop', 'lbs')
->leftJoin('lbs', $this->dbPrefix . 'link_block', 'lb', 'lbs.id_link_block = lb.id_link_block')
->andWhere('lb.id_hook = :idHook')
->andWhere('lbs.id_shop = :idShop')
->setParameter('idHook', $idHook)
->setParameter('idShop', $idShop)
;
$maxPosition = $qb->execute()->fetchColumn(0);
return null !== $maxPosition ? $maxPosition + 1 : 0;
}
/**
* @param int $linkBlockId
* @param array $shopIds
*
* @throws DatabaseException
*/
private function updateMaxPosition(int $linkBlockId, ?int $hookId = null, array $shopIds): void
{
$qb = $this->connection->createQueryBuilder();
foreach ($shopIds as $shopId) {
$qb
->update($this->dbPrefix . 'link_block_shop lbs')
->set('position', ':position')
->andWhere('lbs.id_shop = :shopId')
->andWhere('lbs.id_link_block = :linkBlockId')
->setParameter('position', $this->getHookMaxPosition($hookId, $shopId))
->setParameter('shopId', $shopId)
->setParameter('linkBlockId', $linkBlockId);
$this->executeQueryBuilder($qb, 'Link block max position update error');
}
}
/**
* @param int $shopId
* @param array $positionsData
*
* @return void
*/
public function updatePositions(int $shopId, array $positionsData = []): void
{
try {
$this->connection->beginTransaction();
$i = 0;
foreach ($positionsData['positions'] as $position) {
$qb = $this->connection->createQueryBuilder();
$qb
->update($this->dbPrefix . 'link_block_shop')
->set('position', ':position')
->andWhere('id_link_block = :linkBlockId')
->andWhere('id_shop = :shopId')
->setParameter('shopId', $shopId)
->setParameter('linkBlockId', $position['rowId'])
->setParameter('position', $i);
++$i;
$statement = $qb->execute();
if ($statement instanceof Statement && $statement->errorCode()) {
throw new DatabaseException('Could not update #%i');
}
}
$this->connection->commit();
} catch (ConnectionException $e) {
$this->connection->rollBack();
throw new DatabaseException('Could not update positions.');
}
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;