| 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/nice/administrator/components/com_djcatalog2/helpers/ |
Upload File : |
<?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();
use Joomla\CMS\Factory;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Filesystem\Path;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\Filesystem\File;
class Djcatalog2ImportHelper
{
static $countries = array();
static $states = array();
static $translations = false;
static $translationsQueries = array();
public static function parseCSV($filename, $separator = ",", $enclosure = "\"")
{
$rows = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
$headers = fgetcsv($handle, 0, $separator, $enclosure);
if ($headers !== FALSE) {
while (($data = fgetcsv($handle, 0, $separator, $enclosure)) !== false) {
$row = array();
for ($i = 0; $i < count($headers); $i++) {
if (array_key_exists($i, $data)) {
$row[trim($headers[$i])] = trim((string)$data[$i]);
}
}
$rows[] = $row;
}
}
fclose($handle);
}
return $rows;
}
public static function storeRecords($rows, $model, $type, $defaults = array(), $settingAttributes = false)
{
$db = Factory::getDbo();
$params = ComponentHelper::getParams('com_djcatalog2');
$img_import_source = Path::clean(JPATH_ROOT . $params->get('import_images_path', '/media/djcatalog2/import/images'));
$att_import_source = Path::clean(JPATH_ROOT . $params->get('import_files_path', '/media/djcatalog2/import/files'));
$inserted = 0;
$updated = 0;
$ignored = 0;
$failed = 0;
$messages = array('message' => array(), 'warning' => array(), 'error' => array());
$messages['message'][] = Text::_('COM_DJCATALOG2_IMPORT_SUMMARY_' . strtoupper($type));
$table_name = false;
switch ($type) {
case 'item' :
$table_name = '#__djc2_items';
break;
case 'category' :
$table_name = '#__djc2_categories';
break;
case 'producer' :
$table_name = '#__djc2_producers';
break;
}
$basic_columns = $db->getTableColumns($table_name, true);
$extra_fields = ($type == 'item') ? self::getExtraFields() : false;
$app = Factory::getApplication();
$limit = $app->input->getInt('import_limit', 200);
$limit_start = $app->input->getInt('import_start', 0);
$total = count($rows);
$rows = array_slice($rows, $limit_start, $limit, true);
foreach ($rows as $key => $row) {
// By default, initially, each record is considered as new
$new = true;
// If ID has been supplied and is greater than 0,
// let's load it first into $old_row variable
$old_row = null;
if ($type == 'item') {
self::prepareCustomConfigValues($row);
}
if (isset($row['id']) && (int)$row['id'] > 0) {
$old_row = $model->getItem($row['id']);
}
// If the record exists in DB,
// fill-in any missing data in CSV record
if (!empty($old_row) && $old_row->id > 0) {
$new = false;
foreach ($old_row as $k => $v) {
if (!isset($row[$k])) {
$row[$k] = $v;
}
}
} else if (isset($row['id']) && (int)$row['id'] > 0) {
//$new = true;
// TODO: this should be handled by Table object, but AdminModel::save() returns true even if record hasn't been stored in DB
// dummy insert
$db->setQuery("set @@sql_mode = ''");
$db->execute();
$db->setQuery('INSERT INTO ' . $table_name . ' (id) VALUES (' . (int)$row['id'] . ')');
$db->execute();
} else {
$row['id'] = 0;
$row['alias'] = !isset($row['alias']) ? null : $row['alias'];
}
if (empty($row['name'])) {
$ignored++;
continue;
}
foreach ($defaults as $column => $value) {
if (!isset($row[$column])) {
$row[$column] = trim((string)$value);
}
}
$img_list = null;
if (isset($row['images'])) {
$img_list = explode(',', $row['images']);
unset($row['images']);
}
$att_list = null;
if (isset($row['files'])) {
$att_list = explode(',', $row['files']);
unset($row['files']);
}
// establish custom fields when importing products
if ($type == 'item') {
Factory::getApplication()->input->set('jform', null);
$jform = array();
if ($extra_fields && count($extra_fields)) {
Factory::getApplication()->input->set('attribute', null);
$attributes = self::prepareExtraFieldsValues($row, $extra_fields);
if (!empty($attributes)) {
Factory::getApplication()->input->set('attribute', $attributes);
}
}
if (isset($row['group_id'])) {
$group_ids = false;
if (is_array($row['group_id'])) {
$group_ids = $row['group_id'];
} else {
$group_ids = array($row['group_id']);
}
$jform['group_id'] = $group_ids;
}
/*
if (isset($row['country']) && !empty($row['country'])) {
if (!(is_numeric($row['country']) && floatval($row['country']) == intval(floatval($row['country'])))) {
$row['country'] = self::getCountryByName($row['country']);
}
}
$country_id = !empty($row['country']) ? $row['country'] : 0;
if (isset($row['state']) && !empty($row['state'])) {
if (!(is_numeric($row['state']) && floatval($row['state']) == intval(floatval($row['state'])))) {
$row['state'] = self::getStateByName($row['state'], $country_id);
}
}*/
Factory::getApplication()->input->set('jform', $jform);
}
// remove unnecessary attributes from the record
foreach ($row as $k => $v) {
if (array_key_exists($k, $basic_columns) == false) {
unset($row[$k]);
}
}
if (!$model->save($row)) {
$messages['error'][] = Text::_('COM_DJCATALOG2_IMPORT_ERROR_ROW') . ': [' . ($key + 1) . ', ' . $row['name'] . ']. ' . $model->getError();
$failed++;
continue;
}
$last_id = $model->getState($model->getName() . '.id');
if ($last_id > 0) {
if (!empty($img_list)) {
self::storeMedias($last_id, $type, $img_list, $img_import_source, DJCATIMGFOLDER, '#__djc2_images', $defaults);
}
if (!empty($att_list)) {
self::storeMedias($last_id, $type, $att_list, $att_import_source, DJCATATTFOLDER, '#__djc2_files', $defaults);
}
}
if ($new) {
$inserted++;
} else {
$updated++;
}
}
Factory::getApplication()->input->set('attribute', null);
Factory::getApplication()->input->set('jform', null);
$messages['message'][] = Text::sprintf('COM_DJCATALOG2_IMPORT_ROWS', $limit, $limit_start, count($rows), $total);
$messages['message'][] = Text::_('COM_DJCATALOG2_IMPORT_INSERTED') . $inserted;
$messages['message'][] = 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;
}
return $messages;
}
public static function storeMedias($item_id, $type, $files, $source_path, $target_path, $table_name, $defaults)
{
$db = Factory::getDbo();
$destination = DJCatalog2FileHelper::getDestinationFolder($target_path, $item_id, $type);
$sub_path = DJCatalog2FileHelper::getDestinationPath($item_id, $type);
if (!Folder::exists($destination)) {
$destExist = Folder::create($destination, 0755);
} else {
$destExist = true;
}
if ($destExist && !empty($files)) {
$ordering = 1;
foreach ($files as $file) {
$file = trim((string)$file);
if ($file && File::exists($source_path . '/' . $file)) {
$obj = new stdClass();
$obj->id = null;
$obj->fullname = DJCatalog2FileHelper::createFileName($file, $destination);
$obj->name = File::stripExt($obj->fullname);
$obj->ext = File::getExt($obj->fullname);
$obj->item_id = $item_id;
$obj->path = $sub_path;
$obj->fullpath = $sub_path . '/' . $obj->fullname;
$obj->type = $type;
$obj->caption = File::stripExt($file);
$obj->ordering = $ordering++;
if ($table_name == '#__djc2_files') {
$obj->access = $defaults['access'];
}
if (File::copy($source_path . '/' . $file, $destination . '/' . $obj->fullname)) {
$db->insertObject($table_name, $obj, 'id');
}
}
}
}
}
public static function getExtraFields()
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('f.*, f.alias as field_column');
$query->from('#__djc2_items_extra_fields AS f');
$query->order('f.group_id asc, f.ordering asc');
//echo str_replace('#_', 'jos', (string)$query);die();
$db->setQuery($query);
$fields = ($db->loadObjectList('field_column'));
if (count($fields)) {
$db->setQuery('SELECT * FROM #__djc2_items_extra_fields_options ORDER BY field_id ASC, ordering ASC');
$optionList = $db->loadObjectList();
foreach ($fields as $field_column => $field) {
$field_id = $field->id;
foreach ($optionList as $optionRow) {
if ($optionRow->field_id == $field_id) {
if (empty($field->optionlist)) {
$fields[$field_column]->optionlist = array();
}
$fields[$field_column]->optionlist[] = $optionRow;
}
}
}
return $fields;
}
return false;
}
public static function prepareExtraFieldsValues(&$item, &$fields)
{
$values = array();
foreach ($fields as $colname => $field) {
if (isset($item[$colname])) {
if (trim((string)$item[$colname]) !== '') {
if (!isset($item['group_id']) || !is_array($item['group_id'])) {
$current = isset($item['group_id']) ? $item['group_id'] : false;
$item['group_id'] = array();
if ($current) {
$item['group_id'][] = $current;
}
}
$item['group_id'][] = $field->group_id;
if (empty($field->optionlist)) {
// assuming that it's not select/radio/checkbox field
$values[$field->id] = $item[$colname];
} else {
// it must be select/radio/checkbox field
$option_values = array();
$option_names = explode(',', $item[$colname]);
foreach ($option_names as $k => $v) {
$option_value = trim((string)$v);
foreach ($field->optionlist as $option_key => $option) {
if (\Joomla\String\StringHelper::strtolower((string)$option_value) == \Joomla\String\StringHelper::strtolower(trim((string)$option->value))) {
$option_values[] = (int)$option->id;
}
}
}
// try by checking option ids
if (empty($option_values)) {
foreach ($option_names as $k => $v) {
$option_value = trim((string)$v);
foreach ($field->optionlist as $option_key => $option) {
if (is_numeric($option_value) && $option_value == $option->id) {
$option_values[] = (int)$option->id;
}
}
}
}
$option_values = array_unique($option_values);
$values[$field->id] = $option_values;
}
} else {
$values[$field->id] = null;
}
unset($item[$colname]);
} else {
// $values[$field->id] = '__{{UNSET}}__';
}
}
if (is_array($item['group_id'])) {
$item['group_id'] = array_unique($item['group_id']);
}
return $values;
}
public static function prepareCustomConfigValues(&$row)
{
$db = Factory::getDbo();
if (self::$translations === false) {
$query = $db->getQuery(true);
$query->select('*')->from('#__djc2_import_configs')->where('published=1')->order('ordering asc');
$db->setQuery($query);
self::$translations = $db->loadObjectList();
}
if (empty(self::$translations)) {
return;
}
foreach (self::$translations as $translation) {
$k = trim((string)$translation->csv_name);
$v = trim((string)$translation->target_name);
if (isset($row[$k])) {
$value = $row[$k];
if ($translation->is_db == 1 && trim((string)$value) != '') {
if (empty($translation->db_name) || empty($translation->db_lookup_column) || empty($translation->db_value_column)) {
continue;
}
try {
$query = $db->getQuery(true);
//$query->select($db->quoteName(trim((string)$translation->db_lookup_column)));
$query->select($db->quoteName(trim((string)$translation->db_value_column)));
$query->from(trim((string)$translation->db_name));
$operator = $translation->db_operator;
if (!$operator) {
$query->where($db->quoteName(trim((string)$translation->db_lookup_column)) . ' = ' . $value);
} else if ($operator == '1') {
$query->where($db->quoteName(trim((string)$translation->db_lookup_column)) . ' LIKE ' . $db->quote($value));
} else if ($operator == '2') {
$query->where($db->quoteName(trim((string)$translation->db_lookup_column)) . ' LIKE ' . $db->quote('%' . $value));
} else if ($operator == '3') {
$query->where($db->quoteName(trim((string)$translation->db_lookup_column)) . ' LIKE ' . $db->quote('%' . $value . '%'));
}
if ($translation->db_where_clause != '') {
$query->where($translation->db_where_clause);
}
$query_hash = md5((string)$query);
if (isset(self::$translationsQueries[$query_hash])) {
$value = self::$translationsQueries[$query_hash];
} else {
$db->setQuery($query);
$value = self::$translationsQueries[$query_hash] = $db->loadResult();
}
} catch (Exception $e) {
continue;
}
}
if ($translation->html_wrapper != '') {
$value = '<' . $translation->html_wrapper . '>' . $value . '</' . $translation->html_wrapper . '>';
}
if ($translation->merging != 'R' && !empty($row[$v])) {
if ($translation->merging == 'B') {
$value = (empty($row[$v])) ? $value : $value . ' ' . $row[$v];
} else if ($translation->merging == 'A') {
$value = (empty($row[$v])) ? $value : $row[$v] . ' ' . $value;
}
}
$row[$v] = $value;
//unset($row[$k]);
}
}
}
public static function getCountryByName($name)
{
if (empty($name)) {
return false;
}
$name = \Joomla\String\StringHelper::strtolower(\Joomla\String\StringHelper::trim((string)$name));
if (empty(self::$countries)) {
$db = Factory::getDbo();
$db->setQuery('select country_name, id from #__djc2_countries order by country_name asc');
self::$countries = $db->loadObjectList('country_name');
}
if (isset(self::$countries[$name])) {
return self::$countries[$name]->id;
}
$db->setQuery('select lower(country_name) as country_name, id from #__djc2_countries where lower(country_name) like' . $db->quote('%' . $db->escape($name) . '%') . ' LIMIT 1');
$result = $db->loadObject();
if (!empty($result)) {
self::$countries[$name] = $result;
return self::$countries[$name]->id;
}
return false;
}
public static function getStateByName($name, $country_id = 0)
{
if (empty($name)) {
return false;
}
$name = \Joomla\String\StringHelper::strtolower(\Joomla\String\StringHelper::trim((string)$name));
$where = ((int)$country_id > 0) ? ' country_id=' . (int)$country_id . ' ' : ' 1 ';
if (empty(self::$states)) {
$db = Factory::getDbo();
$db->setQuery('select lower(name) as name, id from #__djc2_countries_states WHERE ' . $where . ' order by name asc');
self::$states = $db->loadObjectList('name');
}
if (isset(self::$states[$name])) {
return self::$states[$name]->id;
}
$db->setQuery('select country_name, id from #__djc2_countries where ' . $where . ' AND lower(country_name) like' . $db->quote('%' . $db->escape($name) . '%') . ' LIMIT 1');
$result = $db->loadObject();
if (!empty($result)) {
self::$countries[$name] = $result;
return self::$countries[$name]->id;
}
return false;
}
public static function storeAttributes($rows, $model, $type, $defaults = array())
{
$text_types = array('text', 'textarea', 'html', 'media');
$int_types = array('select', 'multiselect', 'checkbox', 'radio', 'color', 'multicolor', 'bool');
$date_types = array('calendar');
$attribs = [];
$skipFields = ['id', 'name', 'alias', 'language', 'cat_id', 'producer_id', 'SKU', 'description', 'intro_desc', 'price',
'on_stock', 'length', 'width', 'height', 'weight', 'metakey', 'metadesc', 'published', 'ordering', 'created', 'created_by', 'images'];
$db = Factory::getDbo();
foreach ($rows as $row) {
foreach ($row as $r => $key) {
if (!in_array($r, $skipFields)) {
if (!empty($key)) {
$query = "SELECT * FROM #__djc2_items_extra_fields WHERE alias = " . $db->quote($r);
$db->setQuery($query);
$result = $db->loadObject();
if ($result) { // sprawdzamy czy coś zwróciło
$result->valueTmp = $key;
$result->productId = $row['id'];
$attribs[] = $result;
}
}
}
}
}
foreach ($attribs as $k => $v) {
$fv_table = null;
$type_table_name = null;
$table_type = null;
if (in_array($v->type, $text_types)) {
$fv_table = Table::getInstance('FieldValuesText', 'Djcatalog2Table', array());
$type_table_name = '#__djc2_items_extra_fields_values_text';
$table_type = 'text';
} else if (in_array($v->type, $int_types)) {
$fv_table = Table::getInstance('FieldValuesInt', 'Djcatalog2Table', array());
$type_table_name = '#__djc2_items_extra_fields_values_int';
$table_type = 'int';
} else if (in_array($v->type, $date_types)) {
$fv_table = Table::getInstance('FieldValuesDate', 'Djcatalog2Table', array());
$type_table_name = '#__djc2_items_extra_fields_values_date';
$table_type = 'date';
} else {
continue;
}
$extraField = new stdClass();
$extraField->item_id = $v->productId;
$extraField->field_id = $v->id;
$extraField->value = $v->valueTmp;
if(explode("\\", $extraField->value)){
echo "explode";
$values = explode("\\", $extraField->value);
$extraField->value = $values;
}
$group = new stdClass();
$group->item_id = $v->productId;
$group->group_id = $v->group_id;
try {
$result = $db->insertObject("#__djc2_items_groups", $group);
} catch (Exception $e) {
}
if(is_array($extraField->value)){
foreach ($extraField->value as $value){
echo "<br>";
$extraField->value = $value;
//Get value from db
//Set value that is from db
$query = "SELECT id FROM #__djc2_items_extra_fields_options WHERE field_id ='" . $extraField->field_id . "' AND value = '".$extraField->value."'";
$db->setQuery($query);
$result = $db->loadObject();
$extraField->value = $result->id;
$result = $db->insertObject($type_table_name, $extraField);
}
}else {
$query = "SELECT id FROM #__djc2_items_extra_fields_options WHERE field_id ='" . $extraField->field_id . "' AND value = '".$extraField->value."'";
$db->setQuery($query);
$result = $db->loadObject();
$extraField->value = $result->id;
$result = $db->insertObject($type_table_name, $extraField);
}
}
return true;
}
public static function storeCombinations($rows, $model, $type, $defaults = array())
{
$skipFields = ['id', 'name', 'alias', 'language', 'cat_id', 'producer_id', 'SKU', 'description', 'intro_desc', 'price',
'on_stock', 'length', 'width', 'height', 'weight', 'metakey', 'metadesc', 'published', 'ordering', 'created', 'created_by', 'images'];
$db = Factory::getDbo();
$arrayOfFields = array();
require_once __DIR__.'/combinations_helper.php';
//Combination id
$query = "SELECT * FROM `#__djc2_items_combinations` ORDER BY id DESC LIMIT 1;";
$db->setQuery($query);
$result = $db->loadObject();
$combination_id = $result->id + 1;
$index = 0;
//Get combinations by fields
foreach ($rows as $row) {
foreach ($row as $r => $key) {
if (!in_array($r, $skipFields)) {
if (!empty($key)) {
$query = "SELECT * FROM #__djc2_items_extra_fields WHERE alias ='" . $r . "'";
$db->setQuery($query);
$result = $db->loadObject();
foreach (explode('\\', $key) as $exp) {
$field = new stdClass();
$field->field_id = $result->id;
$field->value = $exp;
$field->group_id = $result->group_id;
$field->item_id = $row['id'];
if ($arrayOfFields[$index] == null) $arrayOfFields[$index] = array();
array_push($arrayOfFields[$index], (object)$field);
}
}
}
}
$index++;
}
$combinations_generated = array();
for ($i = 0; $i < $index; $i++)
array_push($combinations_generated, combinations_objects_by_field_id_and_combination_id($arrayOfFields[$i]));
// Use array_map to apply a callback function to each inner array
$outputArray = array_map(function ($innerArray) use (&$combination_id) {
// Use array_map again to apply a callback function to each inner object
$outputInnerArray = array_map(function ($innerObj) use ($innerArray, &$combination_id) {
// Create a new output object with the same properties as the input object,
// and a new 'combination_id' attribute based on the IDs in the inner array
$outputObj = (object) array(
'fields' => $innerObj,
'combination_id' => $combination_id
);
// Increment the combination ID value for the next object
$combination_id++;
return $outputObj;
}, $innerArray);
// Return the output inner array
return $outputInnerArray;
}, $combinations_generated);
// Flatten the array of arrays into an array of objects
$outputArray = call_user_func_array('array_merge', $outputArray);
//items_combinations_fields
foreach ($outputArray as $combo) {
$comboClass = new stdClass();
$comboClass->id = $combo->combination_id;
$comboClass->item_id = $combo->fields[0]->item_id;
$comboClass->sku = '';
$comboClass->gtin = '';
$comboClass->price = 0.0;
$comboClass->avg_price = 0.0;
$comboClass->avg_of_days = 0;
$comboClass->stock = 0.0;
$comboClass->length = 0.0;
$comboClass->width = 0.0;
$comboClass->height = 0.0;
$comboClass->dimensions_unit = 0;
$comboClass->weight = 0.0;
$comboClass->weight_unit = 0;
$comboClass->default = 0;
$result = $db->insertObject("#__djc2_items_combinations",$comboClass);
foreach ($combo->fields as $field) {
$fieldClass = new stdClass();
$fieldClass->combination_id = $combo->combination_id;
$fieldClass->field_id = $field->field_id;
//Set value that is from db
$query = "SELECT id FROM #__djc2_items_extra_fields_options WHERE field_id ='" . $fieldClass->field_id . "' AND value = '".$field->value."'";
$db->setQuery($query);
$result = $db->loadObject();
$fieldClass->value = $result->id;
$result = $db->insertObject("#__djc2_items_combinations_fields",$fieldClass);
}
}
return true;
}
}