?? GreyFile — Mystic File Browser

Current path: home/webdevt/www/schtroumpf.fr/modules/an_advantages/controllers/admin/



?? Go up: /home/webdevt/www/schtroumpf.fr/modules/an_advantages/controllers

?? Viewing: AdminAnAdvantages.php

<?php
/**
 * 2022 Anvanto
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 wesite only.
 * If you want to use this file on more websites (or projects), you need to purchase additional licenses. 
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 *  @author Anvanto <anvantoco@gmail.com>
 *  @copyright  2022 Anvanto
 *  @license    Valid for 1 website (or project) for each purchase of license
 *  International Registered Trademark & Property of Anvanto
 */

require_once _PS_MODULE_DIR_ . 'an_advantages/classes/AnAdvantages.php';

class AdminAnAdvantagesController extends ModuleAdminController
{   
    protected $_module = null;

    protected $position_identifier = 'position';
    protected $_defaultOrderBy = 'position';
    protected $_defaultOrderWay = 'ASC';  
	
    public function __construct()
    {
        $this->bootstrap = true;
        $this->context = Context::getContext();
        $this->table = 'an_advantages';
        $this->identifier = 'id_advantage';
        $this->className = 'AnAdvantages';
		$this->lang = true;
	
        $this->addRowAction('edit');
        $this->addRowAction('delete');
 
		$this->name = 'AdminAnAdvantagesController';
		
        parent::__construct();
		
        $this->fields_list = [
            'id_advantage' => [
				'title' => $this->module->l('ID'), 
				'width' => 25,
				'search'  => false,
            ],

            'image' => [
                'title' => $this->module->l('Image'), 
                'search'  => false,
                'type' => 'image',
            ],
            
            'title' => [
				'title' => $this->module->l('Title'), 
				'search'  => false,
			],
            
            'position' => [
                'title' => $this->l('Position'), 
                'search'  => false,
                'type' => 'position',
            ],  
	
            'active' => [
                'title' => $this->module->l('Active'),
                'width' => 40,
                'active' => 'update',
                'align' => 'center',
                'type' => 'bool',
				'search'  => false,
                'orderby' => false
            ],	
        ];

        if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL) {
            $this->_where .= ' AND a.' . $this->identifier . ' IN (
                SELECT sa.' . $this->identifier . '
                FROM `' . _DB_PREFIX_ . $this->table . '_shop` sa
                WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
            )';
        }
	}  

    public function setMedia( $isNewTheme = false ) {
        parent::setMedia();

        $this->addJquery();
        $this->js_files[] = $this->module->modulePath . 'views/js/Sortable.min.js';
        $this->js_files[] = $this->module->modulePath . 'views/js/sorting.js';
        $this->js_files[] = $this->module->modulePath . 'views/js/back.js';    
    }
    
    public function renderList()
	{
		$this->deleteImg();
        return   $this->module->topPromo() . parent::renderList() . $this->renderFormSettings();
	} 

    public function deleteImg()
    {
        if (Tools::getIsset('deleteBackgroundImage')) {
            if (Configuration::get(an_advantages::PREFIX.'bg_image') !=''){

                @unlink(AnAdvantages::imgDir . Configuration::get(an_advantages::PREFIX.'bg_image'));
                Configuration::updateValue(an_advantages::PREFIX.'bg_image', '');

            }   
        }
    }

    public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
    {
        parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop); 

        foreach ($this->_list as &$list) {

            if ($list['image'] !='' && Tools::file_exists_no_cache(AnAdvantages::imgDir.$list['image'])) {              
                $list['image'] = AnAdvantages::imgUrl.$list['image'];
            }
            
            $this->context->smarty->assign([
                'image' => $list['image'],
            ]);

            $list['image'] = $this->module->display(_PS_MODULE_DIR_.'an_advantages', 'views/templates/admin/list-img.tpl'); 
        } 
    }

    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Advantages');
    }
    
    public function initHeader()
    {
        parent::initHeader();

        $id_lang = $this->context->language->id;
        $link = $this->context->link;
        $tabs = &$this->context->smarty->tpl_vars['tabs']->value;

        foreach ($tabs as &$tab0) {
            if ($tab0['class_name'] == 'IMPROVE') {
                foreach ($tab0['sub_tabs'] as &$tab1) {
                    if ($tab1['class_name'] == 'AdminParentModulesSf') {
                        
                        foreach ($tab1['sub_tabs'] as &$tab2) {
                            if ($tab2['class_name'] == 'AdminAnAdvantages') {
                                $sub_tabs = &$tab2['sub_tabs'];

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnAdvantages'));
                                $tab['current'] = true;
                                $tab['href'] = $link->getAdminLink('AdminAnAdvantages');
                                $tab['active'] = true;
                                $sub_tabs[] = $tab; 
                                
                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnadvantagesBlocktext'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnadvantagesBlocktext');
                                $tab['active'] = true;
                                $sub_tabs[] = $tab;

                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    }    

    public function initContent()
    {
        $this->context->smarty->assign('current_tab_level', 3);

        return parent::initContent();
    }       
    
    public function viewImage($thumb)
    {
        if (!$thumb || $thumb == ''){
            return false;
        }

        $this->context->smarty->assign([
            'image' => AnAdvantages::imgUrl . $thumb,
        ]);

        return $this->module->display(_PS_MODULE_DIR_.'an_advantages', 'views/templates/admin/an_advantages/helpers/form/image_class.tpl');   
    }

	public function renderForm()
	{
		$this->initToolbar();
 		if (!$this->loadObject(true)) {
			return;
		}   

        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->module->l('Advantages')],
            'input' => [],
            'buttons' => [
                [
                    'type' => 'submit',
                    'title' => $this->l('Save'),
                    'icon' => 'process-icon-save',
                    'class' => 'pull-right',
                    'name' => 'submit'.$this->table
                ],
                [
                    'type' => 'submit',
                    'title' => $this->l('Save and stay'),
                    'icon' => 'process-icon-save',
                    'class' => 'pull-right',
                    'name' => 'submit'.$this->table.'AndStay'
                ],
            ],
        );

		$this->fields_form['input'][] = array(
			'type' => 'switch',
			'name' => 'active',
			'label' => $this->module->l('Active'),
			'values' => array(
				array(
					'id' => 'active_on',
					'value' => 1,
					'label' => $this->module->l('Enabled')
				),
				array(
					'id' => 'active_off',
					'value' => 0,
					'label' => $this->module->l('Disabled')
				)
			),
			
		);
        
        $this->fields_form['input'][] = array(
            'type' => 'file',
            'label' => $this->module->l('Image'),
            'required' => false,
            'name' => 'image_file',
            'image' => $this->viewImage($this->object->image),
        ); 

        $this->fields_form['input'][] = array(
            'type' => 'text',
            'name' => 'link',
            'label' => $this->l('Link'),    
            'lang' => true,
        );

		$this->fields_form['input'][] = array(
			'col' => 6,
			'type' => 'text',
			'name' => 'title',
			'label' => $this->module->l('Title'),	
			'lang' => true,
		);	

		$this->fields_form['input'][] = array(
			'type' => 'textarea',
			'class' => 'autoload_rte',
			'name' => 'text',
			'label' => $this->module->l('Text'),
			'lang' => true		
		);			

        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = [
                'required' => true,
                'type' => 'shop',
                'label' => $this->l('Shop association'),
                'name' => 'checkBoxShopAsso',
            ];
        }        

		return $this->module->topPromo() . parent::renderForm();
	}

    protected function getConfigFormCarrier()
    {

        $form = array(
            'form' => array(
                'legend' => array(
                    'title' => $this->l('Settings'),
                ),
                'input' => array(  
                    
                    array(
                        'type' => 'file',
                        'label' => $this->l('Background'),
                        'name' => 'advan_image',
                        'lang' => false,
                        'image' => $this->viewImage(Configuration::get(an_advantages::PREFIX . 'bg_image')),
                        'delete_url' =>  $this->context->link->getAdminLink('AdminAnAdvantages') . '&deleteBackgroundImage=',
                    ),
                ),

                'submit' => array(
                    'title' => $this->l('Save'),
                    'name' => 'advan_save_title',
                ),
            ),
        );
        return $form;
    }

    public function renderFormSettings()
    {
        $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
        
        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->name_controller = $this->name;
        $helper->submit_action = $this->name;
        $helper->currentIndex = $this->context->link->getAdminLink('AdminAnAdvantages', false);
        $helper->token = Tools::getAdminTokenLite('AdminAnAdvantages');
		
        $helper->default_form_language = $default_lang;
        $helper->allow_employee_form_lang = $default_lang;
       
        $helper->languages = $this->context->controller->getLanguages();
		$helper->id_language = $this->context->language->id;

        if (Tools::isSubmit('advan_save_title')) {
		    $this->postProcessSettings();			
		}
		
        return $helper->generateForm(array($this->getConfigFormCarrier()));		
	}

    public function postProcessSettings()
    {
        if (isset($_FILES['advan_image']) && isset($_FILES['advan_image']['tmp_name']) && !empty($_FILES['advan_image']['tmp_name'])) {
            if ($error = $this->validateUpload($_FILES['advan_image'])) {
                $this->errors[] = $error;                 
            }
        }

        if (!empty($this->errors)) {
            $this->display = 'edit';
            return false;
        } 
		
        if (isset($_FILES['advan_image']) && isset($_FILES['advan_image']['tmp_name'])
            && !empty($_FILES['advan_image']['tmp_name'])) {

            $ext = substr($_FILES['advan_image']['name'], strrpos($_FILES['advan_image']['name'], '.') + 1);
            $fileName = md5(uniqid()) . '.' . $ext;

            if (!move_uploaded_file($_FILES['advan_image']['tmp_name'], AnAdvantages::imgDir . $fileName)) {
                return $this->displayError($this->trans('An error occurred while attempting to upload the file.', [], 'Admin.Notifications.Error'));
            }
                    
            if (Configuration::get(an_advantages::PREFIX.'bg_image') !=''){
                @unlink(AnAdvantages::imgDir . Tools::getValue('advan_image'));
            }
            Configuration::updateValue(an_advantages::PREFIX.'bg_image', $fileName);      
                       
        }

        $currentIndex = $this->context->link->getAdminLink('AdminAnAdvantages', false);
        $token = Tools::getAdminTokenLite('AdminAnAdvantages');		
          
        $this->module->exportJsonSettings();

        Tools::redirectAdmin($currentIndex.'&token='.$token.'&conf=4');

		return  true;
    }

    public function validateUpload($file)
    {
        $maxFileSize = 4000000;
        $types = ['gif', 'jpg', 'jpeg', 'jpe', 'png', 'svg'];

        if ((int) $maxFileSize > 0 && $file['size'] > (int) $maxFileSize) {
            return Context::getContext()->getTranslator()->trans('Image is too large (%1$d kB). Maximum allowed: %2$d kB', [$file['size'] / 1024, $maxFileSize / 1024], 'Admin.Notifications.Error');
        }

        if (!ImageManager::isCorrectImageFileExt($file['name'], $types) || preg_match('/\%00/', $file['name'])) {
            return Context::getContext()->getTranslator()->trans('Image format not recognized, allowed formats are: .gif, .jpg, .png, .svg', [], 'Admin.Notifications.Error');
        }  

        if ($file['error']) {
            return Context::getContext()->getTranslator()->trans('Error while uploading image; please change your server\'s settings. (Error code: %s)', [$file['error']], 'Admin.Notifications.Error');
        }   
        
        return false;
    }
     

	public function processSave()
    {
        $isUpdateImage = false;

        if (isset($_FILES['image_file']) && isset($_FILES['image_file']['tmp_name']) && !empty($_FILES['image_file']['tmp_name'])) {
            if ($error = $this->validateUpload($_FILES['image_file'])) {
                $this->errors[] = $error;                 
            }
        }

        if (!empty($this->errors)) {
            $this->display = 'edit';
            return false;
        } 
  
        $object = parent::processSave();
        
        if (isset($object->id) && $object->id) {
            
            $deleteImage = Tools::getValue('image_delete');
            
            if ($deleteImage == 1){
                @unlink(AnAdvantages::imgDir . $object->image);
                    
                $object->image = '';
                    
                $isUpdateImage = true;
            }

            if (isset($_FILES['image_file']) && isset($_FILES['image_file']['tmp_name'])
                && !empty($_FILES['image_file']['tmp_name'])) {

                $ext = substr($_FILES['image_file']['name'], strrpos($_FILES['image_file']['name'], '.') + 1);
                $fileName = md5(uniqid()) . '.' . $ext;

                if (!move_uploaded_file($_FILES['image_file']['tmp_name'], AnAdvantages::imgDir . $fileName)) {
                    return $this->displayError($this->trans('An error occurred while attempting to upload the file.', [], 'Admin.Notifications.Error'));
                }
                    
                if (isset($object->image) && $object->image !=''){
                    @unlink(AnAdvantages::imgDir . $object->image);
                }
                $object->image = $fileName;
                    
                $isUpdateImage = true;
            }

			if ($isUpdateImage){
                $object->save();		
			}   

            AnAdvantages::exportJsonAdvantages();	

            if (Tools::getIsset('submit'.$this->table.'AndStay')) {
                $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).'&conf=4&updatean_advantages&token='.$this->token.'&id_advantage='.$object->id;
            }
            
            return $object;
        }     
    }	
		
    public function ajaxProcessUpdatePositions()
    {
        $status = false;
		$position = 1;
        $positions = array_map('intval', (array)Tools::getValue('positions'));
		
		foreach ($positions as $pos){
			$sql = 'UPDATE `' . _DB_PREFIX_ . 'an_advantages` SET position="'.(int)$position.'" WHERE `id_advantage`="'.(int)$pos.'" ';
			Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql);
			$position++;
		}

		$status = true;

        return $this->setJsonResponse(array(
            'success' => $status,
            'message' => $this->l($status ? 'Blocks reordered successfully' : 'An error occurred')
        ));
    }

    protected function setJsonResponse($response)
    {
        header('Content-Type: application/json; charset=utf8');
        print(json_encode($response));
        exit;
    }	


    protected function updateAssoShop($id_object)
    {
        if (!Shop::isFeatureActive()) {
            return;
        }

        $assos_data = $this->getSelectedAssoShop($this->table, $id_object);

        $exclude_ids = $assos_data;

        foreach (Db::getInstance()->executeS('SELECT id_shop FROM ' . _DB_PREFIX_ . 'shop') as $row) {
            if (!$this->context->employee->hasAuthOnShop($row['id_shop'])) {
                $exclude_ids[] = $row['id_shop'];
            }
        }

        Db::getInstance()->delete($this->table . '_shop', '`' . $this->identifier . '` = ' . (int) $id_object . ($exclude_ids ? ' AND id_shop NOT IN (' . implode(', ', $exclude_ids) . ')' : ''));

        $insert = array();

        foreach ($assos_data as $id_shop) {
            $insert[] = array(
                $this->identifier => $id_object,
                'id_shop' => (int) $id_shop,
            );
        }

        return Db::getInstance()->insert($this->table . '_shop', $insert, false, true, Db::INSERT_IGNORE);
    }

    protected function getSelectedAssoShop($table)
    {
        if (!Shop::isFeatureActive()) {
            return array();
        }

        $shops = Shop::getShops(true, null, true);

        if (count($shops) == 1 && isset($shops[0])) {
            return array($shops[0], 'shop');
        }

        $assos = array();

        if (Tools::isSubmit('checkBoxShopAsso_' . $table)) {
            foreach (Tools::getValue('checkBoxShopAsso_' . $table) as $id_shop => $value) {
                $assos[] = (int) $id_shop;
            }
        } else if (Shop::getTotalShops(false) == 1) {
            // if we do not have the checkBox multishop, we can have an admin with only one shop and being in multishop
            $assos[] = (int) Shop::getContextShopID();
        }

        return $assos;
    }      
}


??

??