HEX
Server: Apache
System: Linux srv13.cpanelhost.cl 3.10.0-962.3.2.lve1.5.38.el7.x86_64 #1 SMP Thu Jun 18 05:28:41 EDT 2020 x86_64
User: cca63905 (4205)
PHP: 7.3.20
Disabled: NONE
Upload Files
File: //proc/self/cwd/nueva/modules/chatgptcontentgenerator/src/Process/GeneratePostCron.php
<?php
/**
 * 2007-2024 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * 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.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <contact@prestashop.com>
 *  @copyright 2007-2024 PrestaShop SA
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */
namespace PrestaShop\Module\Chatgptcontentgenerator\Process;

if (!defined('_PS_VERSION_')) {
    exit;
}

use PrestaShop\Module\Chatgptcontentgenerator\Entity\GptContentPost;
use PrestaShop\Module\Chatgptcontentgenerator\Entity\GptContentPostCron;
use PrestaShop\Module\Chatgptcontentgenerator\Helper\GeneratePostPeriod;
use PrestaShop\Module\Chatgptcontentgenerator\Helper\ShortCodeContentGenerator as HelperShortCode;

class GeneratePostCron extends GeneratePost
{
    private $object;
    private $helperShortCode;
    private $helperPeriod;

    public function __construct($id)
    {
        parent::__construct();

        $this->object = new GptContentPostCron($id, $this->context->language->id);
        $this->helperShortCode = new HelperShortCode();
        $this->helperPeriod = new GeneratePostPeriod($this->object);
    }

    public function run()
    {
        if (!$this->checkRunCron()) {
            return true;
        }

        $errors = [];
        // $products = $this->object->getProducts();

        // foreach ($products as $idProduct) {
        //     try {
        //         foreach ($this->helperPeriod->getNumberByProduct($idProduct) as $dateAdd) {
        //             $this->generateByIdProduct($idProduct, $dateAdd);
        //         }
        //     } catch (\Exception $e) {
        //         $errors[] = [
        //             'id_product' => $idProduct,
        //             'code' => $e->getCode(),
        //             'message' => $e->getMessage(),
        //         ];
        //     }
        // }
        exit;
    }

    private function generateByIdProduct($idProduct, $dateAdd = null)
    {
        if (!$requestData = $this->getRequestData($idProduct)) {
            return true;
        }

        if ($this->object->isCustomRequest()) {
            $res = $this->generatePostByPrompt(
                $idProduct,
                $this->object->id_lang,
                $requestData['promptContent'],
                $requestData['promptTitle'],
                $this->object->length_content,
                $requestData['images'],
                $this->object->active_post,
                $this->object->number_links_product
            );
        } else {
            $res = $this->generatePostByProduct(
                $idProduct,
                $requestData['product'],
                $this->object->id_lang,
                $this->object->length_content,
                $requestData['images'],
                $this->object->active_post,
                $this->object->number_links_product
            );
        }

        if (isset($res['post']) && $res['post'] instanceof GptContentPost) {
            $postObj = $res['post'];
            $this->addGptContentGeneratorByPost($postObj, $this->object->id_lang, true);
            $isUpdate = false;

            if ($this->object->is_translate) {
                $this->translateByPost($postObj);
                $isUpdate = true;
            }

            if ($dateAdd && \Validate::isDate($dateAdd)) {
                $postObj->date_add = $dateAdd;
                $isUpdate = true;
            }

            if ($isUpdate) {
                $postObj->update();
            }
        }
    }

    private function checkRunCron()
    {
        if (
            !\Validate::isLoadedObject($this->object)
            || !$this->object->active
        ) {
            $message = $this->trans(
                'Cron job not found',
                [],
                'Modules.Chatgptcontentgenerator.Admin'
            );

            throw new \PrestaShopException($message);
        }

        return true;
    }

    private function getRequestData($idProduct)
    {
        $product = (new \Product((int) $idProduct, true, (int) $this->object->id_lang));

        if (!\Validate::isLoadedObject($product)) {
            return false;
        }

        $promptTitle = '';
        $promptContent = '';
        $images = [];

        if ($this->object->use_produt_image) {
            $product_images = $product->getImages($this->object->id_lang);

            foreach ($product_images as $image) {
                $images[] = [
                    'id' => (int) $image['id_image'],
                    'save_path' => _PS_IMG_DIR_ . 'p/' . \Image::getImgFolderStatic($image['id_image']) . $image['id_image'] . '.jpg',
                ];
            }
        }

        if ($this->object->isCustomRequest()) {
            $promptTitle = $this->helperShortCode->generateContentByObject($product, $this->object->short_code_title, $this->object->id_lang);
            $promptContent = $this->helperShortCode->generateContentByObject($product, $this->object->short_code_content, $this->object->id_lang);
        }

        return [
            'id_product' => $product->id,
            'product' => [
                'name' => $product->name,
                'category' => $product->category,
                'brand' => $product->manufacturer_name,
            ],
            'promptTitle' => $promptTitle,
            'promptContent' => $promptContent,
            'images' => $images,
        ];
    }

    private function translateByPost(&$post)
    {
        if (!$fromLang = \Language::getLanguage($this->object->id_lang)) {
            return false;
        }

        $mh = curl_multi_init();
        $ch = [];

        foreach (\Language::getLanguages() as $toLang) {
            if ($toLang['id_lang'] == $fromLang['id_lang']) {
                continue;
            }
            $idLang = (int) $toLang['id_lang'];

            $link = $this->context->link->getModuleLink(
                $this->module->name,
                'cron',
                [
                    'token' => GptContentPostCron::getCronTokenById($post->id, 'translate_post'),
                    'id' => (int) $post->id,
                    'from' => $fromLang['iso_code'],
                    'to' => $toLang['iso_code'],
                ]
            );

            $curl = curl_init($link);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $ch[$idLang] = $curl;
            curl_multi_add_handle($mh, $ch[$idLang]);
        }

        if ($ch) {
            do {
                $status = curl_multi_exec($mh, $active);
                if ($active) {
                    curl_multi_select($mh);
                }
            } while ($active && $status == CURLM_OK);
        }

        foreach ($ch as $chMulti) {
            $content = json_decode(curl_multi_getcontent($chMulti), true);

            if (isset($content['result']) && is_array($content['result'])) {
                foreach ($content['result'] as $iso => $value) {
                    $idLang = \Language::getIdByIso($iso);

                    if (!$idLang) {
                        continue;
                    }

                    if (!empty($value[TranslatePost::TRANSLATE_TYPE_TITLE]['text'])) {
                        $post->title[$idLang] = $value[TranslatePost::TRANSLATE_TYPE_TITLE]['text'];
                    }

                    if (!empty($value[TranslatePost::TRANSLATE_TYPE_CONTENT]['text'])) {
                        $post->content[$idLang] = $value[TranslatePost::TRANSLATE_TYPE_CONTENT]['text'];
                    }

                    if (!empty($value[TranslatePost::TRANSLATE_TYPE_SHORT_CONTENT]['text'])) {
                        $post->short_content[$idLang] = $value[TranslatePost::TRANSLATE_TYPE_SHORT_CONTENT]['text'];
                    }
                }
            }

            curl_multi_remove_handle($mh, $chMulti);
        }

        curl_multi_close($mh);

        return true;
    }
}