AnonSec Shell
Server IP : 54.36.91.62  /  Your IP : 216.73.217.112
Web Server : Apache
System : Linux webm013.cluster127.gra.hosting.ovh.net 5.15.206-ovh-vps-grsec-zfs-classid #1 SMP Fri May 15 02:41:25 UTC 2026 x86_64
User : coopiak ( 151928)
PHP Version : 8.3.23
Disable Function : _dyuweyrj4,_dyuweyrj4r,dl
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /home/coopiak/amisdesseniors-fr/administrator/components/com_djcatalog2/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/coopiak/amisdesseniors-fr/administrator/components/com_djcatalog2/controllers/items.php
<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 *
 */
defined('_JEXEC') or die( 'Restricted access' );
use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Factory;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\MVC\Model\ListModel;
jimport('joomla.application.component.controlleradmin');


class Djcatalog2ControllerItems extends AdminController
{
    static $exclude_columns = array('sections', 'sections_source', 'params');

    public function __construct($config = array())
    {
        parent::__construct($config);
        $this->registerTask('unfeatured',	'featured');
        $this->registerTask('inavailable',	'available');
        $this->registerTask('listing', 'publish');
        $this->registerTask('unlisting', 'publish');
    }

    public function getModel($name = 'Item', $prefix = 'Djcatalog2Model', $config = array())
    {
        $model = parent::getModel($name, $prefix, array('ignore_request' => true));
        return $model;
    }
    function featured()
    {
        // Check for request forgeries
        Session::checkToken() or die(Text::_('JINVALID_TOKEN'));

        $app = Factory::getApplication();

        $session	= Factory::getSession();
        $registry	= $session->get('registry');

        // Get items to publish from the request.
        $cid	= $app->input->get('cid', array(), 'array');
        $task 	= $this->getTask();
        $value = ($task == 'featured') ? 1 : 0;

        if (empty($cid) ) {
            throw new \Exception(Text::_($this->text_prefix.'_NO_ITEM_SELECTED'), 500);
        }
        else {
            // Get the model.
            $model = $this->getModel();

            // Make sure the item ids are integers
            ArrayHelper::toInteger($cid);

            // Publish the items.
            if (!$model->changeFeaturedState($cid, $value)) {
                throw new Joomla\CMS\MVC\View\GenericDataException(implode("\n", $model->getErrors()), 500);
            }
        }
        $extension = $app->input->get('extension', null, 'cmd');
        $extensionURL = ($extension) ? '&extension=' . $app->input->get('extension', null, 'cmd') : '';
        $this->setRedirect(Route::_('index.php?option='.$this->option.'&view='.$this->view_list.$extensionURL, false));
    }

    function available()
    {
        // Check for request forgeries
        Session::checkToken() or die(Text::_('JINVALID_TOKEN'));

        $app = Factory::getApplication();

        $session	= Factory::getSession();
        $registry	= $session->get('registry');

        // Get items to publish from the request.
        $cid	= $app->input->get('cid', array(), 'array');
        $task 	= $this->getTask();
        $value = ($task == 'available') ? 1 : 0;

        if (empty($cid)) {
            throw new Joomla\CMS\MVC\View\GenericDataException(Text::_($this->text_prefix.'_NO_ITEM_SELECTED'), 500);
        }
        else {
            // Get the model.
            $model = $this->getModel();

            // Make sure the item ids are integers
            ArrayHelper::toInteger($cid);

            // Publish the items.
            if (!$model->changeAvailableState($cid, $value)) {
                throw new Joomla\CMS\MVC\View\GenericDataException(implode("\n", $model->getErrors()), 500);
            }
        }
        $extension = $app->input->get('extension', null, 'cmd');
        $extensionURL = ($extension) ? '&extension=' . $app->input->get('extension', null, 'cmd') : '';
        $this->setRedirect(Route::_('index.php?option='.$this->option.'&view='.$this->view_list.$extensionURL, false));
    }

    public function publish()
    {
        // Check for request forgeries
        $this->checkToken();

        // Get items to publish from the request.
        $cid = $this->input->get('cid', array(), 'array');
        $data = array('publish' => 1, 'unpublish' => 0, 'archive' => 2, 'trash' => -2, 'report' => -3, 'listing' => 1, 'unlisting' => 3);
        $task = $this->getTask();
        $value = ArrayHelper::getValue($data, $task, 0, 'int');

        if (empty($cid))
        {
            \Log::add(Text::_($this->text_prefix . '_NO_ITEM_SELECTED'), \Log::WARNING, 'jerror');
        }
        else
        {
            // Get the model.
            $model = $this->getModel();

            // Make sure the item ids are integers
            $cid = ArrayHelper::toInteger($cid);

            // Publish the items.
            try
            {
                $model->publish($cid, $value);
                $errors = $model->getErrors();
                $ntext = null;

                if ($value === 1)
                {
                    if ($errors)
                    {
                        \Factory::getApplication()->enqueueMessage(Text::plural($this->text_prefix . '_N_ITEMS_FAILED_PUBLISHING', count($cid)), 'error');
                    }
                    else
                    {
                        $ntext = $this->text_prefix . '_N_ITEMS_PUBLISHED';
                    }
                }
                elseif ($value === 0)
                {
                    $ntext = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';
                }
                elseif ($value === 2)
                {
                    $ntext = $this->text_prefix . '_N_ITEMS_ARCHIVED';
                }
                else
                {
                    $ntext = $this->text_prefix . '_N_ITEMS_TRASHED';
                }

                if ($ntext !== null)
                {
                    $this->setMessage(Text::plural($ntext, count($cid)));
                }
            }
            catch (\Exception $e)
            {
                $this->setMessage($e->getMessage(), 'error');
            }
        }

        $extension = $this->input->get('extension');
        $extensionURL = $extension ? '&extension=' . $extension : '';
        $this->setRedirect(Route::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $extensionURL, false));
    }

    public function export_selected() {
        // Check for request forgeries
        Session::checkToken() or die(Text::_('JINVALID_TOKEN'));

        $app = Factory::getApplication();

        // Get items to publish from the request.
        $cid	= $app->input->get('cid', array(), 'array');

        if (empty($cid)) {
            throw new Joomla\CMS\MVC\View\GenericDataException(Text::_( 'COM_DJCATALOG2_NO_ITEM_SELECTED' ), 500);
        }
        else {
            return $this->export_filtered($cid);
        }
    }

    public function export_filtered($cid = array()) {

        if (!Session::checkToken('post') && !Session::checkToken('get')) {
            jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
        }
        $app = Factory::getApplication();
        $task 	= $this->getTask();

        $path = JPATH_ROOT.'/media/djcatalog2/export/item';
        if (!Folder::exists($path)) {
            Folder::create($path);
        }

        if (!is_writable($path)) {
            $this->setRedirect( 'index.php?option=com_djcatalog2&view=items', Text::_('COM_DJCATALOG2_FOLDER_NOT_WRITABLE').' '.$path, 'error' );
            return false;
        }

        $enclosure = "\"";
        $separator = ",";
        $newline = PHP_EOL;

        $user = Factory::getUser();
        if (!$user->authorise('core.manage', 'com_djcatalog2')){
            $this->setError(Text::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
            $this->setMessage($this->getError(), 'error');
            $this->setRedirect( 'index.php?option=com_djcatalog2&view=items' );
            return false;
        }

        jimport('joomla.application.component.modellist');

        $model = ListModel::getInstance('Items', 'Djcatalog2Model', array('ignore_request'=>true));

        $state = $model->getState();
        $context = 'com_djcatalog2.items';

        $start = $app->input->get('start', 0);
        $limit = 1000;

        $model->setState('list.select', 'a.*, c.name as category_name, p.name as producer_name, uc.name AS author');
        if ($task == 'export_selected' && count($cid) > 0) {
            $limit = $start = 0;
            ArrayHelper::toInteger($cid);
            $model->setState('filter.ids', implode(',',$cid));
        } else {
            $search = $model->getUserStateFromRequest($context.'.filter.search', 'filter_search');
            $model->setState('filter.search', $search);

            $published = $model->getUserStateFromRequest($context.'.filter.published', 'filter_published', '');
            $model->setState('filter.published', $published);

            $category = $model->getUserStateFromRequest($context.'.filter.category', 'filter_category', '');
            $model->setState('filter.category', $category);

            $producer = $model->getUserStateFromRequest($context.'.filter.producer', 'filter_producer', '');
            $model->setState('filter.producer', $producer);
        }

        $model->setState('list.start', $start);
        $model->setState('list.limit', $limit);

        $params = ComponentHelper::getParams('com_djcatalog2');
        $model->setState('params', $params);

        $items = $model->getItems();

        $db = Factory::getDbo();
        $db->setQuery('SHOW COLUMNS FROM #__djc2_items');
        $columns = $db->loadColumn(0);
        $columns = array_merge($columns, array('category_name', 'producer_name', 'author'));


        foreach($columns as $key => $column) {
            if (in_array($column, static::$exclude_columns)) {
                unset($columns[$key]);
            }
        }

        if (true) {
            $db->setQuery('SELECT concat("_", alias) FROM #__djc2_items_extra_fields ORDER BY group_id asc, ordering asc');
            $e_fields = $db->loadColumn();
            $columns = array_merge($columns, $e_fields);
        }

        $filename = $app->input->get('export_file', 'product-export-'.date("Y-m-d_H-i-s").'.csv', 'raw');

        $fp = fopen($path.'/'.$filename, 'a');
        if (!empty($columns) && (!$start || $start == 0)) {
            fputcsv($fp, $columns, $separator, $enclosure);
        }

        foreach ($items as $id => $item) {

            $itemRow = array();

            foreach($columns as $colname) {

                if (!empty($items[$id]->$colname)) {
                    if (is_array($items[$id]->$colname)) {
                        $items[$id]->$colname = implode(', ',$items[$id]->$colname);
                    }
                    $itemRow[$colname] = $items[$id]->$colname;
                }

                if (!isset($itemRow[$colname])) {
                    $itemRow[$colname] = '';
                }
            }

            fputcsv($fp, $itemRow, $separator, $enclosure);
        }

        fclose($fp);

        $pagination = $model->getPagination();

        $total = $pagination->pagesTotal;
        $current = $pagination->pagesCurrent;

        if ($total > $current) {
            header("refresh: 0; url=".JURI::base().'index.php?option=com_djcatalog2&task=items.export_filtered&start='.($start+=$limit).'&export_file='.$filename.'&'.Session::getFormToken().'=1');
            echo '<p>'.$current.' / '.$total.'</p>';
        } else {
            //header("refresh: 0; url=".JURI::base().'index.php?option=com_djcatalog2&view=items');
            $file_link = '<a href="'.Route::_('index.php?option=com_djcatalog2&task=download_file&path='.base64_encode('media/djcatalog2/export/item/'.$filename)).'">'.$filename.'</a>';
            $this->setRedirect( 'index.php?option=com_djcatalog2&view=items', Text::_('COM_DJCATALOG2_EXPORT_SUCCESFULL').' '.$file_link );
        }

        return true;
    }
    public function import($importWithAttributes = false, $importWithCombinations = false) {
        if (!Session::checkToken('post') && !Session::checkToken('get')) {
            jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
        }


        require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/helpers/import.php');

        $app = Factory::getApplication();
        $model = $this->getModel('item');
        $files = $app->input->files;
        $db = Factory::getDbo();
        $user = Factory::getUser();
        $date = Factory::getDate();


        $file = $files->get('csvfile');

        $enclosure = ($app->input->get('enclosure', 0) == 0) ? "\"" : "'";
        $separator = ($app->input->get('separator', 0) == 0) ? "," : ";";

        $defaults = array();
        $defaults['cat_id'] = (int)$app->input->get('cat_id', 0);
        $defaults['producer_id'] = (int)$app->input->get('producer_id', 0);
        $defaults['group_id'] = (int)$app->input->get('group_id', 0);
        $defaults['price'] = $app->input->get('price', 0.0);
        $defaults['special_price'] = $app->input->get('special_price', 0.0);
        $defaults['published'] = $app->input->get('published', 0);
        $defaults['created_by'] = $app->input->get('created_by', $user->id);
        $defaults['created'] = $app->input->getString('created',  $date->toSql());

        $query = $db->getQuery(true)
            ->select('id')
            ->from($db->quoteName('#__viewlevels') . ' AS a')
            ->group('a.id, a.title, a.ordering')
            ->order('a.ordering ASC');

        $db->setQuery($query);
        $defaultAccess = $db->loadResult();
        $defaults['access'] = $app->input->get('access', $defaultAccess);

        if ($defaults['cat_id'] > 0) {
            $db->setQuery('select count(*) from #__djc2_categories where id ='. $defaults['cat_id']);
            $result = (bool)$db->loadResult();
            if ($result == false ){
                $defaults['cat_id'] = 0;
            }
        }
        if ($defaults['producer_id'] > 0) {
            $db->setQuery('select count(*) from #__djc2_producers where id ='. $defaults['producer_id']);
            $result = (bool)$db->loadResult();
            if ($result == false ){
                $defaults['producer_id'] = 0;
            }
        }
        if ($defaults['group_id'] > 0) {
            $db->setQuery('select count(*) from #__djc2_items_extra_fields_groups where id ='. $defaults['group_id']);
            $result = (bool)$db->loadResult();
            if ($result == false ){
                $defaults['group_id'] = 0;
            }
        }

        $messages = array();

        if(!empty($file)) {
            if(!$file['error']) {
                $tempname = $file['tmp_name'];

                if (mb_check_encoding(file_get_contents($file['tmp_name']), 'UTF-8') == false) {
                    $this->setRedirect(Route::_('index.php?option=com_djcatalog2&view=import', false), Text::_('COM_DJCATALOG2_ERROR_INVALID_ENCODING'), 'error');
                    return false;
                }

                $rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);
                if (!empty($rows)) {
                    $messages = Djcatalog2ImportHelper::storeRecords($rows, $model, 'item', $defaults, $importWithAttributes);
                    if($importWithAttributes){
                        Djcatalog2ImportHelper::storeAttributes($rows, $model, 'item', $defaults);
                    }
                }
            }
        }

        foreach($messages as $type => $arr) {
            if (!empty($arr) && is_array($arr)){
                foreach($arr as $message) {
                    $app->enqueueMessage($message, $type);
                }
            }
        }


        $this->setRedirect(Route::_('index.php?option=com_djcatalog2&view=import', false));
        return true;
    }

    function geocode()
    {
        // Check for request forgeries
        Session::checkToken() or die(Text::_('JINVALID_TOKEN'));

        $app = Factory::getApplication();

        $session	= Factory::getSession();
        $registry	= $session->get('registry');

        // Get items to publish from the request.
        $cid	= $app->input->get('cid', array(), 'array');
        $task 	= $this->getTask();

        if (empty($cid)) {
            throw new Joomla\CMS\MVC\View\GenericDataException(Text::_( 'COM_DJCATALOG2_NO_ITEM_SELECTED' ), 500);
        }
        else {
            // Get the model.
            $model = $this->getModel();

            // Make sure the item ids are integers
            ArrayHelper::toInteger($cid);

            // Publish the items.
            if (!$model->geocode($cid)) {
                throw new Joomla\CMS\MVC\View\GenericDataException(implode("\n", $model->getErrors()), 500);
            }
        }
        $extension = $app->input->get('extension', null, 'cmd');
        $extensionURL = ($extension) ? '&extension=' . $app->input->get('extension', null, 'cmd') : '';
        $this->setRedirect(Route::_('index.php?option='.$this->option.'&view='.$this->view_list.$extensionURL, false));
    }

    /*
    public function geocode() {
        if (!Session::checkToken('post') && !Session::checkToken('get')) {
            jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
        }

        $app = Factory::getApplication();
        $model = $this->getModel();
        $db = Factory::getDbo();

        $limit = 2;

        $db->setQuery('select id from #__djc2_items where latitude = 0.000000000000000 OR longitude = 0.000000000000000 OR latitude IS NULL or longitude is NULL order by id asc');
        $items = $db->loadColumn();

        if (count($items) == 0) {
            $this->setRedirect( 'index.php?option=com_djcatalog2&view=items', Text::_('COM_DJCATALOG2_GEOCODE_COMPLETE'));
            return true;
        }

        $messages = array('message'=>array(), 'error'=>array());

        if (count($items) < $limit) {
            $limit = count($items);
        }

        for ($i = 0; $i < $limit; $i++) {
            $row = $model->getItem($items[$i]);
            usleep(150000);
            if (!$model->geocode($row)) {
                $messages['error'][] = Text::_('COM_DJCATALOG2_GEOCODE_ERROR_ROW').': ['.$items[$i].'] '.$model->getError();
                continue;
            }
        }

        $db->setQuery('select count(*) from #__djc2_items where latitude = 0.000000000000000 OR longitude = 0.000000000000000 OR latitude IS NULL or longitude is NULL ');
        $left = $db->loadResult();

        $messages['message'][] = Text::sprintf('COM_DJCATALOG2_GEOCODE_ITEMS_LEFT', $left);

        foreach($messages as $type => $arr) {
            if (!empty($arr)){
                foreach($arr as $message) {
                    $app->enqueueMessage($message, $type);
                }
            }
        }

        $this->setRedirect( 'index.php?option=com_djcatalog2&view=items');
        return true;
    } */

    public function set_prices() {
        // Check for request forgeries
        Session::checkToken() or die(Text::_('JINVALID_TOKEN'));
        $app = Factory::getApplication();
        $db = Factory::getDbo();
        $user = Factory::getUser();

        if (!$user->authorise('djcatalog2.admin.prices', 'com_djcatalog2') && !$user->authorise('djcatalog2.admin.catalogue'))
        {
            throw new NotAllowed(Text::_('JERROR_ALERTNOAUTHOR'), 403);
        }

        $prices = $app->input->get('djc_prices', array(), 'array');
        $target = $app->input->get('target', 'items');

        if ($target != 'items' && $target != 'combinations') {
            $this->setRedirect( 'index.php?option=com_djcatalog2&view=prices');
            return true;
        }

        $rows = array();

        if (!empty($prices)) {
            foreach ($prices as $item_id => $price) {
                $row = new stdClass();

                $row->price = floatval($price['new']);
                $row->stock = $price['stock'];
                if (isset($price['onstock'])) {
                    $row->onstock = $price['onstock'];
                }

                $row->length = $price['length'];
                $row->width = $price['width'];
                $row->height = $price['height'];
                if (isset($price['dimensions_unit'])) {
                    $row->dimensions_unit = $price['dimensions_unit'];
                }

                $row->weight = $price['weight'];
                if (isset($price['weight_unit'])) {
                    $row->weight_unit = $price['weight_unit'];
                }

                $row->id = $item_id;
                $row->available = $price['available'];

                $rows[] = $row;
            }
        }

	    $group = $app->input->get('filter', array(),"ARRAY");
	    $group = (int)$group['customergroup'];
        if (!empty($rows)) {
            foreach ($rows as $item) {
                if ($group  > 0) {
                    if ($target == 'items') {
                        $db->setQuery('select id from #__djc2_prices where item_id='.$item->id.' and group_id ='.$group);
                    } else if ($target == 'combinations') {
                        $db->setQuery('select id from #__djc2_combination_prices where combination_id='.$item->id.' and group_id ='.$group);
                    }

                    $price_id = $db->loadResult();
                    $price_item = new stdClass();
                    $price_item->id = $price_id;

                    if ($target == 'items') {
                        $price_item->item_id = $item->id;
                    } else if ($target == 'combinations') {
                        $price_item->combination_id = $item->id;
                    }

                    $price_item->group_id = $group;
                    $price_item->price = $item->price;
                    $price_item->available = $item->available;

                    $objName = '#__djc2_prices';
                    if ($target == 'combinations') {
                        $objName = '#__djc2_combination_prices';
                    }

                    if ($price_id > 0) {
                        if (!$db->updateObject($objName, $price_item, 'id', false)) {
                            $app->enqueueMessage($db->getErrorMsg(), 'error');
                        }
                    } else {
                        if (!$db->insertObject($objName, $price_item)) {
                            $app->enqueueMessage($db->getErrorMsg(), 'error');
                        }
                    }
                } else {
                    $objName = '#__djc2_items';
                    if ($target == 'combinations') {
                        unset($row->available);
                        $objName = '#__djc2_items_combinations';
                    } else {
                        if ($row->available == -1) {
                            unset($row->available);
                        }
                    }

                    if (!$db->updateObject($objName, $item, 'id', false)) {
                        $app->enqueueMessage($db->getErrorMsg(), 'error');
                    }
                }
            }
        }

        $this->setRedirect( 'index.php?option=com_djcatalog2&view=prices', Text::_('COM_DJCATALOG2_PRICES_UPDATED'));

        return true;
    }

    public function import_prices() {
        if (!Session::checkToken('post') && !Session::checkToken('get')) {
            jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
        }

        $user = Factory::getUser();
        if (!$user->authorise('djcatalog2.admin.prices', 'com_djcatalog2') && !$user->authorise('djcatalog2.admin.catalogue'))
        {
            throw new NotAllowed(Text::_('JERROR_ALERTNOAUTHOR'), 403);
        }

        require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/helpers/import.php');

        $app = Factory::getApplication();
        $model = $this->getModel('item');
        $files = $app->input->files;
        $db = Factory::getDbo();
        $user = Factory::getUser();
        $date = Factory::getDate();


        $file = $files->get('csvfile');

        $enclosure = ($app->input->get('enclosure', 0) == 0) ? "\"" : "'";
        $separator = ($app->input->get('separator', 0) == 0) ? "," : ";";

        $defaults = array();
        $defaults['group_id'] = (int)$app->input->get('group_id', 0);

        if ($defaults['group_id'] > 0) {
            $db->setQuery('select count(*) from #__djc2_customer_groups where id ='. $defaults['group_id']);
            $result = (bool)$db->loadResult();
            if ($result == false ){
                $defaults['group_id'] = 0;
            }
        }

        $inserted = 0;
        $updated = 0;
        $ignored = 0;
        $failed = 0;

        $messages = array('info'=>array(), 'warning' => array(), 'error'=>array());

        if(!empty($file)) {
            if(!$file['error']) {
                $tempname = $file['tmp_name'];

                if (mb_check_encoding(file_get_contents($file['tmp_name']), 'UTF-8') == false) {
                    $this->setRedirect(Route::_('index.php?option=com_djcatalog2&view=import', false), Text::_('COM_DJCATALOG2_ERROR_INVALID_ENCODING'), 'error');
                    return false;
                }

                $rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);
                $prices = array();
                foreach ($rows as $row) {
                    if (empty($row['sku']) ) {
                        $ignored++;
                        continue;
                    }
                    if (!isset($row['group_id']) || (int)$row['group_id'] == 0) {
                        $row['group_id'] = $defaults['group_id'];
                    }

                    $row['price'] = floatval(str_replace(',', '.', $row['price']));

                    $item_ids = array();
                    if (!empty($row['sku'])) {
                        $db->setQuery('select id from #__djc2_items WHERE sku LIKE '.$db->quote(trim((string)$row['sku'])));
                        $item_ids = $db->loadColumn();
                    } else if (!empty($row['id'])) {
                        $item_ids[] = $row['id'];
                    }

                    if (count($item_ids)) {
                        foreach($item_ids as $item_id) {
                            $prices[] = array('item_id' => $item_id, 'group_id' => $row['group_id'], 'price' => $row['price']);
                        }
                    } else {
                        $ignored++;
                    }
                }

                if (!empty($prices)) {
                    foreach($prices as $row) {
                        if (!isset($row['price'])) {
                            continue;
                        }

                        if ($row['group_id'] == 0) {
                            // UPDATE djc2_items table
                            $db->setQuery('UPDATE #__djc2_items SET price='.$row['price'].' WHERE id='.$row['item_id']);
                            if ($db->execute()){
                                $updated++;
                            } else {
                                $failed++;
                            }
                        } else {
                            // UPDATE djc2_prices table
                            $db->setQuery('SELECT * FROM #__djc2_prices WHERE group_id='.$row['group_id'] .' AND item_id='.$row['item_id']);
                            $price_row = $db->loadObject();
                            if ($price_row) {
                                if ($price_row->price == $row['price']) {
                                    $ignored++;
                                    continue;
                                }
                                $row['id'] = $price_row->id;
                            } else {
                                $row['id'] = 0;
                            }

                            $obj = ArrayHelper::toObject($row);
                            if ($obj->id > 0) {
                                if ($db->updateObject('#__djc2_prices', $obj, 'id', false)) {
                                    $updated++;
                                } else {
                                    $failed++;
                                }
                            } else {
                                if($db->insertObject( '#__djc2_prices', $obj, 'id')){
                                    $inserted++;
                                } else {
                                    $failed++;
                                }
                            }
                        }

                    }
                }
            }
        }

        $messages['info'][] = Text::_('COM_DJCATALOG2_IMPORT_INSERTED').': '.$inserted;
        $messages['info'][] = Text::_('COM_DJCATALOG2_IMPORT_UPDATED').': '.$updated;

        if ($ignored > 0) {
            $messages['warning'][] = Text::_('COM_DJCATALOG2_IMPORT_IGNORED').': '.$ignored;
        }
        if ($failed > 0) {
            $messages['error'][] = Text::_('COM_DJCATALOG2_IMPORT_FAILED').': '.$failed;
        }

        foreach($messages as $type => $arr) {
            if (!empty($arr)){
                foreach($arr as $message) {
                    $app->enqueueMessage($message, $type);
                }
            }
        }

        $this->setRedirect(Route::_('index.php?option=com_djcatalog2&view=import', false));
        return true;
    }

    public function import_with_attributes(){
        self::import(true);
        return true;
    }

    public function import_with_combinations(){
        require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/helpers/import.php');

        $app = Factory::getApplication();
        $model = $this->getModel('item');
        $files = $app->input->files;
        $file = $files->get('csvfile');
        $tempname = $file['tmp_name'];
        $enclosure = ($app->input->get('enclosure', 0) == 0) ? "\"" : "'";
        $separator = ($app->input->get('separator', 0) == 0) ? "," : ";";


        $rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);


        Djcatalog2ImportHelper::storeCombinations($rows,$model,'item');
        $this->setRedirect(Route::_('index.php?option=com_djcatalog2&view=import', false));
        return true;
    }


	// Price rules importer - price_rule_id, sku of product are necessary.
	public function import_with_pricerules(){
		$app = Factory::getApplication();
		$model = $this->getModel('item');
		$files = $app->input->files;
		$file = $files->get('csvfile');
		$tempname = $file['tmp_name'];
		$enclosure = ($app->input->get('enclosure', 0) == 0) ? "\"" : "'";
		$separator = ($app->input->get('separator', 0) == 0) ? "," : ";";
		$clear = $app->input->get('import_clear', false);



		require_once(JPATH_ROOT . '/administrator/components/com_djcatalog2/helpers/import.php');
		$rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);



		$productIdsToUpdate = [];
		$messages = [];
		foreach ($rows as $row) {
			$productSKU = $row['sku'];
			$priceRuleId = $row['price_rule_id'];

			// Get the database connection
			$db = Factory::getDbo();

			// Step 1: Get product by SKU
			$query = $db->getQuery(true);
			$query->select('*')
				->from($db->quoteName('#__djc2_items'))
				->where($db->quoteName('sku') . ' = ' . $db->quote($productSKU));
			$db->setQuery($query);
			$product = $db->loadObject();

			if ($product) {
				$productID = $product->id;


				if($clear === "on"){
					//Clear item from pricerules
					$query = $db->getQuery(true);
					$query->select('*')
						->from($db->quoteName('#__djc2_price_rules'));
					$db->setQuery($query);
					$priceRules = $db->loadObjectList();

					foreach ($priceRules as $priceR){
						$decodedProductIds = json_decode($priceR->product_id);
						if(!empty($decodedProductIds))
							if(in_array($productID,$decodedProductIds)){
								// Clear the product id from the price rule
								$decodedProductIds = array_diff($decodedProductIds, [$productID]);

								// Re-encode the array back to JSON
								$updatedProductIds = json_encode(array_values($decodedProductIds)); // Re-indexing the array

								// Update the database with the modified product_id
								$query = $db->getQuery(true)
									->update($db->quoteName('#__djc2_price_rules'))
									->set($db->quoteName('product_id') . ' = ' . $db->quote($updatedProductIds))
									->where($db->quoteName('id') . ' = ' . $db->quote($priceR->id));
								$db->setQuery($query);
								$db->execute();
							}
					}
				}

				// Step 2: Fetch the price rule by price_rule_id, only once (when first encountering a price rule)
				if (!isset($productIdsToUpdate[$priceRuleId])) {
					$query = $db->getQuery(true);
					$query->select('*')
						->from($db->quoteName('#__djc2_price_rules'))
						->where($db->quoteName('id') . ' = ' . $db->quote($priceRuleId)); // Ensure you're updating the correct row
					$db->setQuery($query);
					$priceRule = $db->loadObject();

					if ($priceRule) {
						// Step 3: If the price rule exists, initialize the array for this price_rule_id
						// Clear the `product_id` for this rule at the first encounter
						$query = $db->getQuery(true);
						$fields = array(
							$db->quoteName('product_id') . ' = ' . $db->quote(json_encode([])) // Clear the column (empty array)
						);
						$conditions = array(
							$db->quoteName('id') . ' = ' . $db->quote($priceRuleId)
						);
						$query->update($db->quoteName('#__djc2_price_rules'))->set($fields)->where($conditions);
						$db->setQuery($query);
						$db->execute();

						echo 'Cleared product_id for price rule ' . $priceRuleId . '<br>';

						// Initialize the array for this price_rule_id
						$productIdsToUpdate[$priceRuleId] = [];
					} else {
						echo 'Price rule not found with ID: ' . $priceRuleId . '<br>';
						continue;
					}
				}

				// Step 4: Accumulate product IDs under the correct price_rule_id
				if (!in_array($productID, $productIdsToUpdate[$priceRuleId])) {
					$productIdsToUpdate[$priceRuleId][] = $productID;
				}

			} else {
				echo 'Product not found with SKU: ' . $productSKU . '<br>';
			}
		}

		foreach ($productIdsToUpdate as $priceRuleId => $productIds) {
			// Encode the array into JSON format
			$newProductIdsJson = json_encode($productIds);

			// Update the price rule with the accumulated product IDs
			$query = $db->getQuery(true);
			$fields = array(
				$db->quoteName('product_id') . ' = ' . $db->quote($newProductIdsJson)
			);
			$conditions = array(
				$db->quoteName('id') . ' = ' . $db->quote($priceRuleId)
			);
			$query->update($db->quoteName('#__djc2_price_rules'))->set($fields)->where($conditions);

			// Execute the update query
			$db->setQuery($query);
			$db->execute();

			$messages['info'][] = Text::_('COM_DJCATALOG2_IMPORT_UPDATED').': '.'Products:'.implode(',',$productIds).' are inserted to the price rule with id '.$priceRuleId;


		}

		foreach($messages as $type => $arr) {
			if (!empty($arr)){
				foreach($arr as $message) {
					$app->enqueueMessage($message, $type);
				}
			}
		}
		$this->setRedirect(Route::_('index.php?option=com_djcatalog2&view=import', false));
		return true;
	}
}

Anon7 - 2022
AnonSec Team