<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Enterprise License (PEL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PEL
*/
namespace GlobalBundle\Twig\Extension;
use AppBundle\Model\Catalog\Catalog;
use AppBundle\Model\Product\Product;
use GlobalBundle\AppHelpers\GeneralHelper;
use GlobalBundle\Website\LinkGenerator\AbstractProductLinkGenerator;
use GlobalBundle\Website\LinkGenerator\CategoryLinkGenerator;
use GlobalBundle\Website\LinkGenerator\ProductLinkGenerator;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\SiteMenu;
use Pimcore\Model\Document;
use Pimcore\Navigation\Container;
use Pimcore\Navigation\Page\Document as NavDocument;
use Pimcore\Twig\Extension\Templating\Navigation;
use Pimcore\Twig\Extension\Templating\Placeholder;
use Pimcore\Translation\Translator;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use AppBundle\Website\Tool\Text;
use Pimcore\Cache;
use Pimcore\Db;
use Pimcore\Model\DataObject\Attributes;
use GlobalBundle\Services\CatalogServices;
use Pimcore\Model\DataObject\Customer;
use Pimcore\Model\DataObject\RequestAnItem;
use Pimcore\Model\DataObject\Status;
use Pimcore\Model\DataObject\WishListComments;
use Pimcore\Model\DataObject\LeadTime;
use Pimcore\Model\DataObject\ProformaInvoice;
class NavigationExtension extends AbstractExtension
{
private $piObjectIdsByRfq = [];
private $poObjectIdsByRfq = [];
const NAVIGATION_EXTENSION_POINT_PROPERTY = 'navigation_extension_point';
const CACHE_PRIORITY = 1000;
/**
* @var CategoryLinkGenerator
*/
protected $categoryLinkGenerator;
/**
* @var ProductLinkGenerator
*/
protected $productLinkGenerator;
/**
* @var Navigation
*/
protected $navigationHelper;
/**
* @var Placeholder
*/
protected $placeholderHelper;
/**
* @param Navigation $navigationHelper
*/
public function __construct(Navigation $navigationHelper, Placeholder $placeholderHelper, CategoryLinkGenerator $categoryLinkGenerator, ProductLinkGenerator $productLinkGenerator, Translator $translator)
{
$this->navigationHelper = $navigationHelper;
$this->categoryLinkGenerator = $categoryLinkGenerator;
$this->productLinkGenerator = $productLinkGenerator;
$this->placeholderHelper = $placeholderHelper;
$this->translator = $translator;
}
/**
* @return array|TwigFunction[]
*/
public function getFunctions()
{
return [
new TwigFunction('app_navigation_data_links', [$this, 'getDataLinks']),
new TwigFunction('app_navigation_enrich_breadcrumbs', [$this, 'enrichBreadcrumbs']),
new TwigFunction('app_navigation_menubar', [$this, 'getMenuBar']),
new TwigFunction('app_navigation_megamenu_url', [$this, 'getMegaMenuLinks']),
new TwigFunction('app_navigation_product_details', [$this, 'getProductLinks']),
new TwigFunction('app_general_filter_translate', [$this, 'translateValues']),
new TwigFunction('app_general_filter_sort', [$this, 'sort']),
new TwigFunction('app_general_filter_sort_objects', [$this, 'sortObjects']),
new TwigFunction('app_general_filter_value_string', [$this, 'fromIdToValueStr']),
new TwigFunction('pimcore_pagination_url', [$this, 'pimcorePaginationUrl']),
new TwigFunction('app_navigation_category_url', [$this, 'getCategoryUrl']),
new TwigFunction('app_navigation_sitemap_id', [$this, 'getSitemapId']),
new TwigFunction('app_navigation_product_in_wishlist', [$this, 'getProductWishlistStatus']),
new TwigFunction('app_navigation_check_user_subscription_type', [$this, 'checkUserSubscriptionType']),
new TwigFunction('app_navigation_product_attribute_name', [$this, 'getProductAttributeName']),
new TwigFunction('app_navigation_menu_status', [$this, 'checkMenuStatus']),
new TwigFunction('app_navigation_mega_menu_status', [$this, 'checkMegaMenuStatus']),
new TwigFunction('app_navigation_rfq_status', [$this, 'rfqStatus']),
new TwigFunction('app_navigation_selected_wishlist', [$this, 'getSelectedWhislistByProduct']),
new TwigFunction('app_navigation_latest_highlight_menu', [$this, 'getLatestHighlightCatalogForMenu']),
new TwigFunction('app_product_comment', [$this, 'getProductComment']),
new TwigFunction('app_wishlist_product_comment', [$this, 'getWishlistProductComment']),
new TwigFunction('app_navigation_analytics_access', [$this, 'getAnalyticsAccess']),
new TwigFunction('app_navigation_curated_fpg_menubar', [$this, 'getCuratedFPGMenuBar']),
new TwigFunction('app_navigation_exclusive_fpg_menubar', [$this, 'getExclusiveFPGMenuBar']),
new TwigFunction('app_navigation_exclusive_random_products', [$this, 'getExclusiveRandomProducts']),
new TwigFunction('app_navigation_catalogtype', [$this, 'getCatalogTypeInMenu']),
new TwigFunction('app_navigation_unit_details', [$this, 'getQuantityUnit']),
new TwigFunction('app_CDN_url', [$this, 'getCDNurl']),
new TwigFunction('app_navigation_lead_time', [$this, 'getLeadTimeData']),
new TwigFunction('app_navigation_color', [$this, 'getColorData']),
new TwigFunction('app_navigation_field_collection', [$this, 'getRFQData']),
new TwigFunction('app_current_site', [$this, 'getCurrentSite']),
new TwigFunction('app_sub_document_category', [$this, 'getSubDocumentCategory']),
new TwigFunction('app_category_top_parent', [$this, 'getCategoryTopParent']),
new TwigFunction('app_product_id', [$this, 'getOnlyProductId']),
new TwigFunction('app_array_object_id', [$this, 'getArrayObjectsToIds']),
new TwigFunction('pimcore_complex_url', [$this, 'pimcoreComplexUrl']),
new TwigFunction('get_product_by_id', [$this, 'getSingleProductById']),
new TwigFunction('get_cmf_array', [$this, 'getCMFArray']),
new TwigFunction('get_exclusive_to_these_customers_array', [$this, 'getExclusiveCustomersArray']),
new TwigFunction('get_selected_internal_customer_ids', [$this, 'getInternalCustomersArray']),
new TwigFunction('get_selected_supplier_customer_id', [$this, 'getSupplierCustomersArray']),
new TwigFunction('get_boardcart_status', [$this, 'getBoardProductCartStatus']),
new TwigFunction('get_product_status', [$this, 'getProductStatus']),
new TwigFunction('get_status_in_field_collection', [$this, 'getCartStatusInFieldCollection']),
new TwigFunction('has_brief_response_comments', [$this, 'hasBriefResponseComments']),
new TwigFunction('has_brief_uploads_comments', [$this, 'hasBriefUploadsComments']),
new TwigFunction('get_selected_buyer_customer_id', [$this, 'getBuyerCustomersArray']),
new TwigFunction('get_selected_supplier_kam_id', [$this, 'getSupplierKAMCustomersArray']),
new TwigFunction('get_selected_supplier_internal_users_id', [$this, 'getSupplierInternalCustomersArray']),
new TwigFunction('get_selected_buyer_kam_id', [$this, 'getBuyerKAMCustomersArray']),
new TwigFunction('get_selected_buyer_internal_users_id', [$this, 'getBuyerInternalCustomersArray']),
new TwigFunction('get_rfq_generated_pi_status', [$this, 'getRFQGeneratedPIStatus']),
new TwigFunction('get_pi_obj_id', [$this, 'getPIObjId']),
new TwigFunction('get_rfq_generated_po_status', [$this, 'getRFQGeneratedPOStatus']),
new TwigFunction('get_po_obj_id', [$this, 'getPOObjId']),
];
}
/**
* @param Document $document
* @param Document $startNode
*
* @return \Pimcore\Navigation\Container
*/
public function getDataLinks(Document $document, Document $startNode)
{
$navigation = $this->navigationHelper->build([
'active' => $document,
'root' => $startNode,
'pageCallback' => function ($page, $document) {
$rootCategory = $document->getProperty(AbstractProductLinkGenerator::ROOT_CATEGORY_PROPERTY_NAME);
foreach ($rootCategory->getChildren() as $category) {
$categoryPage = new NavDocument([
'label' => $category->getLabel(),
'id' => 'category-' . $category->getId(),
'uri' => $category->getLabel()
]);
$page->addPage($categoryPage);
}
}
]);
return $navigation;
}
public function getCMFArray($productId){
$productObj = Product::getById($productId, ["force" => true]);
return $productObj;
}
public function getExclusiveCustomersArray($productId){
$productObj = Product::getById($productId, ["force" => true]);
foreach ($productObj->getExclusiveToTheseCustomersOnly() as $key => $value) {
$customerIdsArray[] = $value->getId();
}
return $customerIdsArray;
}
public function getInternalCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$sharedWithInternal = $rfqObj->getSharedWithInternal();
$customerIdsArray = [];
if (!empty($sharedWithInternal)) {
foreach ($sharedWithInternal as $key => $value) {
$customerIdsArray[] = $value->getId();
}
}
return $customerIdsArray;
}
public function getSupplierCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$supplierCustomer = $rfqObj->getSharedWithSupplier();
if ($supplierCustomer !== null) {
$supplierCustomerId = $supplierCustomer->getId();
} else {
$supplierCustomerId = null;
}
return $supplierCustomerId;
}
public function getBuyerCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$buyerCustomer = $rfqObj->getBuyer();
/*
if ($buyerCustomer !== null) {
$buyerCustomerId = $buyerCustomer->getId();
} else {
$buyerCustomerId = null;
}
return $buyerCustomerId; \
*/
$buyerCustomerIds = [];
$buyerCustomers = $rfqObj->getBuyer();
if (!empty($buyerCustomers)) {
foreach ($buyerCustomers as $buyerCustomer) {
if ($buyerCustomer !== null) {
$buyerCustomerIds[] = $buyerCustomer->getId();
}
}
}
return $buyerCustomerIds;
}
public function getSupplierKAMCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$supplierKAMCustomer = $rfqObj->getSharedWithSupplierKAM();
$supplierKAMCustomerIds = [];
if (!empty($supplierKAMCustomer)) {
foreach ($supplierKAMCustomer as $supplierKAM) {
if ($supplierKAM !== null) {
$supplierKAMCustomerIds[] = $supplierKAM->getId();
}
}
}
return $supplierKAMCustomerIds;
}
public function getSupplierInternalCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$supplierInternalCustomers = $rfqObj->getSharedWithInternalSupplier();
$supplierInternalCustomerIds = [];
if (!empty($supplierInternalCustomers)) {
foreach ($supplierInternalCustomers as $supplierInternal) {
if ($supplierInternal !== null) {
$supplierInternalCustomerIds[] = $supplierInternal->getId();
}
}
}
return $supplierInternalCustomerIds;
}
public function getBuyerKAMCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$buyerKAMCustomers = $rfqObj->getSharedWithBuyerKAM();
$buyerKAMCustomerIds = [];
if (!empty($buyerKAMCustomers)) {
foreach ($buyerKAMCustomers as $buyerKAM) {
if ($buyerKAM !== null) {
$buyerKAMCustomerIds[] = $buyerKAM->getId();
}
}
}
return $buyerKAMCustomerIds;
}
public function getBuyerInternalCustomersArray($rfqId){
$rfqObj = RequestAnItem::getById($rfqId, ["force" => true]);
$buyerInternalUsers = $rfqObj->getSharedWithInternalBuyer();
$buyerInternalUserIds = [];
if (!empty($buyerInternalUsers)) {
foreach ($buyerInternalUsers as $buyerInternalUser) {
if ($buyerInternalUser !== null) {
$buyerInternalUserIds[] = $buyerInternalUser->getId();
}
}
}
return $buyerInternalUserIds;
}
public function getProductStatus($statusId){
$productStatus = '';
if ($statusId !== null && $statusId !== '') {
try {
$statusObj = Status::getById($statusId, ["force" => true]);
if ($statusObj) {
$statusName = $statusObj->getName();
if ($statusName !== null) {
$productStatus = $statusName;
}
}
} catch (\Exception $e) {
// Log the exception or handle it as needed
error_log('Error fetching product status: ' . $e->getMessage());
}
}
return $productStatus;
}
public function hasBriefResponseComments($id)
{
$briefResponseObj = \Pimcore\Model\DataObject\RFNResponses::getById($id);
if (!$briefResponseObj) {
return false;
}
$commentDetailsCollection = [];
$commentDetails = $briefResponseObj->getBriefResponseLevelCommentDetails();
if ($commentDetails) {
foreach ($commentDetails as $commentItem) {
$commentData = [
'comment' => $commentItem->getComment(),
];
$attachments = $commentItem->getAttachments();
if ($attachments) {
$commentData['attachments'] = array_map(function ($attachment) {
return [
'fileName' => $attachment->getFilename(),
'fullPath' => $attachment->getFullPath(),
];
}, $attachments);
}
$commentDetailsCollection[] = $commentData;
}
}
return count($commentDetailsCollection) > 0 ? true : false;
}
public function hasBriefUploadsComments($id)
{
$briefUploadsObj = \Pimcore\Model\DataObject\RFNUploads::getById($id);
if (!$briefUploadsObj) {
return false;
}
$commentDetailsCollection = [];
$commentDetails = $briefUploadsObj->getBriefUploadsLevelCommentDetails();
if ($commentDetails) {
foreach ($commentDetails as $commentItem) {
$commentData = [
'comment' => $commentItem->getComment(),
];
$attachments = $commentItem->getAttachments();
if ($attachments) {
$commentData['attachments'] = array_map(function ($attachment) {
return [
'fileName' => $attachment->getFilename(),
'fullPath' => $attachment->getFullPath(),
];
}, $attachments);
}
$commentDetailsCollection[] = $commentData;
}
}
return count($commentDetailsCollection) > 0 ? true : false;
}
public function getBoardProductCartStatus($productId,$customer){
$prodIds = [];
if($customer){
$rfqDataList = new DataObject\RequestForQuote\Listing();
$rfqDataList->addConditionParam("customer__id = ?", $customer->getId(), "AND");
$rfqDataList->addConditionParam("status = ?", "Validation", "AND");
$rfqDataList->addConditionParam("customerStatus NOT IN (?, ?, ?)", ["Cancelled", "Accepted", "PO received"], "AND");
$RFQData = $rfqDataList->load();
if($RFQData){
foreach ($RFQData as $key => $value) {
$collectionCart = $value->getRFQCollections();
if($collectionCart) {
foreach ($collectionCart as $key => $valueCC) {
$product = $valueCC->getProducts();
if ($product) {
$prodIds[] = $product->getId();
}
}
}
}
}
}
if(in_array($productId,$prodIds)){
return false;
}else{
return true;
}
}
public function getCategoryUrl($sitemenu)
{
$menu['label'] = $sitemenu->getLabel();
$menu['id'] = $sitemenu->getId();
$menu['url'] = "/shop/" . Text::toUrl($sitemenu->getLabel() ?? 'elements') . "~c" . $sitemenu->getId();
return $menu;
}
public function getMegaMenuLinks($megaMenuKey, $megaMenuValue, $mainURL)
{
$url = "";
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
if (!empty($customer)) {
$subscriptionType = $customer->getCompany()->getSubscription();
$curateFilter = explode(',', GeneralHelper::getWebsiteSetting('CurateFilter'));
$signatureFilter = explode(',', GeneralHelper::getWebsiteSetting('SignatureFilter'));
$essencialRemoveFilter = array_merge($curateFilter, $signatureFilter);
$filterArray = false;
if ($subscriptionType == "Essential") {
if (!in_array($megaMenuKey, $essencialRemoveFilter)) {
$filterArray = true;
}
} elseif ($subscriptionType == "Curate") {
if (!in_array($megaMenuKey, $signatureFilter)) {
$filterArray = true;
}
} else {
$filterArray = true;
}
if (!empty($mainURL) && $filterArray == true) {
if (false !== strpos($mainURL, '?')) {
$params = '&' . MEGA_MENU[$megaMenuKey] . '[]=';
} else {
$params = '?' . MEGA_MENU[$megaMenuKey] . '[]=';
}
$url = $mainURL . $params . $megaMenuValue;
$filterArray = false;
}
}
return $url;
}
public function getSitemapId($siteMenuId, $category)
{
if ($siteMenuId) {
return $siteMenuId;
} else {
$siteMenuList = new \Pimcore\Model\DataObject\SiteMenu\Listing();
$siteMenuList->setCondition("categories like '%," . $category . ",%'");
$siteMenuObject = $siteMenuList->load();
if (!empty($siteMenuObject)) {
$customerSiteMenuData = $this->getAllSiteMenu();
if (!empty($customerSiteMenuData)) {
foreach ($siteMenuObject as $key => $value) {
if (in_array($value->getId(), $customerSiteMenuData)) {
return $value->getId();
}
}
return $siteMenuObject[0]->getId();
} else {
return $siteMenuObject[0]->getId();
}
}
}
}
public function getMenuBar()
{
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$menu = [];
if (!empty($customer) && !empty($customer->getCompany())) {
$cacheKey = 'frontend_product_group_' . $customer->getCompany()->getId();
if (!$menu = Cache::load($cacheKey)) {
$menu = [];
$customerSiteMenuData = $this->getAllSiteMenu();
$entries = new DataObject\SiteMenu\Listing();
$entries->setCondition("level = ?", [1]);
$entries->setOrderKey("order");
$entries->setOrder("asc");
$level1Data = $entries->load();
foreach ($level1Data as $key => $value) {
//if($value->getLevel() == 1 || $value->getLevel() == 2){
$menu[$key]['label'] = $value->getLabel();
$menu[$key]['id'] = $value->getId();
$menu[$key]['order'] = $value->getOrder();
$mainURL = $this->genrateMainURL($value, $customerSiteMenuData);
$menu[$key]['url'] = $mainURL;
$megeMenuArray = $this->megaMenu($value, $mainURL);
$menu[$key]['megaMenu'] = $megeMenuArray;
$menu[$key]['children'] = [];
$entries = new DataObject\SiteMenu\Listing();
$entries->setCondition("parenLevel__id = ? AND level = ?", [$value->getId(), $value->getLevel() + 1]);
$entries->setOrderKey("order");
$entries->setOrder("asc");
$level2Data = $entries->load();
if (!empty($level2Data)) {
$menu[$key]['children'] = $this->getRecurciveCategory($level2Data, $customerSiteMenuData);
}
//}
}
Cache::save($menu, $cacheKey, [$cacheKey], null, self::CACHE_PRIORITY, true);
}
}
return $menu;
}
public function getAllSiteMenu()
{
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$siteMenuDataArray = [];
if ($customer) {
$sitemenuData = $customer->getCompany()->getSiteMenuCategory();
foreach ($sitemenuData as $siteKey => $siteValue) {
$siteMenuDataArray[] = $siteValue->getId();
if($siteValue->getLevel() == 3){
$siteMenuDataArray[] = $siteValue->getParenLevel()->getId();
$siteMenuDataArray[] = $siteValue->getParenLevel()->getParent()->getId();
}elseif ($siteValue->getLevel() == 2) {
$siteMenuDataArray[] = $siteValue->getParenLevel()->getId();
$entries = new DataObject\SiteMenu\Listing();
$entries->setCondition("parenLevel__id = ? AND level = ?", [$siteValue->getId(), 3]);
$entries->setOrderKey("order");
$entries->setOrder("asc");
$level3Data = $entries->load();
foreach ($level3Data as $key => $value) {
$siteMenuDataArray[] = $value->getId();
}
} elseif ($siteValue->getLevel() == 1) {
$entries = new DataObject\SiteMenu\Listing();
$entries->setCondition("parenLevel__id = ? AND level = ?", [$siteValue->getId(), 2]);
$entries->setOrderKey("order");
$entries->setOrder("asc");
$level2Data = $entries->load();
foreach ($level2Data as $value) {
$siteMenuDataArray[] = $value->getId();
$entries = new DataObject\SiteMenu\Listing();
$entries->setCondition("parenLevel__id = ? AND level = ?", [$value->getId(), 3]);
$entries->setOrderKey("order");
$entries->setOrder("asc");
$level3Data = $entries->load();
foreach ($level3Data as $k => $v) {
$siteMenuDataArray[] = $v->getId();
}
}
}
}
}
return array_unique($siteMenuDataArray);
}
public function genrateMainURL($value, $customerSiteMenuData)
{
$mainURL = "";
$object = new Product();
$db = Db::get();
if (!empty($value->getFrontendFilter()->getItems())) {
$frontendFilterArray = [];
$whereUrl = "";
foreach ($value->getFrontendFilter()->getItems() as $frontendFilterKey => $frontendFilterValue) {
$frontendFilterQuery = "SELECT name FROM classificationstore_keys WHERE id IN (" . $frontendFilterKey . ")";
$frontendGroupName = $db->fetchColumn($frontendFilterQuery);
$fieldOptionsPro = $object->getClass()->getFieldDefinition(MEGA_MENU[$frontendGroupName]);
foreach ($fieldOptionsPro->getOptions() ?: [] as $frontendOptionKey => $frontendOptionValue) {
if (in_array($frontendOptionValue['value'], $frontendFilterValue[$frontendFilterKey]['default'])) {
//$frontendFilterArray[$frontendGroupName][$frontendOptionValue['value']] = $frontendOptionValue['key'];
$whereUrl .= '&' . MEGA_MENU[$frontendGroupName] . '[]=' . $frontendOptionValue['value'];
}
}
}
if (in_array($value->getId(), $customerSiteMenuData)) {
$mainURL = "/shop/" . Text::toUrl($value->getLabel() ?? 'elements') . "~c" . $value->getId() . '?' . substr($whereUrl, 1);
}
} else {
if (in_array($value->getId(), $customerSiteMenuData)) {
$mainURL = "/shop/" . Text::toUrl($value->getLabel() ?? 'elements') . "~c" . $value->getId();
}
}
return $mainURL;
}
public function megaMenu($value, $mainURL)
{
$object = new Product();
$db = Db::get();
$megeMenuArray = [];
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
if (!empty($value->getCurateFilter()->getItems())) {
foreach ($value->getCurateFilter()->getItems() as $megaMenuKey => $megaMenuValue) {
$keySqlQuery = "SELECT name FROM classificationstore_keys WHERE id IN (" . $megaMenuKey . ")";
$groupName = $db->fetchColumn($keySqlQuery);
$fieldOptions = $object->getClass()->getFieldDefinition(MEGA_MENU[$groupName]);
foreach ($fieldOptions->getOptions() ?: [] as $optionKey => $optionValue) {
if (in_array($optionValue['value'], $megaMenuValue[$megaMenuKey]['default'])) {
$subscriptionType = $customer->getCompany()->getSubscription();
$curateFilter = explode(',', GeneralHelper::getWebsiteSetting('CurateFilter'));
$signatureFilter = explode(',', GeneralHelper::getWebsiteSetting('SignatureFilter'));
$essencialRemoveFilter = array_merge($curateFilter, $signatureFilter);
$filterArray = false;
if ($subscriptionType == "Essential") {
if (!in_array(MEGA_MENU[$groupName], $essencialRemoveFilter)) {
$filterArray = true;
}
} elseif ($subscriptionType == "Curate") {
if (!in_array(MEGA_MENU[$groupName], $signatureFilter)) {
$filterArray = true;
}
} else {
$filterArray = true;
}
$megaMenuURL = "";
if (!empty($mainURL) && $filterArray == true) {
if (false !== strpos($mainURL, '?')) {
$params = '&' . MEGA_MENU[$groupName] . '[]=';
} else {
$params = '?' . MEGA_MENU[$groupName] . '[]=';
}
$megaMenuURL = $mainURL . $params . $optionValue['value'];
$filterArray = false;
}
$megeMenuArray[$groupName][$optionValue['key']] = $megaMenuURL;
}
}
}
}
return $megeMenuArray;
}
public function getRecurciveCategory($sitemenu, $customerSiteMenuData)
{
$menu = [];
foreach ($sitemenu as $key => $value) {
$label = $value->getLocalizedfields()->getLocalizedValue("label", "en");
$menu[$key]['label'] = $label;
$menu[$key]['id'] = $value->getId();
$menu[$key]['order'] = $value->getOrder();
if (in_array($value->getId(), $customerSiteMenuData)) {
$mainURL = $this->genrateMainURL($value, $customerSiteMenuData);
//$menu[$key]['url'] = "/shop/".Text::toUrl($value->getLabel() ?? 'elements')."~c".$value->getId();
$menu[$key]['url'] = $mainURL;
}
if ($value->getLevel() == 2) {
$menu[$key]['image'] = !empty($value->getImage()) ? $value->getImage() : '';
}
$entries = new DataObject\SiteMenu\Listing();
$entries->setCondition("parenLevel__id = ? AND level = ?", [$value->getId(), 3]);
$entries->setOrderKey("order");
$entries->setOrder("asc");
$level3Data = $entries->load();
if (!empty($level3Data)) {
$menu[$key]['children'] = $this->getRecurciveCategory($level3Data, $customerSiteMenuData);
}
}
return $menu;
}
public function getProductLinks($product)
{
$url = "";
if (!empty($product)) {
$url = $this->productLinkGenerator->generateWithMockup($product, []);
}
return $url;
}
/**
* @param Container $navigation
*
* @return Container
*
* @throws \Exception
*/
public function enrichBreadcrumbs()
{
$breadctumbsArray = [];
$findArr = array($_SERVER['HTTP_HOST'].'/', 'http://', 'https://');
$replaceArr = array('','','');
$prev_url = str_replace($findArr,$replaceArr,$_SERVER['HTTP_REFERER'] ?? '');
$SCList = new DataObject\SalesCampaign\Listing();
$SCList->setCondition("shareableLink = '" . $prev_url."'");
$SCData = $SCList->load();
$currentUrl = $_SERVER['REQUEST_URI'];
$url_data = array_values(array_filter(explode('/',$currentUrl)));
$path = array_values(array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))));
$params = $url_data[1] ?? '';
$last_url = $_SERVER['HTTP_REFERER'] ?? '';
if(($url_data[0] ?? null)=='catalog-product-listing'){
$catalogId = $path[1];
$type_data = explode('=',$params);
$type = $type_data[1];
$myObject = DataObject\Catalog::getById($catalogId);
$name = $myObject->getName();
$prevUrlData= array_values(array_filter(explode('=',$last_url)));
$lastUrlData= end($prevUrlData);
if($type=='curate'){
if($lastUrlData=='allcurater'){
$showLabel = 'All Curate';
}else if($lastUrlData=='alldesigner'){
$showLabel = 'All Designer';
}else{
$showLabel = 'All Curate';
}
$breadctumbsArray = array(
"level1" => array("id" => 0, "name" => $showLabel,"url"=>$last_url),
"level2" => array("id" =>$catalogId, "name" => $name, "url" =>$currentUrl),
);
}elseif($type == 'signature'){
if($lastUrlData=='alllicences'){
$showLabel = 'All Licences';
}else if($lastUrlData=='alldesigner'){
$showLabel = 'All Designer';
}else if($lastUrlData=='allsignature'){
$showLabel = 'All Exclusive';
}
$breadctumbsArray = array(
"level1" => array("id" => 0, "name" => $showLabel,"url"=>$last_url),
"level2" => array("id" =>$catalogId, "name" => $name, "url" =>$currentUrl),
);
}
}else{
$urlEnd = explode("~c",(string)(end($path) ?: ''));
$siteId = $urlEnd[1] ?? null;
if (!empty($SCData)) {
$sc_id = $SCData[0]->getId();
$breadctumbsArray = array(
"level1" => array("id" => 0, "name" => 'SalesCampaign'),
"level2" => array("id" => $sc_id, "name" => $SCData[0]->getTitle(), "url" => '/'.$SCData[0]->getshareableLink()),
);
} else if (!empty($siteId) && isset($siteId)) {
$data = SiteMenu::getById($siteId);
if (!empty($data) && $data->getLevel() == 3) {
$urlLevel1 = "/shop/" . Text::toUrl($data->getParent()->getParent()->getLabel() ?? 'elements') . "~c" . $data->getParent()->getParent()->getId();
$urlLevel2 = "/shop/" . Text::toUrl($data->getParent()->getLabel() ?? 'elements') . "~c" . $data->getParent()->getId();
$urlLevel3 = "/shop/" . Text::toUrl($data->getLabel() ?? 'elements') . "~c" . $data->getId();
$breadctumbsArray = array(
"level1" => array("id" => $data->getParent()->getParent()->getId(), "name" => $data->getParent()->getParent()->getLabel(), "url" => $urlLevel1),
"level2" => array("id" => $data->getParent()->getId(), "name" => $data->getParent()->getLabel(), "url" => $urlLevel2),
"level3" => array("id" => $data->getId(), "name" => $data->getLabel(), "url" => $urlLevel3)
);
} elseif (!empty($data) && $data->getLevel() == 2) {
$urlLevel1 = "/shop/" . Text::toUrl($data->getParent()->getLabel() ?? 'elements') . "~c" . $data->getParent()->getId();
$urlLevel2 = "/shop/" . Text::toUrl($data->getLabel() ?? 'elements') . "~c" . $data->getId();
$breadctumbsArray = array(
"level1" => array("id" => $data->getParent()->getId(), "name" => $data->getParent()->getLabel(), "url" => $urlLevel1),
"level2" => array("id" => $data->getId(), "name" => $data->getLabel(), "url" => $urlLevel2),
);
} else {
$urlLevel1 = "/shop/" . Text::toUrl($data->getLabel() ?? 'elements') . "~c" . $data->getId();
$breadctumbsArray = array(
"level1" => array("id" => $data->getId(), "name" => $data->getLabel(), "url" => $urlLevel1),
);
}
}
}
// p_r($breadctumbsArray);die;
return $breadctumbsArray;
}
public function translateValues($values)
{
foreach ($values as &$modifyingValue) {
$modifyingValue['translated'] = $this->translator->trans(mb_strtolower('attribute.' . $modifyingValue['value']));
}
return $values;
}
/**
* @param array $values
* @param string|null $fieldname
*
* @return array
*/
public function sort(array $values, string $fieldname = null): array
{
@usort($values, function ($left, $right) use ($fieldname) {
$leftString = $left;
$rightString = $right;
if ($fieldname) {
$methodName = 'get' . ucfirst($fieldname);
if (is_array($leftString)) {
$leftString = $leftString[$fieldname];
} elseif (method_exists($leftString, $methodName)) {
$leftString = $leftString->$methodName();
}
if (is_array($rightString)) {
$rightString = $rightString[$fieldname];
} elseif (method_exists($rightString, $methodName)) {
$rightString = $rightString->$methodName();
}
}
return strcmp($leftString, $rightString);
});
return $values;
}
/**
* @param array $values
* @param string $fieldname
* @param array $objects
*
* @return array
*/
public function sortObjects(array $values, string $fieldname, array $objects): array
{
@usort($values, function ($left, $right) use ($fieldname, $objects) {
$leftString = '';
$rightString = '';
$methodName = 'get' . ucfirst($fieldname);
$object = $objects[$left['value']];
if ($object && method_exists($object, $methodName)) {
$leftString = $object->$methodName();
}
$object = $objects[$right['value']];
if ($object && method_exists($object, $methodName)) {
$rightString = $object->$methodName();
}
return strcmp($leftString, $rightString);
});
return $values;
}
/**
* @param string $className
* @param number $value
* @return string $value
*/
public function fromIdToValueStr($className, $value)
{
if (!empty($className) && !in_array($className, STATIC_FILTER)) {
if ($className == 'country') {
$countryData = GeneralHelper::searchCountry($value);
return $countryData['name'];
}
if($className == 'countryFilter'){
$className = 'country';
}
if ($className == 'lifeStyleTheme') {
$className = 'LifeStyleCollection';
}
if ($className == 'productionLeadTime') {
$className = 'LeadTime';
}
if ($className == 'crossCategory') {
$className = 'CrossGroup';
}
if ($className == 'tradeFair') {
$className = 'TradeFair';
}
if ($className == 'productStatus') {
$className = 'Status';
}
if ($className =='exclusiveToInternalCompany') {
$className = 'SupplierCompany';
}
if ($className =='productCategory') {
$className = 'Category';
}
$objectStr = 'Pimcore\\Model\\DataObject\\' . ucfirst($className) . '\\Listing';
$object = new $objectStr();
$object->setCondition(' o_id = ? ', [$value]);
$object->setLimit(1);
$loadObjectData = $object->load();
if (!empty($loadObjectData)) {
if($className == 'country'){
return $loadObjectData[0]->getO_key();
}else{
return $loadObjectData[0]->getName();
}
} else {
return;
}
} else {
return $value;
}
return $value;
}
/**
* @param Request Parameter $requestVariables
* @param string $currentUrl
* @return modifiedweburl $x
*/
public function pimcorePaginationUrl($requestVariables, $currentUrl = '')
{
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (in_array('sort', $_REQUEST)) {
$actual_linkX = $actual_link;
$actual_linkY = $actual_link;
} else {
$actual_linkX = substr($actual_link, 0, strpos($actual_link, "&" . $requestVariables . "="));
$actual_linkY = substr($actual_link, 0, strpos($actual_link, "?" . $requestVariables . "="));
}
if ($actual_linkX) {
$actual_link = $actual_linkX;
}
if ($actual_linkY) {
$actual_link = $actual_linkY;
}
$urlData = explode('?', $actual_link);
if (count($urlData) >= 2) {
$lchar = substr($actual_link, -1);
if ($lchar == '?') {
$x = $actual_link . $requestVariables . '=';
} else {
$x = $actual_link . '&' . $requestVariables . '=';
}
} else {
$lchar = substr($actual_link, -1);
if ($lchar == '?') {
$x = $actual_link . $requestVariables . '=';
} else {
$x = $actual_link . '?' . $requestVariables . '=';
}
}
return $x;
}
public function getProductWishlistStatus($product)
{
if (isset($_SESSION['_pimcore_admin']['customer']) && !empty($_SESSION['_pimcore_admin']['customer'])) {
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$wishlistListing = new DataObject\Wishlist\Listing();
$wishlistListing->setCondition("customer__id = " . $customer->getId());
// $wishlistListing->setCondition("products like '%,products|".$product->getId().",%'");
$wishlistData = $wishlistListing->load();
// p_r($wishlistListing);die;
if (count($wishlistData) != 0) {
return $wishlistData[0]->getLable();
}
}
return false;
}
public function checkUserSubscriptionType()
{
if (isset($_SESSION['_pimcore_admin']['customer']) && !empty($_SESSION['_pimcore_admin']['customer'])) {
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
return $customer->getCompany()->getSubscription();
}
}
public function getProductAttributeName($attributes)
{
$name = [];
if (!empty($attributes)) {
foreach ($attributes as $key => $value) {
$attributesData = Attributes::getById($value);
if (!empty($attributesData)) {
$name[] = $attributesData->getLocalizedfields()->getLocalizedValue("name", "en");
}
}
}
return $name;
}
public function checkMenuStatus($menu)
{
$status = true;
if (!empty($menu)) {
foreach ($menu as $k => $v) {
if (empty($v)) {
$status = false;
break;
}
}
}
return $status;
}
public function checkMegaMenuStatus($megaMenu)
{
$status = true;
foreach ($megaMenu as $value) {
foreach ($value as $v) {
if (empty($v)) {
$status = false;
break;
}
}
}
return $status;
}
public function rfqStatus($status)
{
return RFQ_STATUS[$status];
}
public function getSelectedWhislistByProduct($productId)
{
if(strpos($productId, "?") !== false){
$productId = strtok($productId, '?');
}
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
if (!empty($customer)) {
$wishlistListing = new DataObject\Wishlist\Listing();
$condition = "(customer__id = ? AND products LIKE ?) OR (products LIKE ? AND sharedWith LIKE ?)";
$wishlistListing->setCondition($condition, [$customer->getId(), '%,' . $productId . ',%', '%,' . $productId . ',%', '%,' . $customer->getId() . ',%']);
$wishlistData = $wishlistListing->load();
$arr = [];
if (!empty($wishlistData)) {
foreach ($wishlistData as $value) {
$arr[] = $value->getO_Id();
}
// PHP 8: templates print this value raw inside onclick attributes -
// return the id list as string (PHP 7.4 silently printed "Array" here)
return implode(',', $arr);
}
}
return false;
}
public function getLatestHighlightCatalogForMenu($type)
{
$catalogServices = new CatalogServices();
return $catalogServices->getLatestHighlightCatalog($type);
}
public function getProductComment($commentProductId){
if(strpos($commentProductId, "?") !== false){
$commentProductId = strtok($commentProductId, '?');
}
$commentProductObj = Product::getById($commentProductId, ["force" => true]);
$isCommentExists = false;
if ($commentProductObj) {
try{
$isCommentExists = ($commentProductObj->getProductComment()) ? true : false;
}
catch(\Exception $e){
$isCommentExists = false;
}
}
return $isCommentExists;
}
public function getAnalyticsAccess(){
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$isAbleToViewAnalytics = false;
if (!empty($customer)) {
$customerId = $customer->getId();
$customerObj = Customer::getById($customerId);
$isAbleToViewAnalytics = ($customerObj->getIsAbleToViewAnalytics()) ? true : false;
}
return $isAbleToViewAnalytics;
}
public function getCuratedFPGMenuBar()
{
$allCuratedFPGMenuData = [];
$curatedFPGMenu = new DataObject\CuratedFPG\Listing();
$allCuratedFPGMenuArray = $curatedFPGMenu->load();
$level1Array = [];
$level2Array = [];
$level3Array = [];
foreach ($allCuratedFPGMenuArray as $key => $value) {
if($value->getLevel() == 1){
$level1Array[$value->getId()] = $value;
}
elseif($value->getLevel() == 2){
$level2Array[$value->getId()] = $value;
}
elseif($value->getLevel() == 3){
$level3Array[$value->getParent()->getParent()->getId()][$value->getParent()->getId()][] = $value;
}
}
return ["level1"=>$level1Array, "level2"=>$level2Array, "level3"=>$level3Array];
}
public function getExclusiveFPGMenuBar()
{
$allExclusiveFPGMenuData = [];
$exclusiveFPGMenu = new DataObject\ExclusiveFPG\Listing();
$allExclusiveFPGMenuArray = $exclusiveFPGMenu->load();
$level1Array = [];
$level2Array = [];
$level3Array = [];
foreach ($allExclusiveFPGMenuArray as $key => $value) {
if($value->getLevel() == 1){
$level1Array[$value->getId()] = $value;
}
elseif($value->getLevel() == 2){
$level2Array[$value->getId()] = $value;
}
elseif($value->getLevel() == 3){
$level3Array[$value->getParent()->getParent()->getId()][$value->getParent()->getId()][] = $value;
}
}
return ["level1"=>$level1Array, "level2"=>$level2Array, "level3"=>$level3Array];
}
public function getExclusiveRandomProducts($catalogId){
$catalogObj = Catalog::getById($catalogId, ["force" => true]);
$productIds = [];
foreach ($catalogObj->getProduct() as $key => $value) {
$productIds[] = $value->getId();
}
$catalogProducts = new DataObject\Product\Listing();
$catalogProducts->setCondition("o_id IN (?)", [$productIds]);
$catalogProducts->setOrderKey("RAND()", false);
$catalogProducts->setLimit(2);
$catalogProductsArray = $catalogProducts->load();
return $catalogProductsArray;
}
public function getCatalogTypeInMenu($catalogId){
$catalogObj = Catalog::getById($catalogId, ["force" => true]);
$catalogType = "";
return $catalogObj->getCatalogFor() ?? "";
}
public function getWishlistProductComment($wishlistId, $productId){
$wishlistCommentsListing = new DataObject\WishListComments\Listing();
$wishlistCommentsListing->setCondition("wishlist like '%".$wishlistId."%' AND Product like '%".$productId."%'");
$wishlistCommentsObj = $wishlistCommentsListing->load();
$wishlistComment = "";
if(count($wishlistCommentsObj) > 0){
$wishlistComment = $wishlistCommentsObj[0]->getWishlistCommentDetails();
}
return $wishlistComment;
}
public function getQuantityUnit($unitId){
$unit = \Pimcore\Model\DataObject\QuantityValue\Unit::getById($unitId);
return $unit;
}
public function getCDNurl(){
return PIMCORE_CDN_BASEURL;
}
public function getLeadTimeData(){
$leadTimeList = new DataObject\LeadTime\Listing();
$leadTimeList->setUnpublished(true);
$leadTimeArray = $leadTimeList->load();
return $leadTimeArray;
}
public function getColorData(){
$colorList = new DataObject\Color\Listing();
$colorList->setUnpublished(true);
$colorArray = $colorList->load();
return $colorArray;
}
public function getRFQData($RFQId){
$data = DataObject\Fieldcollection\Definition::getByKey($RFQId);
$options = $data->getFieldDefinitions()['currencyUnit']->getOptions();
return $options;
}
public function getCartStatusInFieldCollection($RFQId){
$data = DataObject\Fieldcollection\Definition::getByKey($RFQId);
$options = $data->getFieldDefinitions()['status']->getOptions();
return $options;
}
public function getCurrentSite(){
$nuFindDomain = ['3smisource', 'nu-find'];
$threeSGlobalDomain = ['3swebsite', '3sglobal'];
if (\Pimcore\Model\Site::isSiteRequest()) {
return $GLOBALS['site'] ?? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
}
else if(GeneralHelper::array_contains($_SERVER['SERVER_NAME'], $threeSGlobalDomain)){
return '3SWebsite';
}
else if(GeneralHelper::array_contains($_SERVER['SERVER_NAME'], $nuFindDomain)){
return 'NuFind';
}
else{
return 'NuFind';
}
}
public function getSubDocumentCategory($category){
$attr = $category.'SubTypes';
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$customerData = $customer->getClass()->getFieldDefinition($attr);
$getSubcategory = $customerData->getChilds()[0]->getOptions();
$subcatArray = [];
foreach($getSubcategory as $subcat){
$subcatArray[$subcat['value']] = $subcat['key'];
}
return $subcatArray;
}
public function getCategoryTopParent($categoryId){
$categoryObj = SiteMenu::getById($categoryId);
if($categoryObj->getLevel() == 1 && $categoryObj->getType() != "folder"){
return $categoryObj->getLabel();
}
else{
if($categoryObj->getType() != "folder"){
return $this->getCategoryTopParent($categoryObj->getParent()->getId());
}
}
}
public function getOnlyProductId($productId){
if(strpos($productId, "?") !== false){
$productId = strtok($productId, '?');
}
return $productId;
}
public function getArrayObjectsToIds($arrayOfObj){
$idsArray = [];
if(count($arrayOfObj)){
foreach($arrayOfObj as $singleObj){
$idsArray[] = $singleObj->getId();
}
}
return $idsArray;
}
public function pimcoreComplexUrl($requestVariables, $currentUrl = '')
{
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
// Parse the URL to get the query parameters and the path
$urlParts = parse_url($actual_link);
$queryParams = [];
parse_str($urlParts['query'] ?? '', $queryParams);
// Remove the $requestVariables parameter if it exists
unset($queryParams[$requestVariables]);
// Rebuild the query string without the $requestVariables parameter
$queryString = http_build_query($queryParams);
// Get the URL without the query string
$actual_link = $urlParts['path'];
// Append the query string to the URL
$actual_link .= empty($queryString) ? '' : '?' . $queryString;
// Append the $requestVariables parameter to the URL
$x = $actual_link . (strpos($actual_link, '?') === false ? '?' : '&') . $requestVariables . '=';
return $x;
}
public function getSingleProductById($productId, $field){
$productObj = Product::getById($productId, ["force" => true]);
$value = "";
$getter = 'get' . ucfirst($field);
if (method_exists($productObj, $getter)) {
$value = $productObj->$getter();
}
return $value;
}
public function getRFQGeneratedPIStatus($rfqId) {
return $this->getCachedPIObjectId($rfqId) !== '';
}
public function getPIObjId($rfqId) {
return $this->getCachedPIObjectId($rfqId);
}
public function getRFQGeneratedPOStatus($rfqId) {
return $this->getCachedPOObjectId($rfqId) !== '';
}
public function getPOObjId($rfqId) {
return $this->getCachedPOObjectId($rfqId);
}
private function getCachedPIObjectId($rfqId)
{
$rfqId = (string)$rfqId;
if ($rfqId === '') {
return '';
}
if (!array_key_exists($rfqId, $this->piObjectIdsByRfq)) {
$list = new \Pimcore\Model\DataObject\ProformaInvoice\Listing();
$list->setCondition("linkedRFQNumber = ?", [$rfqId]);
$list->setLimit(1);
$objects = $list->load();
$this->piObjectIdsByRfq[$rfqId] = count($objects) > 0 ? $objects[0]->getId() : '';
}
return $this->piObjectIdsByRfq[$rfqId];
}
private function getCachedPOObjectId($rfqId)
{
$rfqId = (string)$rfqId;
if ($rfqId === '') {
return '';
}
if (!array_key_exists($rfqId, $this->poObjectIdsByRfq)) {
try {
$list = new \Pimcore\Model\DataObject\PurchaseOrders\Listing();
$list->setCondition("linkedRFQNumber = ?", [$rfqId]);
$list->setLimit(1);
$objects = $list->load();
$this->poObjectIdsByRfq[$rfqId] = count($objects) > 0 ? $objects[0]->getId() : '';
} catch (\Throwable $e) {
$this->poObjectIdsByRfq[$rfqId] = '';
}
}
return $this->poObjectIdsByRfq[$rfqId];
}
}