Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/old/app/code/Cnc/Shipping/Preference/Model/Dhl/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/old/app/code/Cnc/Shipping/Preference/Model/Dhl/Carrier.php
<?php

namespace Cnc\Shipping\Preference\Model\Dhl;

use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Dhl\Model\Validator\XmlValidator;
use Magento\Directory\Helper\Data;
use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\CurrencyFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\Directory\ReadFactory;
use Magento\Framework\HTTP\AsyncClientInterface;
use Magento\Framework\HTTP\ZendClientFactory;
use Magento\Framework\Math\Division;
use Magento\Framework\Stdlib\DateTime;
use Magento\Framework\Stdlib\StringUtils;
use Magento\Framework\Xml\Security;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Rate\Result\ProxyDeferredFactory;
use Magento\Framework\Module\Dir;
use Magento\Shipping\Model\Simplexml\ElementFactory;
use Magento\Shipping\Model\Tracking\Result\ErrorFactory;
use Magento\Shipping\Model\Tracking\Result\StatusFactory;
use Magento\Shipping\Model\Tracking\ResultFactory;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use Throwable;
use const DATE_RFC3339;

class Carrier extends \Magento\Dhl\Model\Carrier
{
    /**
     * DHL service prefixes used for message reference
     */
    private const SERVICE_PREFIX_QUOTE = 'QUOT';
    private const SERVICE_PREFIX_SHIPVAL = 'SHIP';
    private const SERVICE_PREFIX_TRACKING = 'TRCK';


    /**
     * Xml response validator
     *
     * @var \Magento\Dhl\Model\Validator\XmlValidator
     */
    private $xmlValidator;

    /**
     * @var ProductMetadataInterface
     */
    private $productMetadata;

    /**
     * @var AsyncClientInterface
     */
    private $httpClient;

    /**
     * @var ProxyDeferredFactory
     */
    private $proxyDeferredFactory;

    /**
     * Carrier constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param LoggerInterface $logger
     * @param Security $xmlSecurity
     * @param ElementFactory $xmlElFactory
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateFactory
     * @param MethodFactory $rateMethodFactory
     * @param ResultFactory $trackFactory
     * @param ErrorFactory $trackErrorFactory
     * @param StatusFactory $trackStatusFactory
     * @param RegionFactory $regionFactory
     * @param CountryFactory $countryFactory
     * @param CurrencyFactory $currencyFactory
     * @param Data $directoryData
     * @param StockRegistryInterface $stockRegistry
     * @param \Magento\Shipping\Helper\Carrier $carrierHelper
     * @param DateTime\DateTime $coreDate
     * @param Dir\Reader $configReader
     * @param StoreManagerInterface $storeManager
     * @param StringUtils $string
     * @param Division $mathDivision
     * @param ReadFactory $readFactory
     * @param DateTime $dateTime
     * @param \Magento\Framework\HTTP\LaminasClientFactory $httpClientFactory
     * @param array $data
     * @param XmlValidator|null $xmlValidator
     * @param ProductMetadataInterface|null $productMetadata
     * @param AsyncClientInterface|null $httpClient
     * @param ProxyDeferredFactory|null $proxyDeferredFactory
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        LoggerInterface $logger,
        Security $xmlSecurity,
        ElementFactory $xmlElFactory,
        \Magento\Shipping\Model\Rate\ResultFactory $rateFactory,
        MethodFactory $rateMethodFactory,
        ResultFactory $trackFactory,
        ErrorFactory $trackErrorFactory,
        StatusFactory $trackStatusFactory,
        RegionFactory $regionFactory,
        CountryFactory $countryFactory,
        CurrencyFactory $currencyFactory,
        Data $directoryData,
        StockRegistryInterface $stockRegistry,
        \Magento\Shipping\Helper\Carrier $carrierHelper,
        DateTime\DateTime $coreDate,
        Dir\Reader $configReader,
        StoreManagerInterface $storeManager,
        StringUtils $string,
        Division $mathDivision,
        ReadFactory $readFactory,
        DateTime $dateTime,
        \Magento\Framework\HTTP\LaminasClientFactory $httpClientFactory,
        array $data = [],
        XmlValidator $xmlValidator = null,
        ProductMetadataInterface $productMetadata = null,
        ?AsyncClientInterface $httpClient = null,
        ?ProxyDeferredFactory $proxyDeferredFactory = null
    ) {

        $this->xmlValidator = $xmlValidator ?? ObjectManager::getInstance()->get(XmlValidator::class);
        $this->productMetadata = $productMetadata ?? ObjectManager::getInstance()->get(ProductMetadataInterface::class);
        $this->httpClient = $httpClient ?? ObjectManager::getInstance()->get(AsyncClientInterface::class);
        $this->proxyDeferredFactory = $proxyDeferredFactory
            ?? ObjectManager::getInstance()->get(ProxyDeferredFactory::class);

        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $xmlSecurity, $xmlElFactory, $rateFactory, $rateMethodFactory, $trackFactory, $trackErrorFactory, $trackStatusFactory, $regionFactory, $countryFactory, $currencyFactory, $directoryData,
            $stockRegistry, $carrierHelper, $coreDate, $configReader, $storeManager, $string, $mathDivision, $readFactory, $dateTime, $httpClientFactory, $data, $xmlValidator, $productMetadata, $httpClient, $proxyDeferredFactory);
    }


    /**
     * Generation Shipment Details Node according to origin region
     *
     * @param \Magento\Shipping\Model\Simplexml\Element $xml
     * @param RateRequest $rawRequest
     * @param string $originRegion
     * @return void
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    protected function _shipmentDetails($xml, $rawRequest, $originRegion = '')
    {
        $nodeShipmentDetails = $xml->addChild('ShipmentDetails', '', '');
        $nodeShipmentDetails->addChild('NumberOfPieces', count($rawRequest->getPackages()));

        $nodePieces = $nodeShipmentDetails->addChild('Pieces', '', '');

        /*
         * Package type
         * EE (DHL Express Envelope), OD (Other DHL Packaging), CP (Custom Packaging)
         * DC (Document), DM (Domestic), ED (Express Document), FR (Freight)
         * BD (Jumbo Document), BP (Jumbo Parcel), JD (Jumbo Junior Document)
         * JP (Jumbo Junior Parcel), PA (Parcel), DF (DHL Flyer)
         */
        $i = 0;
        foreach ($rawRequest->getPackages() as $package) {
            $nodePiece = $nodePieces->addChild('Piece', '', '');
            $packageType = 'EE';
            if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
                $packageType = 'CP';
            }
            $nodePiece->addChild('PieceID', ++$i);
            $nodePiece->addChild('PackageType', $packageType);
            $nodePiece->addChild('Weight', sprintf('%.3f', $package['params']['weight']));
            $params = $package['params'];
            if ($params['width'] && $params['length'] && $params['height']) {
                $nodePiece->addChild('Width', round($params['width']));
                $nodePiece->addChild('Height', round($params['height']));
                $nodePiece->addChild('Depth', round($params['length']));
            }
            $content = [];
            foreach ($package['items'] as $item) {
                $content[] = $item['name'];
            }
            $nodePiece->addChild('PieceContents', substr(implode(',', $content), 0, 34));
        }

        $nodeShipmentDetails->addChild('Weight', sprintf('%.3f', $rawRequest->getPackageWeight()));
        $nodeShipmentDetails->addChild('WeightUnit', substr($this->_getWeightUnit(), 0, 1));
        /**
         * KALIOP OVERRIDE STARTS HERE
         * //TODO - change from preference for better solution?
         * Shipping method may be an array due to EcomBricks modification, we need to pass
         * string to be able to generate label from native module.
         */
        $shippingMethod = $rawRequest->getShippingMethod();
        if (is_array($shippingMethod)) {
            $shippingMethod = reset($shippingMethod);
        }
        $nodeShipmentDetails->addChild('GlobalProductCode', $shippingMethod);
        $nodeShipmentDetails->addChild('LocalProductCode', $shippingMethod);
        /** KALIOP OVERRIDE ENDS HERE */

        $nodeShipmentDetails->addChild(
            'Date',
            $this->_coreDate->date('Y-m-d', strtotime('now + 1day'))
        );
        $nodeShipmentDetails->addChild('Contents', 'DHL Parcel');
        /**
         * The DoorTo Element defines the type of delivery service that applies to the shipment.
         * The valid values are DD (Door to Door), DA (Door to Airport) , AA and DC (Door to
         * Door non-compliant)
         */
        $nodeShipmentDetails->addChild('DoorTo', 'DD');
        $nodeShipmentDetails->addChild('DimensionUnit', substr($this->_getDimensionUnit(), 0, 1));
        if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
            $packageType = 'CP';
        }
        $nodeShipmentDetails->addChild('PackageType', $packageType);
        if ($this->isDutiable($rawRequest->getOrigCountryId(), $rawRequest->getDestCountryId())) {
            $nodeShipmentDetails->addChild('IsDutiable', 'Y');
        }
        $nodeShipmentDetails->addChild(
            'CurrencyCode',
            $this->_storeManager->getWebsite($this->_request->getWebsiteId())->getBaseCurrencyCode()
        );
    }


    /**
     * Process response received from DHL's API for quotes.
     *
     * @param array $responsesData
     * @return Error|Result
     */
    private function processQuotesResponses(array $responsesData)
    {
        usort(
            $responsesData,
            function (array $a, array $b): int {
                return $a['date'] <=> $b['date'];
            }
        );
        /** @var string $lastResponse */
        $lastResponse = '';
        //Processing different dates
        foreach ($responsesData as $responseData) {
            $debugPoint = [];
            $debugPoint['request'] = $this->filterDebugData($responseData['request']);
            $debugPoint['response'] = $this->filterDebugData($responseData['body']);
            $debugPoint['from_cache'] = $responseData['from_cache'];
            $unavailable = false;
            try {
                //Getting availability
                $bodyXml = $this->_xmlElFactory->create(['data' => $responseData['body']]);
                $code = $bodyXml->xpath('//GetQuoteResponse/Note/Condition/ConditionCode');
                if (isset($code[0]) && (int)$code[0] == self::CONDITION_CODE_SERVICE_DATE_UNAVAILABLE) {
                    $debugPoint['info'] = sprintf(
                        __("DHL service is not available at %s date"),
                        $responseData['date']
                    );
                    $unavailable = true;
                }
            } catch (Throwable $exception) {
                //Failed to read response
                $unavailable = true;
                $this->_errors[$exception->getCode()] = $exception->getMessage();
            }
            if ($unavailable) {
                //Cannot get rates.
                $this->_debug($debugPoint);
                break;
            }
            //Caching rates
            $this->_setCachedQuotes($responseData['request'], $responseData['body']);
            $this->_debug($debugPoint);
            //Will only process rates available for the latest date possible.
            $lastResponse = $responseData['body'];
        }

        return $this->_parseResponse($lastResponse);
    }

    /**
     * Builds a datetime string to be used as the MessageTime in accordance to the expected format.
     *
     * @param string|null $datetime
     * @return string
     */
    private function buildMessageTimestamp(string $datetime = null): string
    {
        return $this->_coreDate->date(DATE_RFC3339, $datetime);
    }

    /**
     * Builds a string to be used as the MessageReference.
     *
     * @param string $servicePrefix
     * @return string
     * @throws LocalizedException
     */
    private function buildMessageReference(string $servicePrefix): string
    {
        $validPrefixes = [
            self::SERVICE_PREFIX_QUOTE,
            self::SERVICE_PREFIX_SHIPVAL,
            self::SERVICE_PREFIX_TRACKING
        ];

        if (!in_array($servicePrefix, $validPrefixes)) {
            throw new LocalizedException(
                __("Invalid service prefix \"$servicePrefix\" provided while attempting to build MessageReference")
            );
        }

        return str_replace('.', '', uniqid("MAGE_{$servicePrefix}_", true));
    }

    /**
     * Builds a string to be used as the request SoftwareName.
     *
     * @return string
     */
    private function buildSoftwareName(): string
    {
        return substr($this->productMetadata->getName(), 0, 30);
    }

    /**
     * Builds a string to be used as the request SoftwareVersion.
     *
     * @return string
     */
    private function buildSoftwareVersion(): string
    {
        return substr($this->productMetadata->getVersion(), 0, 10);
    }

    /**
     * Get the gateway URL
     *
     * @return string
     */
    private function getGatewayURL(): string
    {
        if ($this->getConfigData('sandbox_mode')) {
            return (string)$this->getConfigData('sandbox_url');
        } else {
            return (string)$this->getConfigData('gateway_url');
        }
    }
}

Spamworldpro Mini