Cristian Capannini
Cristian Capannini

Reputation: 110

Module Prestashop 8.1.0: GIF Image Uploader

I have just created this module which would allow you to upload a gif for each individual product to be included in the product gallery, however the gif must be saved in the database.

The problem is that 1 the file is not loaded or even saved in the database and even inserting the URL does not work. I don't understand where the problem lies.

In practice, this module adds the upload form both via file and via the complete URL address of the animated image in the product detail (when you go to the product modification phase). Obviously when you upload a gif it must not be converted otherwise there is no point in uploading animated gifs and then they are displayed static. At the moment the module would save them in its uploads folder (inside the module itself).

Structure module

colan_prod_gifs.php

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

class Colan_Prod_Gifs extends Module
{
    public function __construct()
    {
        $this->name = 'colan_prod_gifs';
        $this->tab = 'administration';
        $this->version = '1.0.0';
        $this->author = 'Author';
        $this->need_instance = 0;
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('Uploader GIF');
        $this->description = $this->l('Carica GIF e visualizza nella galleria del prodotto.');
    }

    public function install()
    {
        return parent::install() && $this->installDb() && $this->registerHook('actionAdminControllerSetMedia') && $this->registerHook('displayAdminProductsExtra') && $this->registerHook('displayFooterProduct');
    }

    public function uninstall()
    {
        return parent::uninstall() && $this->uninstallDb();
    }

    public function installDb()
    {
        $sql = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'prod_gifs` (
            `id_gif` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `id_product` INT UNSIGNED NOT NULL,
            `gif_url` VARCHAR(255) NULL,
            `gif_file` VARCHAR(255) NULL
        ) ENGINE=' . _MYSQL_ENGINE_;
        return Db::getInstance()->execute($sql);
    }

    private function uninstallDb()
    {
        $sql = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'prod_gifs`';
        return Db::getInstance()->execute($sql);
    }

    public function hookActionAdminControllerSetMedia($params)
    {
        if ($this
            ->context
            ->controller->controller_name === 'AdminProducts')
        {
            // $this->context->controller->addJS($this->_path . 'views/js/admin.js');
            // $this->context->controller->addCSS($this->_path . 'views/css/admin.css');
            
        }
    }

    public function hookDisplayAdminProductsExtra($params)
    {
        $id_product = (int)$params['id_product'];

        $query = 'SELECT * FROM `' . _DB_PREFIX_ . 'prod_gifs` WHERE id_product = ' . $id_product;

        file_put_contents(__DIR__ . "/log.txt", "hookDisplayAdminProductsExtra select: " . $query . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);

        $gifs = Db::getInstance()->executeS($query);

        if (Tools::isSubmit('submitGif'))
        {
            $this->handleGifUpload($id_product);
        }

        $this
            ->context
            ->smarty
            ->assign(['gifs' => $gifs, 'id_product' => $id_product, 'module_dir' => _MODULE_DIR_ . $this->name . '/uploads/', ]);

        return $this->display(__FILE__, 'views/templates/admin/product_gifs.tpl');
    }

    private function handleGifUpload($id_product)
    {
        file_put_contents(__DIR__ . "/log.txt", "handleGifUpload id product " . $id_product . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);

        file_put_contents(__DIR__ . "/log.txt", "handleGifUpload FILES " . json_encode($_FILES) . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);

        if (isset($_FILES['gif_file']) && $_FILES['gif_file']['error'] === UPLOAD_ERR_OK)
        {
            $upload_dir = _PS_MODULE_DIR_ . $this->name . '/uploads/';
            if (!is_dir($upload_dir))
            {
                mkdir($upload_dir, 0755, true);
            }

            // Sanitize the file name
            $file_name = uniqid() . '_' . basename($_FILES['gif_file']['name']);
            $file_path = $upload_dir . $file_name;

            // Move the uploaded file
            if (move_uploaded_file($_FILES['gif_file']['tmp_name'], $file_path))
            {
                // Save the file details in the database
                Db::getInstance()->insert('prod_gifs', ['id_product' => (int)$id_product, 'gif_file' => $file_name, 'gif_url' => null, // Leave URL null if file is uploaded
                ]);

                return true;
            }
            else
            {
                file_put_contents(__DIR__ . "/log.txt", "handleGifUpload upload gif errore urante il caricamento del file" . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);
                //$this->context->controller->errors[] = $this->l('Failed to upload the GIF file.');
                return false;
            }
        }
        elseif (Tools::getValue('gif_url'))
        {
            // Handle URL instead of file upload
            $gif_url = Tools::getValue('gif_url');
            Db::getInstance()->insert('prod_gifs', ['id_product' => (int)$id_product, 'gif_file' => null, // Leave file null if URL is provided
            'gif_url' => pSQL($gif_url) , ]);

            return true;
        }

        $this
            ->context
            ->controller
            ->errors[] = $this->l('No file or URL provided for GIF upload.');
        return false;
    }

    public function hookDisplayFooterProduct($params)
    {
        $id_product = (int)Tools::getValue('id_product');
        $gifs = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'prod_gifs` WHERE id_product = ' . $id_product);
        $this
            ->context
            ->smarty
            ->assign(['gifs' => $gifs]);
        return $this->display(__FILE__, 'views/templates/front/display_gifs.tpl');
    }
}

display_gifs.tpl:

<div class="product-gifs">
    <h4>{l s='GIF Gallery' mod='colan_prod_gifs'}</h4>
    {if $gifs}
        <div class="gifs-gallery">
            {foreach from=$gifs item=gif}
                <div class="gif-item">
                    <img src="{$gif.gif_url ? $gif.gif_url : $gif.gif_file}" alt="GIF" class="img-fluid">
                </div>
            {/foreach}
        </div>
    {else}
        <p>{l s='Nessuna gif per il prodotto selezionato.' mod='colan_prod_gifs'}</p>
    {/if}
</div>

product_gifs.tpl:

<div class="panel">
    <h3>{l s='GIF Gallery' mod='colan_prod_gifs'}</h3>
    <form method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="gif_file">{l s='Upload GIF File' mod='colan_prod_gifs'}</label>
            <input type="file" name="gif_file" id="gif_file" class="form-control">
        </div>
        <div class="form-group">
            <label for="gif_url">{l s='Or Enter GIF URL' mod='colan_prod_gifs'}</label>
            <input type="url" name="gif_url" id="gif_url" class="form-control">
        </div>
        <button type="submit" name="submitGif" class="btn btn-primary">{l s='Save GIF' mod='colan_prod_gifs'}</button>
    </form>
    <ul>
        {foreach from=$gifs item=gif}
            <li>
               <img src="{{ gif.gif_url ?: module_dir ~ gif.gif_file }}" alt="GIF" style="max-width:100px;">
            </li>
        {/foreach}
    </ul>
</div>

Upvotes: 0

Views: 39

Answers (0)

Related Questions