Your IP : 216.73.216.240


Current Path : /home/juvelize/saulnois/tmp/install_695d2cf0b4957/src/Controller/
Upload File :
Current File : /home/juvelize/saulnois/tmp/install_695d2cf0b4957/src/Controller/TfControllerImport.php

<?php
/*
* @package		Tech Fry Library
* @license		https://www.gnu.org/licenses/gpl-3.0.en.html
*/

namespace TechFry\Library\Controller;

defined('_JEXEC') or die;

use Joomla\CMS\Application\CMSApplication;
use Joomla\CMS\Factory;
use Joomla\CMS\Filter\OutputFilter;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\Input\Input;
use Joomla\CMS\Helper\TagsHelper;
use TechFry\Library\TExtension;
use TechFry\Library\TUser;
use TechFry\Library\TArticle;
use TechFry\Library\TDb;
use TechFry\Library\TField;

class TfControllerImport extends BaseController
{
    public $option;

    public $component;

    public $model_name;

    public $table_name;

    public $columns;

    public $custom_fields;

    public $extra_data;

    public function __construct($config = array(), ?MVCFactoryInterface $factory = null, ?CMSApplication $app = null, ?Input $input = null)
    {
        parent::__construct($config, $factory, $app, $input);

        $this->option = $this->input->get('option');
    }

    public function import()
    {
        $model = $this->getModel();

        if (!$model->pro())
        {
            $this->setMessage(Text::_('COM_TF_PRO_UPGRADE_MESSAGE'), 'error');

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

            return;
        }

        $info = $this->input->get('jform', array(), 'array');

        $parts = explode('.', $info['type']);
        $this->component = 'com_' . $parts[0];
        $this->model_name = ucfirst($parts[1]);

        $app = Factory::getApplication();

        $ex = new TExtension($this->component);

        // 1. Create model
        $target_model = $ex->get_model($this->model_name);

        // 2. Get table
        $jtable = $target_model->getTable();
        $this->table_name = $jtable->getTableName();

        // 3. Get uploaded CSV File
        $files = $this->input->files->get('jform');
        $file = $files['upload_file'];

        $filename = File::makeSafe($file['name']);

        $ext = strtolower(File::getExt($filename));
        if ($ext !== 'csv')
        {
            $this->setMessage(Text::_('COM_TF_ERROR_INVALID_FILE'), 'error');

            $this->setRedirect(Route::_('index.php?option=' . $this->option . '&view=import&type=' . $info['type'], false));

            return;
        }

        $fileopen = fopen($file['tmp_name'], "r");
        $counter = 0;
        $updates = 0;
        $exists = 0;

        // First row of CSV file contains column names
        $this->columns = fgetcsv($fileopen, 10000, ',');
        foreach ($this->columns as $i => $column)
        {
            // Column name is numeric (custom field id) for custom fields
            if (\is_numeric($column))
            {
                $cf = new TField();
                $this->custom_fields[$column] = $cf->get_field($column)->name;
            }
        }

        if ($info['addon'])
        {
            $addons = explode(';', $info['addon']);
            foreach ($addons as $addon)
            {
                $extra_data_parts = explode(':', $addon);
                $k = trim($extra_data_parts[0]);
                $v = trim($extra_data_parts[1]);
                $this->extra_data[$k] = $v;
            }
        }

        while (($data = fgetcsv($fileopen, 10000, ",")) !== FALSE)
        {
            $record = $this->set_data($data);

            $record = $this->set_default_data($record);

            // $model->set_message($record);

            $save = true;
            if ($info['enable_new'] && $record['id'] == 0)
            {
                $save = $target_model->save($record);
                $counter++;
            }

            if ($info['enable_updates'] && $record['id'])
            {
                $save = $target_model->save($record);
                $updates++;
            }

            if ($record['id'])
            {
                $exists++;
            }

            if (!$save)
            {
                $app->enqueueMessage(Text::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $target_model->getError()), 'error');

                return;
            }
        }

        fclose($fileopen);

        $this->setMessage($counter . ' ' . Text::_('COM_TF_RECORDS_IMPORTED') . ' ' . $updates . ' records updated. ' . $exists . ' ' . Text::_('COM_TF_RECORDS_EXISTS'));

        $this->setRedirect(Route::_('index.php?option=' . $this->option . '&view=import&type=' . $info['type'], false));
    }

    // 02. Returns record array to save
    public function set_data($data)
    {
        $record = array();

        // Set Addon Data
        if ($this->extra_data)
        {
            $record = array_merge($record, $this->extra_data);
        }

        foreach ($this->columns as $i => $column)
        {
            if (\is_numeric($column)) // Custom Field
            {
                $field_name = $this->custom_fields[$column];
                $record['com_fields'][$field_name] = $data[$i];
            }
            elseif ($column == 'tags') // Tags
            {
                $tag_ids = explode(',', $data[$i]);
                foreach ($tag_ids as $tag_id)
                {
                    $record['tags'][] = trim($tag_id);
                }
            }
            else
            {
                $record[$column] = $data[$i];  
            }
        }

        return $record;
    }

    // Set fields that should be handled automatically
    public function set_default_data($record)
    {
        $db = Factory::getDbo();
        $cols = $db->getTableColumns($this->table_name);

        // 1. Alias
        if (array_key_exists('alias', $cols) && !isset($record['alias']) && !isset($record['id']))
        {
            $record['alias'] = OutputFilter::stringURLSafe($record['title']);
        }

        // 2. Id
        if (array_key_exists('id', $cols))
        {
            if (!isset($record['id']))
            {
                // Check if record exists
                $record['id'] = $this->check_record($record);
            }
        }

        // 3. Published
        if (array_key_exists('published', $cols) && !isset($record['published']) && !$record['id'])
        {
            $record['published'] = 1;
        }

        // 4. State
        if (array_key_exists('state', $cols) && !isset($record['state']) && !$record['id'])
        {
            $record['state'] = 1;
        }

        // 5. Language
        if (array_key_exists('language', $cols) && !isset($record['language']) && !$record['id'])
        {
            $record['language'] = '*';
        }

        // 6. Introtext (Special for Joomla Articles)
        if (array_key_exists('introtext', $cols) && !isset($record['introtext']) && !$record['id'])
        {
            $record['introtext'] = '';
        }

        // 7. Tags (Special for Joomla Articles)
        if ($this->component == 'com_content' && $this->model_name == 'Article' && $record['id'] && !isset($record['tags']))
        {
            $th = new TagsHelper();
            $currentTags = $th->getTagIds($record['id'], 'com_content.article');
            if ($currentTags)
            {
                $record['tags'] = explode(',', $currentTags);
            }
        }

        // 8. Description
        if (array_key_exists('description', $cols) && !isset($record['description']) && !$record['id'])
        {
            $record['description'] = '';
        }

        // 9. Special case for new users
        if ($this->component == 'com_users' && $this->model_name == 'User')
        {
            $u = new TUser();
            $record = $u->complete_user_data($record);
        }

        return $record;
    }

    public function check_record($record)
    {
        if ($this->component == 'com_content' && $this->model_name == 'Article')
        {
            $a = new TArticle();
            $id = $a->find_article($record['alias'], $record['catid']);
        }
        elseif ($this->component == 'com_users' && $this->model_name == 'User')
        {
            $u = new TUser();
            $id = $u->find_user($record['email']);
        }
        elseif ($this->component == 'com_tftools' && $this->model_name == 'Link')
        {
            $conditions = array(
                array('title', '=', $record['title']),
            );
            $db = new TDb('tft_links');
            $item = $db->get_item(array('conditions' => $conditions));
            
            $id = $item->id;
        }
        elseif (isset($record['alias']) && $record['alias'])
        {
            $table_name = substr($this->table_name, 3);
            $conditions = array(
                array('alias', '=', $record['alias']),
            );

            $db = new TDb($table_name);
            $item = $db->get_item(array('conditions' => $conditions));
            
            $id = $item->id;
        }

        return $id ? $id : 0;
    }

    public function cancel($key = null)
    {
        $this->checkToken();

        $this->setRedirect(Route::_('index.php?option=' . $this->option . '&view=dashboard', false));

        return true;
    }
}