imaxaddcatbyfeature.php 15.8 KB
<?php

require_once dirname(__FILE__) . '/ComunesImaxAddCatbyFeature.php';
require_once dirname(__FILE__) . '/FuncionesImaxAddCatbyFeature.php';

class ImaxAddCatbyFeature extends Module {

    use ComunesImaxAddCatbyFeature;

    var $versionPS;
    var $idShop;
    var $idLang;
    var $idTab;
    private $_html = '';
    private static $funciones;

    const prefijo = 'imax_addcat_';

    public function __construct() {
        $this->name = 'imaxaddcatbyfeature';
        $this->tab = 'administration';
        $this->version = '1.5';
        $this->author = 'Informax';
        $this->need_instance = 0;
        $this->idManual = '';
        $this->forceCheck = 0;
        $this->sufijo = self::prefijo;
        parent::__construct();
        $this->displayName = $this->l('Informax add to category by feature');
        $this->description = $this->l('Informax add to category by feature');

        if (version_compare(_PS_VERSION_, '1.7.0.0 ', '>=')) {
            $this->versionPS = 17;
            $context = Context::getContext();
            $this->idShop = $context->shop->id;
            $this->idLang = $context->language->id;
        } elseif (version_compare(_PS_VERSION_, '1.6.0.0 ', '>=')) {
            $this->versionPS = 16;
            $context = Context::getContext();
            $this->idShop = $context->shop->id;
            $this->idLang = $context->language->id;
        } elseif (version_compare(_PS_VERSION_, '1.5.0.0 ', '>=')) {
            $this->versionPS = 15;
            $context = Context::getContext();
            $this->idShop = $context->shop->id;
            $this->idLang = $context->language->id;
        } else {
            $this->_html .= $this->l("La version minima de funcionamiento para nuestros modulos es la 1.5");
        }
    }

    public function install() {
        $directorioAdmin = getcwd();
        if (is_file(dirname(__FILE__) . '/' . $this->name . '_cron.php') && !@copy(dirname(__FILE__) . '/imaxaddcatbyfeature_cron.php', $directorioAdmin . '/imaxaddcatbyfeature_cron.php')) {
            $this->_errors[] = $this->l('Ha fallado al copiar el fichero de cron');
         }
        if (is_file(dirname(__FILE__) . '/' . $this->name . '_cron.php.imax') && !@copy(dirname(__FILE__) . '/imaxaddcatbyfeature_cron.php.imax', $directorioAdmin . '/imaxaddcatbyfeature_cron.php.imax')) {
            $this->_errors[] = $this->l('Ha fallado al copiar el fichero de cron ofuscado');           
        }

        include(dirname(__FILE__) . '/configuration.php');
        foreach ($configuracion AS $indice => $valor) {
            if (!Configuration::updateGlobalValue($indice, $valor)) {
                return false;
            }
        }

        if (!parent::install())
            return false;

        foreach ($hooks as $hook) {
            if (!$this->registerHook($hook)) {
                $this->_errors[] = $this->l('Ha fallado la instalacion del hook:') . ' ' . $hook;
                return false;
            }
        }

        include(dirname(__FILE__) . '/sql-install.php');
        foreach ($sql as $s) {
            if (!Db::getInstance()->execute($s)) {
                $this->_errors[] = $this->l("Error al ejecutar") . $s;
                return false;
            }
        }

        if (!$this->installTab()) {
            $this->_errors[] = $this->l('Error al instalar el tab');
            return false;
        }

        return true;
    }

    public function uninstall() {
        if (!parent::uninstall()) {
            return false;
        }

        include(dirname(__FILE__) . '/sql-unninstall.php');
        foreach ($sql as $s) {
            if (!Db::getInstance()->execute($s)) {
                $this->_errors[] = $this->l("Error al ejecutar") . $s;
                return false;
            }
        }
        $directorioAdmin = getcwd();

        if (!unlink($directorioAdmin . '/imaxaddcatbyfeature_cron.php')) {
            $this->_errors[] = $this->l('Error al borrar el fichero de Cron');
            return false;
        }

        if (!$this->uninstallTab()) {
            $this->_errors[] = $this->l('Error al eliminar el tab');
            return false;
        }

        include(dirname(__FILE__) . '/configuration.php');
        foreach ($configuracion AS $indice => $valor) {
            if (Configuration::getGlobalValue($indice) !== FALSE) {
                if (!Configuration::deleteByName($indice)) {
                    return false;
                }
            }
        }

        return true;
    }

    public function getContent() {
        $this->getTxtFiles();
        $this->addCSS('css.css');
        //$this->addJS('jquery.dynatree.min.js');
        $this->addJqueryUI('ui.sortable');
        $this->addJS('functions.js');

        $this->addCSS('publi.css');
        $this->_html .= $this->createHelpHeader();
        if (!empty($_POST))
            $this->_html .= $this->_postProcess();

        $this->_displayForm();
        $this->_html .= $this->getModuleFooter();
        return $this->_html;
    }

    private function _postProcess() {
        $accion = Tools::getValue("accion");
        $this->idTab = Tools::getValue("idTab");
        $html = "";
        switch ($accion) {
            case 'gestionLicencia':
                $this->forceCheck = 1;
                if (Configuration::updateGlobalValue(self::prefijo . 'LICENCIA', trim(Tools::getValue('licencia')))) {
                    $html .= $this->displayConfirmation($this->l('Licencia guardada correctamente.'));
                } else {
                    $html .= $this->displayError($this->l('Ha ocurrido un error al guardar la licencia.'));
                }
                break;
            case 'configuracion':
                if (Configuration::updateGlobalValue(self::prefijo . 'NUM_ELEMENTOS', (int) (Tools::getValue('numElementos')))) {
                    $html .= $this->displayConfirmation($this->l('Numero de elementos guardado correctamente.'));
                } else {
                    $html .= $this->displayError($this->l('Ha ocurrido un error al guardar el numero de elementos.'));
                }
                break;
            case 'generar_token':
                if (Configuration::updateGlobalValue(self::prefijo . 'TOKEN', md5(uniqid()))) {
                    $html .= $this->displayConfirmation($this->l('Token regenerado correctamente.'));
                } else {
                    $html .= $this->displayError($this->l('Ha ocurrido un error al regenerar el token.'));
                }
                break;
            case 'configurarCategorizacion':
                $criteriosOrdenados = array();
                $criterios = Tools::getValue('categorizacion', array());
                foreach ($criterios as $criterio) {
                    $criteriosOrdenados[(int) $criterio['orden']] = $criterio;
                }

                if (Configuration::updateGlobalValue(self::prefijo . 'CATS_FEATURE', serialize($criteriosOrdenados))) {
                    $html = $this->displayConfirmation($this->l('Criterios guardados correctamente.'));
                } else {
                    $html = $this->displayError($this->l('Ha ocurrido un error.'));
                }
                break;

            default:
                break;
        }

        return $html;
    }

    public function _displayForm() {
        return $this->displayFormTrait(array('_configuracion' => $this->l('Configuracion'), '_mostrarLicencia' => $this->l('Licencia')), '');
    }

    private function _mostrarLicencia() {
        return $this->mostrarLicenciaTrait(2);
    }

    private function _configuracion() {
        include_once(dirname(__FILE__) . '/functionsForm.php');
        include_once(dirname(__FILE__) . '/imaxAcordeon.php');
        $catsFeature = unserialize(Configuration::getGlobalValue(self::prefijo . 'CATS_FEATURE'));
        $token = Configuration::getGlobalValue(self::prefijo . 'TOKEN');
        $numElementos = Configuration::getGlobalValue(self::prefijo . 'NUM_ELEMENTOS');
        $html = '';
        $respuesta = array();
        //

        $acordeon = new imaxAcordeon($this->_path);

        $form = new imaxForm($this, $this->_path);
        $form->createHidden("accion", "configuracion");
        $form->createHidden("idTab", "1");
        $form->createFormTextGroup('numElementos', $numElementos, $this->l('Numero de elementos a procesar'), $this->l('Numero de elementos a procesar'));
        $form->createSubmitButton('opcionesConfiguracion', $this->l('Guardar'));
        $html .= $acordeon->renderAcordeon($this->l('Configuracion'), $form->renderForm());

        $html .= $acordeon->renderAcordeon($this->l('Categorizacion'), $this->getFunciones()->getFormCategorizacion(1)->renderForm());

        unset($form);
        $form = new imaxForm($this, $this->_path);
        $form->createHidden("accion", "generar_token");
        $form->createHidden("idTab", "1");

        $text = '<b>' . $this->l('ATENCION:') . '</b> ' . $this->l('Si cambia el token, tiene que cambiarlo tambien en las tareas de cron');
        $form->createFormInfomationText($text);
        $urlTienda = self::getUrlAdmin();
        $form->createFormInfomationText($this->l('Debe enviar por get a la url de servicio, ya sea con curl o wget el que soporte su servidor, con esta opción se cambian todos los productos independientemente de si usa o no un actualizador de productos'));
        $url = '<a href="' . $urlTienda . $this->name . '_cron.php?token=' . $token . '" target="_blank">' . $urlTienda . $this->name . '_cron.php?token=' . $token . '</a>';
        $form->createFormInfomationText($url);
        $form->createSubmitButton('opcionesConfiguracion', $this->l('Regenerar Token'));
        $html .= $acordeon->renderAcordeon($this->l('Tareas Cron'), $form->renderForm());

        return $html;
    }

    /**
     * Devuelve las funciones especificas del modulo.
     * @return FuncionesImaxNovedades
     */
    public function getFunciones() {
        if (!self::$funciones) {
            self::$funciones = new FuncionesImaxAddCatbyFeature($this);
        }

        return self::$funciones;
    }

    public function hookActionObjectProductAddAfter($params) {
        $cats = $this->getFunciones()->getCategoriesByProductFeature($params['object']->id);
        $this->getFunciones()->deshacerMovimientos($params['object']);
        if ($cats) {
            $this->getFunciones()->agregarCategorias($params['object'], $cats);
        } 
    }
    public function hookActionProductUpdate($params) {
        $params['object'] = $params['product'];
        $this->hookActionObjectProductUpdateAfter($params);
    }
    
    public function hookActionObjectProductUpdateAfter($params) {
        $cats = $this->getFunciones()->getCategoriesByProductFeature($params['object']->id);
        $this->getFunciones()->deshacerMovimientos($params['object']);
        if ($cats) {
            $this->getFunciones()->agregarCategorias($params['object'], $cats);
        } 
    }

    /**
     * Añade o elimina las categorias a los productos que tienen o no las caracteristicas asociadas
     * @return int La cantidad de productos procesados.
     */
    public function procesar() {
        $lastProduct = (int) Configuration::getGlobalValue(self::prefijo . 'LAST_PRODUCT');
        $numElementos = (int) Configuration::getGlobalValue(self::prefijo . 'NUM_ELEMENTOS');
        if (!$numElementos) {
            $numElementos = 100;
            Configuration::updateGlobalValue(self::prefijo . 'NUM_ELEMENTOS', $numElementos);
        }
        $sql = '    SELECT id_product '
                . ' FROM ' . _DB_PREFIX_ . 'product '
                . ' WHERE '
                . '     id_product > ' . $lastProduct . ''
                . ' LIMIT 0,' . $numElementos;
        $result = Db::getInstance()->executeS($sql);
        if (!$result) {
            Configuration::updateGlobalValue(self::prefijo . 'LAST_PRODUCT', 0);
        } else {
            foreach ($result AS $elemento) {
                $producto = new Product($elemento['id_product']);
                $this->getFunciones()->deshacerMovimientos($producto);
                $cats = $this->getFunciones()->getCategoriesByProductFeature($elemento['id_product']);
                 if ($cats) {
                    $this->getFunciones()->agregarCategorias($producto, $cats);
                }
                
                Configuration::updateGlobalValue(self::prefijo . 'LAST_PRODUCT', $elemento['id_product']);
            }
        }

        return count($result);
    }

    /*
      public function procesar() {
      if (!function_exists('procesar_')) {
      $function = $this->getFunction();
      eval(gzuncompress(base64_decode($function)));
      }
      if (function_exists('procesar_')) {
      return procesar_($this);
      }

      echo $this->l('Este modulo no tiene una licencia valida: ') . $this->name;
      echo '<br />';
      echo $this->l('Contacte con nosotros para obtener una licencia valida');
      die();
      }
     */

    public function l($msg, $modulo = '', $locale = null) {
        if ($modulo == '') {
            $modulo = 'traducciones' . strtolower($this->name);
        }
        return parent::l($msg, $modulo, $locale);
    }

    /**
     * Devuelve el formulario para los criterios de desactivacion.
     * @param int $idTab
     * @return imaxForm
     */
    public function getFormCriteriosNovedades($idTab) {
        //Datos para js    
        $caracteristicas = Feature::getFeatures($this->idLang);
        $caracteristicasFormateadas = array(0 => $this->modulo->l('- Seleccione uno -'));
        $valoresCaracteristicaFormateados = array();
        foreach ($caracteristicas as $caracteristica) {
            $caracteristicasFormateadas[$caracteristica['id_feature']] = $caracteristica['name'];
            $valoresCaracteristica = FeatureValue::getFeatureValuesWithLang($this->idLang, $caracteristica['id_feature']);
            if ($valoresCaracteristica) {
                foreach ($valoresCaracteristica as $valorCaracteristica) {
                    if (!isset($valoresCaracteristicaFormateados[$caracteristica['id_feature']])) {
                        $valoresCaracteristicaFormateados[$caracteristica['id_feature']] = array(0 => $this->modulo->l('- Seleccione uno -'));
                    }

                    $valoresCaracteristicaFormateados[$caracteristica['id_feature']][$valorCaracteristica['id_feature_value']] = $valorCaracteristica['value'];
                }
            } else {
                $valoresCaracteristicaFormateados[$caracteristica['id_feature']] = array(0 => $this->modulo->l('- Seleccione uno -'));
            }
        }
        $cats = $form = new imaxForm($this, $this->modulo->getPathUri());
        $form->createHidden("accion", "configurarCriteriosNovedad");
        $form->createHidden("idTab", $idTab);
        $form->createFormTextGroup('numDiasNovedad', $numDiasNovedad, $this->modulo->l('Numero de dias a restar para los productos no nuevos'));
        //  $form->addToForm($this->crearSelectCategorias());
        /*  $form->addToForm('
          <script>
          var caracteristicasFormateadas = ' . json_encode($caracteristicasFormateadas) . ';
          var valoresCaracteristicaFormateados = ' . json_encode($valoresCaracteristicaFormateados) . ';
          var tiposFormateadosNovedad = ' . json_encode($tiposFormateadosNovedad) . ';
          var criteriosSeleccionadosNovedad = ' . json_encode(unserialize(Configuration::getGlobalValue($this->prefijo . 'CRITERIOS_NOVEDAD'))) . ';
          </script>
          <table id="tablaCriteriosNovedad" class="table">
          <thead>
          <tr><th>' . $this->modulo->l('Caracteristica') . '</th><th>' . $this->modulo->l('Valor caracteristica') . '</th><th>' . $this->modulo->l('Accion') . '</th><th></th></tr>
          </thead>
          <tbody></tbody>
          </table>'); */

        $form->createButton('agregarCriterioNovedad', $this->modulo->l('Nuevo'));
        $form->createSubmitButton('save', $this->modulo->l('Guardar'));
        return $form;
    }

}