Created
November 30, 2012 10:51
-
-
Save maxpoletaev/4175101 to your computer and use it in GitHub Desktop.
Advanced miniShop console import
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Вывод ошибок | |
ini_set('display_errors', 1); | |
ini_set('memory_limit', '512M'); | |
error_reporting(E_ERROR); | |
// Подключаем | |
define('MODX_API_MODE', true); | |
require dirname(dirname(dirname(__FILE__))).'/index.php'; | |
// Включаем обработку ошибок | |
$modx->getService('error','error.modError'); | |
$modx->setLogLevel(modX::LOG_LEVEL_FATAL); | |
$modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML'); | |
// Запускаем miniShop | |
if (!isset($modx->miniShop) || !is_object($modx->miniShop)) { | |
$modx->miniShop = $modx->getService('minishop','miniShop', $modx->getOption('core_path').'components/minishop/model/minishop/', array()); | |
if (!($modx->miniShop instanceof miniShop)) return ''; | |
} | |
// Логинимся в админку | |
$response = $modx->runProcessor('security/login', array('username' => 'admin', 'password' => 'password')); | |
if ($response->isError()) { | |
$modx->log(modX::LOG_LEVEL_ERROR, $response->getMessage()); | |
return; | |
} | |
$modx->initialize('mgr'); | |
$start_time = time(); | |
// Настройки | |
$source = $modx->getOption('minishop.import_source', '', '/core/import.xml'); | |
$time = time(); | |
$file = MODX_CORE_PATH.'import/import.xml'; | |
// Работаем | |
if (preg_match('/^http/', $source)) { | |
file_put_contents($file, file_get_contents($source)); | |
} | |
else { | |
copy(MODX_BASE_PATH.$source, $file); | |
} | |
if (file_exists($file)) { | |
require dirname(__FILE__).'/xml2array.php'; | |
$file = file_get_contents($file); | |
if (!$xml = xml2array($file)) { | |
exit('Не могу открыть: '.$file); | |
} | |
} else { | |
exit(); | |
} | |
$categories = $subcategories = $errors = $cat_replace = $subcat_replace = $catalog = array(); | |
$categories_tpl = explode(',', $modx->getOption('minishop.categories_tpl')); | |
$goods_tpl = explode(',', $modx->getOption('minishop.goods_tpl')); | |
if (!array_key_exists('0', $xml['корневой']['ЭлементСправочника'])) { | |
$goods = $xml['корневой']; | |
} | |
else { | |
$goods = $xml['корневой']['ЭлементСправочника']; | |
} | |
$tmp_cat_replace = $modx->getOption('minishop.import_cat_replace'); | |
if (!empty($tmp_cat_replace)) { | |
$tmp_cat_replace = explode('||', $tmp_cat_replace); | |
foreach ($tmp_cat_replace as $k => $v) { | |
$tmp = explode('==',$v); | |
$cat_replace[$tmp[0]] = $tmp[1]; | |
} | |
} | |
$tmp_subcat_replace = $modx->getOption('minishop.import_subcat_replace'); | |
if (!empty($tmp_subcat_replace)) { | |
$tmp_subcat_replace = explode('||', $tmp_subcat_replace); | |
foreach ($tmp_subcat_replace as $k => $v) { | |
$tmp = explode('==',$v); | |
$subcat_replace[$tmp[0]] = $tmp[1]; | |
} | |
} | |
/*-----------------------------------------------*/ | |
$total = $imported = $updated = 0; | |
foreach ($goods as $v) { | |
$total++; | |
// Очищаем ошибки от прошлого прохода | |
$modx->error->errors = array(); | |
$modx->error->message = null; | |
// Определяем группу товара | |
if (isset($v['Группа'])) { | |
$cat = trim($v['Группа']); | |
} else { | |
addError('Не указан параметр Группа у товара "'.$v['Наименование'].'"'); | |
continue; | |
} | |
// Определяем подгруппу | |
if (isset($v['ПодГруппа'])) { | |
$subcat = trim($v['ПодГруппа']); | |
} else { | |
addError('Не указан параметр ПодГруппа у товара "'.$v['Наименование'].'"'); | |
continue; | |
} | |
// Проводим замену имени, если нужно | |
if (array_key_exists($cat, $cat_replace)) { | |
$cat = $cat_replace[$cat]; | |
} | |
if (array_key_exists($subcat, $subcat_replace)) { | |
$subcat = $subcat_replace[$subcat]; | |
} | |
// Ищем категорию | |
if (!array_key_exists($cat, $categories)) { | |
if ($category = $modx->getObject('modResource', array('pagetitle' => $cat, 'template:IN' => $categories_tpl))) { | |
$cat_id = $category->get('id'); | |
$categories[$cat] = array( | |
'id' => $cat_id | |
,'subcat' => array() | |
); | |
} | |
else { | |
addError('Не могу найти категорию "'.$cat.'", пропускаю этот товар.'); | |
continue; | |
} | |
} | |
else { | |
$cat_id = $categories[$cat]['id']; | |
} | |
// Ищем подкатегорию | |
if (!empty($categories[$cat]['subcat'][$subcat])) { | |
$subcat_id = $categories[$cat]['subcat'][$subcat]; | |
} | |
else { | |
if ($subcategory = $modx->getObject('modResource', array('pagetitle' => $subcat, 'parent' => $cat_id, 'template:IN' => $categories_tpl))) { | |
$subcat_id = $subcategory->get('id'); | |
$categories[$cat]['subcat'][$subcat] = $subcat_id; | |
} | |
else { | |
addError('Не могу найти подкатегорию "'.$subcat.'", пытаюсь создать'); | |
// Здесь создаем подкатегорию и получаем ее $subcat_id | |
$response = $modx->runProcessor('resource/create', array( | |
'pagetitle' => $subcat | |
,'parent' => $cat_id | |
,'template' => $categories_tpl[0] | |
,'isfolder' => 1 | |
,'published' => 1 | |
)); | |
if ($response->isError()) { | |
addError('Не смог создать "'.$subcat.'", ошибка: "'.$response->getMessage().'"'); | |
continue; | |
} | |
else { | |
addError('Создал новую подкатегорию "'.$subcat.'", в категории "'.$cat.'"'); | |
$subcat_id = $categories[$cat]['subcat'][$subcat] = $response->response['object']['id']; | |
} | |
} | |
} | |
if ($subcat_id == 0) { | |
addError('Не найдена родительская категория для товара "'.$v['Наименование'].'"'); | |
continue; | |
} | |
// Наконец, создаем товар | |
if ($res = $modx->getObject('modResource', array('pagetitle' => $v['Наименование'], 'parent' => $subcat_id))) { | |
// Update | |
$response = $modx->runProcessor('mgr/goods/update', | |
array( | |
'id' => $res->get('id') | |
,'pagetitle' => $v['Наименование'] | |
,'longtitle' => $v['НаименованиеПолное'] | |
,'weight' => preg_replace('/[^\d]+/', '', $v['Вес']) | |
,'price' => preg_replace('/[^\d]+/', '', $v['Цена']) | |
,'remains' => $v['Остаток'] | |
,'content' => $v['Описание'] | |
,'article' => $v['Код'] | |
,'parent' => $subcat_id | |
,'template' => $goods_tpl[0] | |
,'isfolder' => 0 | |
,'published' => empty($v['Остаток']) || $v['Остаток'] <= 0 ? 0 : 1 | |
,'context_key' => 'web' | |
,'wid' => 1 | |
) | |
,array('processors_path' => MODX_CORE_PATH.'components/minishop/processors/') | |
); | |
if (!$response->isError()) { | |
$updated++; | |
} | |
} | |
else { | |
// Create | |
$response = $modx->runProcessor('mgr/goods/create', | |
array( | |
'pagetitle' => $v['Наименование'] | |
,'longtitle' => $v['НаименованиеПолное'] | |
,'weight' => preg_replace('/[^\d]+/', '', $v['Вес']) | |
,'price' => preg_replace('/[^\d]+/', '', $v['Цена']) | |
,'remains' => $v['Остаток'] | |
,'content' => $v['Описание'] | |
,'article' => $v['Код'] | |
,'parent' => $subcat_id | |
,'template' => $goods_tpl[0] | |
,'isfolder' => 0 | |
,'published' => empty($v['Остаток']) || $v['Остаток'] <= 0 ? 0 : 1 | |
,'context_key' => 'web' | |
,'wid' => 1 | |
) | |
,array('processors_path' => MODX_CORE_PATH.'components/minishop/processors/') | |
); | |
if (!$response->isError()) { | |
$imported++; | |
} | |
} | |
if ($response->isError()) { | |
$modx->log(modX::LOG_LEVEL_ERROR, $response->getMessage()); | |
} | |
} | |
$time = round((time() - $start_time), 2); | |
$message = | |
"Всего товаров: <b>".$total."</b>, импортировано: ".$imported.", обновлено: ".$updated.", время: <b>".$time."</b>сек. <br/>". | |
"Ошибки импорта:"."<br/><pre>".implode("<br/>",$errors)."</pre>"; | |
$to = $modx->getOption('minishop.import_email', '', $modx->getOption('emailsender')); | |
$subject = "Товары были успешно импортированы ".date('d.m.Y H:i:s'); | |
sendMail($subject,$message,$to); | |
if (!preg_match('/^http/', $source)) { | |
unlink(MODX_BASE_PATH.$source); | |
} | |
unlink($file); | |
//--------------------------------- | |
function addError($msg) { | |
global $errors; | |
$hash = md5($msg); | |
if (!array_key_exists($hash, $errors)) { | |
$errors[$hash] = $msg; | |
} | |
} | |
function sendMail($subject, $message, $to) { | |
global $modx; | |
$modx->getService('mail', 'mail.modPHPMailer'); | |
$modx->mail->set(modMail::MAIL_BODY,$message); | |
$modx->mail->set(modMail::MAIL_FROM,$modx->getOption('emailsender')); | |
$modx->mail->set(modMail::MAIL_FROM_NAME,$modx->getOption('site_name')); | |
$modx->mail->set(modMail::MAIL_SUBJECT,$subject); | |
$modx->mail->address('to',$to); | |
$modx->mail->setHTML(true); | |
if (!$modx->mail->send()) { | |
$modx->log(modX::LOG_LEVEL_ERROR,'An error occurred while trying to send the email: '.$modx->mail->mailer->ErrorInfo); | |
} | |
$modx->mail->reset(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment