Files
interblue.pl/modules/pshowimporter/controllers/admin/PShowImporterMainController.php
2024-10-25 14:16:28 +02:00

695 lines
24 KiB
PHP

<?php
/**
* File from http://PrestaShow.pl
*
* DISCLAIMER
* Do not edit or add to this file if you wish to upgrade this module to newer
* versions in the future.
*
* @authors PrestaShow.pl <kontakt@prestashow.pl>
* @copyright 2015 PrestaShow.pl
* @license http://PrestaShow.pl/license
*/
require_once dirname(__FILE__) . "/../../config.php";
class PShowImporterMainController extends PShowAdminController
{
public $default_action = 'index';
public $select_menu_tab = 'subtab-PShowImporterMain';
public function getlogAction()
{
$filepath = _IMPORT_LOG_PATH_ . urldecode(Tools::getValue('filename')) . '.log';
die(PShow_File::getLogFile($filepath));
}
public function __construct()
{
parent::__construct();
$this->controller_displayName = $this->l('Sample Controller');
$modulePath = getModulePath(__FILE__);
$req = array(
$modulePath . 'import-status',
$modulePath . 'import-log',
$modulePath . 'files-data',
$modulePath . 'upload',
$modulePath . 'update',
$modulePath . 'update/backups',
$modulePath . 'update/tmp',
);
// create required directories
foreach ($req as $path) {
if (!is_dir($path)) {
mkdir($path);
chmod($path, 0777);
}
}
// remove old log files
PShow_Log::removeOldFiles();
global $smarty;
$smarty->assign('category_matching', 2);
$smarty->assign('lang_iso', $this->context->language->iso_code);
$smarty->assign('pshowimporter_logs', glob(getModulePath(__FILE__) . "log/*.log"));
}
public function updateChmod($path = null)
{
if ($path === null)
$path = getModulePath(__FILE__) . '*';
$files = glob($path);
foreach ($files as $file) {
if (is_dir($file))
$this->updateChmod($file . "/*");
@chmod($file, 0777);
}
}
/**
* Overrides reinstallation
*/
public function reinstallOverridesAction()
{
if (Tools::getValue('start')) {
$module = Module::getInstanceByName('pshowimporter');
$test = true;
try {
$module->uninstallOverrides();
$this->alerts[] = array('success', $this->l('Override removed'));
} catch (Exception $e) {
$test = false;
$this->alerts[] = array('danger', sprintf(Tools::displayError('Unable to uninstall override: %s'), $e->getMessage()));
}
try {
$module->installOverrides();
$this->alerts[] = array('success', $this->l('Override installed'));
} catch (Exception $e) {
$test = false;
$this->alerts[] = array('danger', sprintf(Tools::displayError('Unable to install override: %s'), $e->getMessage()));
$msg = $this->l("Unfortunately, we failed to install new overrides.") . '<br><br>';
$matches = array();
preg_match_all('~The method ([a-zA-Z0-9\-\_]+) in the class ([a-zA-Z0-9\-\_]+) is already overridden~', $e->getMessage(), $matches);
if (isset($matches[1]) && isset($matches[2])) {
$reflector = new ReflectionClass($matches[2][0]);
$filepath = str_replace(_PS_ROOT_DIR_, '', $reflector->getFileName());
$msg .= sprintf($this->l("Function `%s` in the file %s` has been previously overwritten manually or by another module. "
. "You need to remove the `%s` function from the `%s` file or manually install the overwrite in the store."), $matches[1][0], $filepath, $matches[1][0], $filepath) . '<br><br>';
$msg .= $this->l("If you need help, write to us and send the FTP access data.") . '<br>';
$msg .= '<a href="https://helpdesk.prestashow.pl" target="_blank">https://helpdesk.prestashow.pl</a>';
$this->alerts[] = array('danger', $msg);
}
$module->uninstallOverrides();
}
if ($test) {
$this->alerts[] = array('success', $this->l('Module is now ready to use!'));
}
}
$this->action_displayName = $this->l('Reinstall overrides');
}
public function sshAction()
{
$this->action_displayName = $this->l('How to run import via SSH');
}
public function cloneAction()
{
$this->action_displayName = $this->l('Clone file');
$filename = Tools::getValue('file');
$filepath = false;
$pathes = glob(_MODULE_UPLOAD_PATH_ . $filename . '.*');
foreach ($pathes as $path) {
if (!in_array(pathinfo($path, PATHINFO_EXTENSION), explode(',', _IMPORT_FILE_EXTENSIONS_))) {
continue;
}
$filepath = $path;
break;
}
if ($filepath) {
$clonepath = str_replace($filename, time() . '-' . PShow_File::findFreeNameToUpload(Tools::substr($filename, (stripos($filename, '-') + 1))), $filepath);
file_put_contents($clonepath, PShow_File::file_get_contents($filepath));
if (file_exists(_MODULE_UPLOAD_PATH_ . $filename . '.txt')) {
file_put_contents(
str_replace(pathinfo($path, PATHINFO_EXTENSION), 'txt', $clonepath), PShow_File::file_get_contents(_MODULE_UPLOAD_PATH_ . $filename . '.txt')
);
}
PShow_Log::add(
_IMPORT_LOG_PATH_ . $filename . ".log", PShow_Log::FILE_CLONE, str_replace(_MODULE_UPLOAD_PATH_, '', $clonepath)
);
$this->alerts[] = array('success', $this->l('File cloned successfully'));
}
Cache::getInstance()->delete('pshowimporter_files_list');
$this->action = 'index';
$this->indexAction();
}
public function redownloadAction()
{
$this->action_displayName = $this->l('Update this file from URL');
$filename = Tools::getValue('file');
$filepath = false;
$pathes = glob(_MODULE_UPLOAD_PATH_ . $filename . '.*');
foreach ($pathes as $path) {
if (!in_array(pathinfo($path, PATHINFO_EXTENSION), explode(',', _IMPORT_FILE_EXTENSIONS_))) {
continue;
}
$filepath = $path;
break;
}
$url = PShow_File::file_get_contents(str_replace('.' . pathinfo($filepath, PATHINFO_EXTENSION), ".txt", $filepath));
if (!$url) {
$this->alerts[] = array('error', $this->l('URL not found'));
$this->action = 'index';
$this->indexAction();
return;
}
if (stripos($url, 'http://') === false && stripos($url, 'https://') === false) {
$url = 'http://' . $url;
}
if (PShow_File::updateFileFromURL($filepath, $url)) {
$this->alerts[] = array('success', $this->l('File updated successfully'));
} else {
$this->alerts[] = array('warning', $this->l('Something went wrong! Check file log.'));
}
$this->action = 'index';
$this->indexAction();
return;
}
public function indexAction()
{
$this->addJS(__PS_BASE_URI__ . 'modules/pshowimporter/views/js/files_list.js');
$this->addCSS(__PS_BASE_URI__ . 'modules/pshowimporter/views/css/full-screen-loader.css');
if (version_compare(_PS_VERSION_, '1.6.0', '<')) {
$this->addCSS(__PS_BASE_URI__ . 'modules/pshowimporter/views/css/font-awesome.min.css');
$this->addCSS(__PS_BASE_URI__ . 'modules/pshowimporter/views/css/import_ps15.css');
$this->addJS(__PS_BASE_URI__ . 'modules/pshowimporter/views/js/import_ps15.js');
}
$this->action_displayName = $this->l('Informations');
$smarty = $this->context->smarty;
if ((int) ini_get("upload_max_filesize") < 100) {
$smarty->assign('upload_max_filesize_error', true);
}
if ((int) ini_get("post_max_size") < 150) {
$smarty->assign('post_max_size_error', true);
}
if ((int) ini_get("memory_limit") < 200) {
$smarty->assign('memory_limit_error', true);
}
if (Tools::isSubmit('submit_sendfile')) {
$this->getFile();
}
if (Tools::getValue('removefile')) {
$this->removeFile();
}
if (Tools::getValue('removesamplefiles')) {
$this->removeSampleFiles();
}
if (Tools::getValue('removeconfig')) {
$this->removeConfig();
}
$files_list = PShow_File::getFilesList();
$sortby = Tools::getValue('sortby');
$sortorder = Tools::getValue('sortorder');
if ($sortby && $sortorder) {
$files_list = PShow_File::sortFiles($files_list, $sortby, $sortorder);
}
$smarty->assign('files', $files_list);
$smarty->assign('modulePath', getModulePath(__FILE__));
$smarty->assign('writeableImportConfig', is_writeable(getModulePath(__FILE__) . 'import-config'));
$smarty->assign('writeableImportLog', is_writeable(getModulePath(__FILE__) . 'import-log'));
$smarty->assign('writeableImportStatus', is_writeable(getModulePath(__FILE__) . 'import-status'));
$smarty->assign('writeableUpload', is_writeable(getModulePath(__FILE__) . 'upload'));
$smarty->assign('writeableUpdate', is_writeable(getModulePath(__FILE__) . 'update'));
$smarty->assign('MODULE_PATH', getModulePath(__FILE__));
$isDuringImport = self::isDuringImport();
$smarty->assign('isDuringImport', $isDuringImport);
if ($isDuringImport) {
$smarty->assign('importStartDate', self::getImportStartDate());
$smarty->assign('importUpdateDate', self::getImportUpdateDate());
$smarty->assign('imported', self::getImported());
$smarty->assign('isDuringCronImport', file_exists(getModulePath(__FILE__) . 'direct_import_now'));
}
$this->context->smarty->assign('is_multishop', class_exists('PShow_Import_Object_Multistore'));
if (version_compare(LIBXML_DOTTED_VERSION, '2.9.3') == 0) {
$this->alerts[] = array(
'danger',
$this->l('You are using the php extension `libxml` in version 2.9.3.')
. ' <b>' . $this->l('Many users report a problem with the module\'s functionality with this version of the extension.') . '</b> '
. $this->l('Contact your hosting provider to change the version of this extension.')
);
}
if (Shop::isFeatureActive() && !class_exists('PShow_Import_Object_Multistore')) {
$this->alerts[] = array(
'danger',
$this->l('You are using multistore.')
. ' <b>' . $this->l('The module may operate incorrectly.') . '</b> '
. $this->l('For a special addition to the multistore options, go to this address')
. ': <a href="http://prestashow.pl/pl//26-.html">http://prestashow.pl/pl//26-.html</a>'
);
}
/**
* Multistore support
*/
if (class_exists('PShow_Import_Object_Multistore') &&
(!property_exists('Shop', 'mod_from_pshowimporter_v') || version_compare('2.193', Shop::$mod_from_pshowimporter_v) != 0)) {
$this->alerts[] = array('danger', $this->l('Overrides reinstallation required!')
. ' <a href="' . $this->context->link->getAdminLink('PShowImporterMain') . '&page=reinstallOverrides" class="label label-default">click here</a>');
}
/**
* Queue support
*/
$queue = PShow_Queue::getInstance()->getQueue();
$queue_list = array();
foreach ($queue as $filename) {
foreach ($files_list as $file) {
if ($file['time'] . '-' . $file['filename'] == $filename) {
array_push($queue_list, $file);
break;
}
}
}
$this->context->smarty->assign('import_queue', $queue);
$this->context->smarty->assign('queue_list', $queue_list);
/**
* pshowHook below side menu
*/
$pshowHook_below_side_menu = '<div class="panel col-xs-offset-4 col-xs-4 col-md-offset-0 col-md-12">'
. '<h3>' . $this->l('Addons') . '</h3>';
$pshowHook_below_side_menu .= '<p class="row"><strong>' . $this->l('Multistore support') . ':</strong></p>';
if (PShow_Addon::exists('Multistore')) {
$pshowHook_below_side_menu .= '<p class="row text-right"><span class="label label-success">'
. $this->l('Installed and ready to use') . '</span></p>';
} else {
$pshowHook_below_side_menu .= '<p class="row text-right"><a href="https://prestashow.pl/pl//26-.html" target="_blank">'
. '<span class="label label-warning">' . $this->l('Not available, click to install') . '</span></a></p>';
}
$pshowHook_below_side_menu .= '<p class="row"><strong>' . $this->l('Advanced stock management') . ':</strong></p>';
if (PShow_Addon::exists('ASM')) {
$pshowHook_below_side_menu .= '<p class="row text-right"><span class="label label-success">'
. $this->l('Installed and ready to use') . '</span></p>';
} else {
$pshowHook_below_side_menu .= '<p class="row text-right"><a href="https://prestashow.pl/pl//30-.html" target="_blank">'
. '<span class="label label-warning">' . $this->l('Not available, click to install') . '</span></a></p>';
}
$pshowHook_below_side_menu .= '</div><div class="clearfix"></div>';
$this->context->smarty->assign('pshowHook_below_side_menu', $pshowHook_below_side_menu);
}
public static function getImported()
{
$actual_row_file = _IMPORT_STATUS_PATH_ . 'actual_row';
$filename_file = _IMPORT_STATUS_PATH_ . 'filename';
if (!self::isDuringImport() || !file_exists($actual_row_file) || !file_exists($filename_file)) {
return false;
}
$filename = file_get_contents($filename_file);
$actual_row = (int) file_get_contents($actual_row_file);
PShow_Import::getInstance($filename);
if (!PShow_Import::getInstance()) {
return false;
}
return $actual_row . '/' . PShow_Config::get('rowsCount');
}
public static function getImportStartDate()
{
if (!self::isDuringImport()) {
return false;
}
return date("H:i:s d/m/Y", filemtime(_IMPORT_STATUS_PATH_ . 'filename'));
}
public static function getImportUpdateDate()
{
if (!self::isDuringImport()) {
return false;
}
return date("H:i:s d/m/Y", filemtime(_IMPORT_STATUS_PATH_ . 'actual_row'));
}
public static function isDuringImport()
{
if (count(glob(_IMPORT_STATUS_PATH_ . '*')) > 1) {
$filename = PShow_File::file_get_contents(_IMPORT_STATUS_PATH_ . 'filename');
if (empty($filename)) {
@unlink(_IMPORT_STATUS_PATH_ . "actual_row");
@unlink(_IMPORT_STATUS_PATH_ . "error_rows");
@unlink(_IMPORT_STATUS_PATH_ . "counter_imported_rows");
@unlink(_IMPORT_STATUS_PATH_ . "counter_skipped_rows");
@unlink(_IMPORT_STATUS_PATH_ . "counter_error_rows");
@unlink(_IMPORT_STATUS_PATH_ . "filename");
@unlink(_IMPORT_STATUS_PATH_ . "imported_references");
@unlink(getModulePath(__FILE__) . "direct_import_now");
} else {
return $filename;
}
}
return false;
}
public function getFile()
{
global $smarty;
$url = Tools::getValue('url');
$auth_req = Tools::getValue('auth_req');
$login = Tools::getValue('login');
$password = Tools::getValue('password');
if (!$url) {
$status = PShow_File::getFileFromLocalDisk();
} else {
$status = PShow_File::getFileFromURL($url, $auth_req, $login, $password);
}
$smarty->assign('status', $status);
}
/**
*
* @global \Smarty $smarty
* @param string $filename
*/
public function _removeFile($filename)
{
global $smarty;
$this->updateChmod();
$pathes = glob(_MODULE_UPLOAD_PATH_ . $filename . '.*');
$removed = array();
foreach ($pathes as $path) {
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext != 'txt') {
$removed[] = pathinfo($path, PATHINFO_FILENAME) . '.' . $ext;
}
unlink($path);
}
if (file_exists(_MODULE_FILES_DATA_PATH_ . pathinfo($pathes[0], PATHINFO_FILENAME) . '.ini'))
unlink(_MODULE_FILES_DATA_PATH_ . pathinfo($pathes[0], PATHINFO_FILENAME) . '.ini');
@exec("rm -rf '" . _IMPORT_CONFIG_PATH_ . $filename . "'");
Cache::getInstance()->delete('pshowimporter_files_list');
if (count($removed) > 0)
$smarty->assign('removeStatus', $removed);
}
public function removeFile()
{
$this->_removeFile(Tools::getValue('removefile'));
}
public function removeSampleFiles()
{
$this->_removeFile('3-1_kategorie_xml');
$this->_removeFile('3-2_atrybuty_xml');
$this->_removeFile('3-3_produkty_xml');
$this->_removeFile('3-4_kombinacje_xml');
$this->_removeFile('1-1_kategorie_csv');
$this->_removeFile('1-2_atrybuty_csv');
$this->_removeFile('1-3_produkty_csv');
$this->_removeFile('1-4_kombinacje_csv');
$this->_removeFile('2-cechy_csv');
$this->_removeFile('4-cechy_xml');
}
public function removeConfig()
{
$this->updateChmod();
$filename = Tools::getValue('removeconfig');
array_map('unlink', glob(_IMPORT_CONFIG_PATH_ . $filename . '/*'));
rmdir(_IMPORT_CONFIG_PATH_ . $filename);
$this->alerts[] = array('success', $this->l('Configuration removed'));
}
/**
* Convert csv to xml
*/
public function converttoxmlAction()
{
$filename = Tools::getValue('filename');
$filepath = _MODULE_UPLOAD_PATH_ . $filename . '.csv';
if (!file_exists($filepath)) {
return Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
$config = PShow_Config::getFileConfig($filename);
if (isset($config['file']) && isset($config['file']['csv']) && isset($config['file']['csv']['separator'])) {
$delimiter = $config['file']['csv']['separator'];
} else {
return Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
$headers_in_the_file = 1;
$delimiter = $config['file']['csv']['separator'];
// create xml file
PShow_Csv::convertToXml($filepath, $delimiter, true, $headers_in_the_file);
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
public function addtoqueueAction()
{
$filename = Tools::getValue('filename');
PShow_Queue::getInstance()->addToQueue($filename);
if (Tools::getValue('import')) {
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterImport', true));
return;
}
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
public function ajaxProcess()
{
if (Tools::isSubmit('clearLog')) {
$filename = Tools::getValue('filename');
unlink(_IMPORT_LOG_PATH_ . $filename . '.log');
die(Tools::jsonEncode('ok'));
}
}
public function delfromqueueAction()
{
$filename = Tools::getValue('filename');
PShow_Queue::getInstance()->delFromQueue($filename);
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
public function stopAction()
{
$filename = PShow_File::file_get_contents(_IMPORT_STATUS_PATH_ . 'filename');
@unlink(_IMPORT_STATUS_PATH_ . "actual_row");
@unlink(_IMPORT_STATUS_PATH_ . "error_rows");
@unlink(_IMPORT_STATUS_PATH_ . "counter_imported_rows");
@unlink(_IMPORT_STATUS_PATH_ . "counter_skipped_rows");
@unlink(_IMPORT_STATUS_PATH_ . "counter_error_rows");
@unlink(_IMPORT_STATUS_PATH_ . "filename");
@unlink(_IMPORT_STATUS_PATH_ . "imported_references");
@unlink(getModulePath(__FILE__) . "direct_import_now");
PShow_Log::add(_IMPORT_LOG_PATH_ . $filename . ".log", PShow_Log::IMPORT_STOP);
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
/**
* Edit filename
*/
public function editfilenameAction()
{
$old = Tools::getValue('oldname');
$new = Tools::getValue('newname');
if (!$new || empty($new) || !$old) {
die('1');
}
PShow_Config::saveFileConfig($old, array('displayFileName' => $new));
Cache::getInstance()->delete('pshowimporter_files_list');
die('OK');
}
public function editsourceAction()
{
$filename = Tools::getValue('filename');
$newSource = Tools::getValue('newSource');
if (!$filename || empty($filename) || $newSource === false) {
die('1');
}
$files = glob(_MODULE_UPLOAD_PATH_ . '*-' . $filename . '.*');
if (!count($files)) {
die('2');
}
$filepath = reset($files);
$filepath = str_replace(array('.csv', '.xml'), '.txt', $filepath);
if (file_exists($filepath) && $newSource == '') {
unlink($filepath);
} else {
file_put_contents($filepath, $newSource);
}
Cache::getInstance()->delete('pshowimporter_files_list');
die('OK');
}
public function copyconfigAction()
{
$from = Tools::getValue('from');
$to = Tools::getValue('to');
if (!$from || empty($from) || !$to || empty($to) || !is_dir(_IMPORT_CONFIG_PATH_ . $from)) {
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
if (!is_dir(_IMPORT_CONFIG_PATH_ . $to)) {
mkdir(_IMPORT_CONFIG_PATH_ . $to);
}
$files = glob(_IMPORT_CONFIG_PATH_ . $from . '/*.ini');
foreach ($files as $f) {
$t = str_replace($from, $to, $f);
if (file_exists($t)) {
unlink($t);
}
copy($f, $t);
}
copy(_IMPORT_CONFIG_PATH_ . $from . '/config.yml', _IMPORT_CONFIG_PATH_ . $to . '/config.yml');
Cache::getInstance()->delete('pshowimporter_files_list');
Tools::redirectAdmin($this->context->link->getAdminLink('PShowImporterMain', true));
}
public function uploadconfigAction()
{
if (!isset($_FILES) || !count($_FILES) || !isset($_FILES['file']) ||
$_FILES['file']['error'] || !Tools::getValue('filename')) {
$this->alerts[] = array('warning', $this->l('File upload failed'));
$this->action = 'index';
$this->indexAction();
return;
}
if (!is_dir(_IMPORT_CONFIG_PATH_ . Tools::getValue('filename'))) {
mkdir(_IMPORT_CONFIG_PATH_ . Tools::getValue('filename'));
}
move_uploaded_file($_FILES['file']['tmp_name'], _IMPORT_CONFIG_PATH_ . Tools::getValue('filename') . '/config.yml');
Cache::getInstance()->delete('pshowimporter_files_list');
$this->alerts[] = array('success', $this->l('File uploaded successfully'));
$this->action = 'index';
$this->indexAction();
}
}