Compare commits

..

No commits in common. "master" and "v1.0.0" have entirely different histories.

17 changed files with 191 additions and 418 deletions

View file

@ -1,17 +1,80 @@
Legacy (устаревший, не рекомендуется к использованию) Legacy
===================================================== ======
Микрофреймворк для интеграции устаревших платформ (php <= 5.2.17), либо, в случае отсутствия модуля для конкретной платформы. Микрофреймворк для устаревших платформ (php <= 5.2.17), либо, в случае отсутствия
возможности создать модуль для конкретной платформы.
### Документация ### Установка
* Распаковать директорию retailcrm в корень проекта
* На основе файла data/config/settings-dist.ini создать конфигурационный файл data/config/settings.ini
* Создать необходимые sql файлы, файлы с критериями поиска писем и их обработчки (в случае их отсутствия скрипт даст подсказку)
* [Базовая информация](https://github.com/retailcrm/legacy/wiki/%D0%91%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D1%8F-%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%86%D0%B8%D1%8F) ### Настройка
* [Параметры запуска](https://github.com/retailcrm/legacy/wiki/%D0%9F%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B-%D0%B7%D0%B0%D0%BF%D1%83%D1%81%D0%BA%D0%B0) Скрипт выполняет определенные действия в зависимости от переданных параметров.
* [Конфигурация](https://github.com/retailcrm/legacy/wiki/%D0%9A%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D1%8F) Пример параметров можно увидеть, запустив скрипт без них:
* [Принцип работы](https://github.com/retailcrm/legacy/wiki/%D0%9F%D1%80%D0%B8%D0%BD%D1%86%D0%B8%D0%BF-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%8B)
* [Создание SQL файлов и классов обработчиков](https://github.com/retailcrm/legacy/wiki/%D0%A1%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5-SQL-%D1%84%D0%B0%D0%B9%D0%BB%D0%BE%D0%B2-%D0%B8-%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%BE%D0%B2-%D0%BE%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%BE%D0%B2) ```
* [Создание своих и переопределение базовых классов](https://github.com/retailcrm/legacy/wiki/%D0%A1%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5-%D1%81%D0%B2%D0%BE%D0%B8%D1%85-%D0%B8-%D0%BF%D0%B5%D1%80%D0%B5%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B1%D0%B0%D0%B7%D0%BE%D0%B2%D1%8B%D1%85-%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%BE%D0%B2) php app.php
* [Базовые классы](https://github.com/retailcrm/legacy/wiki/%D0%91%D0%B0%D0%B7%D0%BE%D0%B2%D1%8B%D0%B5-%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D1%8B) ```
* [Примеры](https://github.com/retailcrm/legacy/wiki/%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B)
Обмен работает через вызов скрипта по cron, в частности производится:
1. Выгрузка новых заказов из магазина в CRM
2. Выгрузка новых клиентов из магазина в CRM
3. Получение изменений из CRM и запись их в БД сайта
4. Выгрузка каталога товаров в ICML файл
5. Выгрузка справочников (доставки, типы оплат, статусы заказов)
6. Выгрузка заказов из почты
Для этого необходимо создать следующие записи:
```
*/5 * * * * /path/to/php /path/to/retailcrm/app.php -e orders -l
*/5 * * * * /path/to/php /path/to/retailcrm/app.php -e mail -m mail@example.com
*/25 * * * * /path/to/php /path/to/retailcrm/app.php -e customers -l
*/15 * * * * /path/to/php /path/to/retailcrm/app.php -e history
* */6 * * * /path/to/php /path/to/retailcrm/app.php -e icml
* 3 * * * /path/to/php /path/to/retailcrm/app.php -e references
```
В случае, если для консольного окружения нет отдельного php.ini (чаще всего на FreeBSD),
а подключение модулей (mysql.so, dom.so, xmlwriter.so) выполняется отельно, необходимо
при запуске скрипта явно указать путь к php.ini, можно к тому, который используется
при вызове php через libapache-mod-php (путь к нему покажет phpinfo()):
```
*/5 * * * * /path/to/php -c /path/to/php.ini /path/to/retailcrm/app.php -e orders -l
*/15 * * * * /path/to/php -c /path/to/php.ini /path/to/retailcrm/app.php -e history
* */6 * * * /path/to/php -c /path/to/php.ini /path/to/retailcrm/app.php -e icml
```
### Параметры
#### Общие параметры запуска
Общие параметры передаются с помощью ключа -e:
* icml - генерация icml файла
* history - получение истории изменений из CRM для обновления данных в БД сайта
* orders - выгрузка последних заказов (выгружаются заказы, сформированые с момента предыдущего запуска скрипта)
* customers - выгрузка последних клиентов (выгружаются клиенты, не имеющие заказов, сформированые с момента предыдущего запуска скрипта)
* references - выгрузка справочников (по расписанию можно выгружать все справочники, если они доступны)
* mail - выгрузка заказов из почты (выгружаются заказы из писем)
* dump - выгрузка дампа БД
#### Дополнительные параметры запуска
* Ручной запуск с передачей дополнительных параметров для выгрузки конкретного справочника:
```
/usr/bin/php -i /etc/cli/php.ini -f app.php -e reference -r delivery-types
```
* Выгрузка 1 заказа:
```
/usr/bin/php -i /etc/cli/php.ini -f app.php -e orders -p 12345
```
* Выгрузка нескольких клиентов:
```
/usr/bin/php -i /etc/cli/php.ini -f app.php -e customers -p 404,417-423
```

View file

@ -10,9 +10,7 @@ if (
require_once 'bootstrap.php'; require_once 'bootstrap.php';
$shortopts = 'dluce:m:p:r:h:'; $options = getopt('luce:m:p:r:h:');
$options = getopt($shortopts);
if (isset($options['e'])) { if (isset($options['e'])) {
$command = new Command($options); $command = new Command($options);

View file

@ -3,8 +3,7 @@ domain=site.ru
icml_file=retailcrm.xml icml_file=retailcrm.xml
shop_url=http://www.site.ru shop_url=http://www.site.ru
shop_name=Simple Shop shop_name=Simple Shop
support=your_email@example.com support=integration@retailcrm.ru
notify=noreply@example.com
[api] [api]
url=https://demo.retailcrm.ru url=https://demo.retailcrm.ru
@ -19,7 +18,7 @@ driver=mysql
enabled=false enabled=false
[mail] [mail]
mail@example.com=login,password,imap.example.com,993,imap,SpecialFolderName mail@example.com=login,password,imap.example.com,993,imap
mail@example.org=login,password,pop.example.org,995,pop mail@example.org=login,password,pop.example.org,995,pop
enabled=false enabled=false

View file

@ -41,11 +41,11 @@ class CustomersBuilder extends Builder
*/ */
public function buildCustomersById($uidString) public function buildCustomersById($uidString)
{ {
$uids = DataHelper::explodeUids($uidString);
$query = $this->rule->getSQL('customers_uid'); $query = $this->rule->getSQL('customers_uid');
$handler = $this->rule->getHandler('CustomersHandler'); $handler = $this->rule->getHandler('CustomersHandler');
$this->sql = $this->container->db->prepare($query); $this->sql = $this->container->db->prepare($query);
$this->sql->bindParam(':orderIds', $uids); $this->sql->bindParam(':orderIds', $uids);
$uids = DataHelper::explodeUids($uidString);
return $this->build($handler); return $this->build($handler);
} }
@ -74,11 +74,11 @@ class CustomersBuilder extends Builder
*/ */
public function buildCustomersUpdateById($uidString) public function buildCustomersUpdateById($uidString)
{ {
$uids = DataHelper::explodeUids($uidString);
$query = $this->rule->getSQL('customers_update_uid'); $query = $this->rule->getSQL('customers_update_uid');
$handler = $this->rule->getHandler('CustomersHandler'); $handler = $this->rule->getHandler('CustomersHandler');
$this->sql = $this->container->db->prepare($query); $this->sql = $this->container->db->prepare($query);
$this->sql->bindParam(':orderIds', $uids); $this->sql->bindParam(':orderIds', $uids);
$uids = DataHelper::explodeUids($uidString);
return $this->build($handler); return $this->build($handler);
} }

View file

@ -43,8 +43,8 @@ class OrdersBuilder extends Builder
$query = $this->rule->getSQL('orders_uid'); $query = $this->rule->getSQL('orders_uid');
$handler = $this->rule->getHandler('OrdersHandler'); $handler = $this->rule->getHandler('OrdersHandler');
$this->sql = $this->container->db->prepare($query); $this->sql = $this->container->db->prepare($query);
$uids = DataHelper::explodeUids($uidString);
$this->sql->bindParam(':orderIds', $uids); $this->sql->bindParam(':orderIds', $uids);
$uids = DataHelper::explodeUids($uidString);
return $this->build($handler); return $this->build($handler);
} }

View file

@ -10,7 +10,6 @@ class Command
private $limit; private $limit;
private $update; private $update;
private $container; private $container;
private $debug;
public function __construct($arguments) public function __construct($arguments)
{ {
@ -23,7 +22,6 @@ class Command
$this->limit = isset($arguments['l']); $this->limit = isset($arguments['l']);
$this->update = isset($arguments['u']); $this->update = isset($arguments['u']);
$this->custom = isset($arguments['c']); $this->custom = isset($arguments['c']);
$this->debug = isset($arguments['d']);
$this->container = Container::getInstance(); $this->container = Container::getInstance();
@ -42,17 +40,9 @@ class Command
return; return;
} }
$debug = new DebugHelper(); $command = 'run' . ucfirst($this->run);
if ($this->debug) {
$debug->write(sprintf('Start %s', ucfirst($this->run)));
}
$command = sprintf('run%s', ucfirst($this->run)); return $this->$command();
$this->$command();
if ($this->debug) {
$debug->write(sprintf('End %s', ucfirst($this->run)));
}
} }
public function runDump() public function runDump()
@ -62,30 +52,10 @@ class Command
$dbName = $this->container->settings['db']['dbname']; $dbName = $this->container->settings['db']['dbname'];
$dbHost = $this->container->settings['db']['host']; $dbHost = $this->container->settings['db']['host'];
switch ($this->container->settings['db']['driver']) { $dumpfile = $this->container->saveDir . "dbdump.sql.gz";
case 'mysql':
$cmd = sprintf(
'mysqldump -u %s --password=%s --host=%s %s',
$dbUser, $dbPass, $dbHost, $dbName
);
break;
case 'pgsql':
$cmd = sprintf(
'PGPASSWORD=\'%s\' pg_dump -U %s -h %s %s',
$dbPass, $dbUser, $dbHost, $dbName
);
break;
default:
CommandHelper::dumpNotice();
return;
}
passthru( $cmd = "mysqldump -u $dbUser --password=$dbPass --host=$dbHost $dbName | gzip --best > $dumpfile";
sprintf( passthru($cmd);
'%s | gzip --best > %sdbdump.sql.gz',
$cmd, $this->container->saveDir
)
);
} }
public function runIcml() public function runIcml()
@ -221,7 +191,7 @@ class Command
break; break;
case 'payment-statuses': case 'payment-statuses':
$reference = $builder->buildPaymentStatuses(); $reference = $builder->buildPaymentStatuses();
$this->requestHelper->uploadPaymentStatuses($reference); $this->requestHelper->uploadDeliveryStatuses($reference);
break; break;
case 'statuses': case 'statuses':
$reference = $builder->buildStatuses(); $reference = $builder->buildStatuses();
@ -242,7 +212,7 @@ class Command
$this->requestHelper->uploadPaymentTypes($paymentTypes); $this->requestHelper->uploadPaymentTypes($paymentTypes);
$paymentStatuses = $builder->buildPaymentStatuses(); $paymentStatuses = $builder->buildPaymentStatuses();
$this->requestHelper->uploadPaymentStatuses($paymentStatuses); $this->requestHelper->uploadDeliveryStatuses($paymentStatuses);
$statuses = $builder->buildStatuses(); $statuses = $builder->buildStatuses();
$this->requestHelper->uploadStatuses($statuses); $this->requestHelper->uploadStatuses($statuses);
@ -284,10 +254,12 @@ class Command
$handler = $rule->getHandler('AmoHandler'); $handler = $rule->getHandler('AmoHandler');
$data = $handler->prepare($amo); $data = $handler->prepare($amo);
if (!empty($data) && !empty($data['customers'])) { if (!empty($data)) {
$this->requestHelper->uploadCustomers($data['customers']); if (!empty($data['customers'])) {
if (!empty($data['orders'])) { $this->requestHelper->uploadCustomers($data['customers']);
$this->requestHelper->uploadOrders($data['orders'], true); if (!empty($data['orders'])) {
$this->requestHelper->uploadOrders($data['orders'], true);
}
} }
} }
} }

View file

@ -59,7 +59,6 @@ class Container
); );
$this->db->exec("set names utf8"); $this->db->exec("set names utf8");
$this->db->exec("set group_concat_max_len = 1000000");
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) { } catch (PDOException $e) {
CommandHelper::activateNotice('database'); CommandHelper::activateNotice('database');

View file

@ -6,7 +6,7 @@ class Logger
private $push; private $push;
private $files; private $files;
public function __construct($rotate = true, $push = false, $files = 5) public function __construct($rotate = true, $push = true, $files = 5)
{ {
$this->rotate = $rotate; $this->rotate = $rotate;
$this->push = $push; $this->push = $push;
@ -101,9 +101,10 @@ class Logger
{ {
$domain = $this->container->domain; $domain = $this->container->domain;
$recipient = $this->container->support; $recipient = $this->container->support;
$subject = sprintf("Legacy notification from %s", $domain); $subject = 'Legacy notification';
$headers = sprintf("From: %s\r\nX-Mailer: PHP/%s", $this->container->notify, phpversion()); $headers = 'From: noreply@retailcrm.ru' . "\r\n" .
$message = sprintf("New log message from %s:\n\n%s\n", $domain, $message); 'X-Mailer: PHP/' . phpversion();
$message = "New log message from $domain:\n\n$message";
mail($recipient, $subject, $message, $headers); mail($recipient, $subject, $message, $headers);
} }

View file

@ -13,7 +13,7 @@ class Mail
$this->mailBox = $mailBox; $this->mailBox = $mailBox;
if (is_array($this->container->mail)) { if (is_array($this->container->mail)) {
if (isset($this->container->mail[$mailBox])) { if(isset($this->container->mail[$mailBox])) {
$this->mailSettings = explode( $this->mailSettings = explode(
',', ',',
$this->container->mail[$mailBox] $this->container->mail[$mailBox]
@ -32,7 +32,6 @@ class Mail
public function parse() public function parse()
{ {
$server = new Server( $server = new Server(
$this->mailSettings[2], $this->mailSettings[2],
$this->mailSettings[3], $this->mailSettings[3],
@ -44,10 +43,6 @@ class Mail
$this->mailSettings[1] $this->mailSettings[1]
); );
if (!empty($this->mailSettings[5])) {
$server->setMailBox($this->mailSettings[5]);
}
$mailCriteria = $this->clean($this->mailBox, 'criteria'); $mailCriteria = $this->clean($this->mailBox, 'criteria');
$mailHandler = $this->clean($this->mailBox, 'handler'); $mailHandler = $this->clean($this->mailBox, 'handler');

View file

@ -28,10 +28,6 @@ class RequestProxy
if (isset($response['errors'])) { if (isset($response['errors'])) {
foreach ($response['errors'] as $error) { foreach ($response['errors'] as $error) {
if (is_array($error)) {
$error = @implode(', ', $error);
}
$this->logger->write( $this->logger->write(
"[$method] $error \n", "[$method] $error \n",
$this->container->errorLog $this->container->errorLog
@ -46,22 +42,11 @@ class RequestProxy
"[$method] " . $e->getMessage() . "\n", "[$method] " . $e->getMessage() . "\n",
$this->container->errorLog $this->container->errorLog
); );
return null;
} catch (InvalidJsonException $e) { } catch (InvalidJsonException $e) {
$this->logger->write( $this->logger->write(
"[$method] " . $e->getMessage() . "\n", "[$method] " . $e->getMessage() . "\n",
$this->container->errorLog $this->container->errorLog
); );
return null;
} catch (InvalidArgumentException $e) {
$this->logger->write(
"[$method] " . $e->getMessage() . "\n",
$this->container->errorLog
);
return null;
} }
} }
} }

View file

@ -76,15 +76,11 @@ class ApiHelper
$this->logger->put($timemark, $this->container->customersLog); $this->logger->put($timemark, $this->container->customersLog);
} }
public function updateCustomers($customers, $searchEdit = false) public function updateCustomers($customers)
{ {
$timemark = date('Y-m-d H:i:s'); $timemark = date('Y-m-d H:i:s');
foreach ($customers as $customer) { foreach ($customers as $customer) {
if ($searchEdit) { $this->api->ordersEdit($customer);
$this->checkCustomers($customer, true);
} else {
$this->api->customersEdit($customer);
}
time_nanosleep(0, 250000000); time_nanosleep(0, 250000000);
} }
@ -155,7 +151,7 @@ class ApiHelper
return $orders; return $orders;
} }
private function checkCustomers($customer, $searchEdit = false) private function checkCustomers($customer)
{ {
$criteria = array( $criteria = array(
@ -193,11 +189,6 @@ class ApiHelper
$_externalId = $customer['externalId']; $_externalId = $customer['externalId'];
}; };
if ($searchEdit) {
$customer['externalId'] = $_externalId;
$this->api->customersEdit($customer);
}
return $_externalId; return $_externalId;
} }
} else { } else {

View file

@ -5,7 +5,7 @@ class CommandHelper
public static function runHelp() public static function runHelp()
{ {
echo "\n\033[35;2;18mUsage:\033[0m\n"; echo "\n\033[35;2;18mUsage:\033[0m\n";
echo " /usr/bin/php [-c /etc/php5/cli/php.ini] -f app.php -e command [-l] [-u] [-p ids] [-r reference] [-h history] [-m mail@example.com]\n"; echo " /usr/bin/php [-i /etc/php5/cli/php.ini] -f app.php -e command [-l] [-u] [-p ids] [-r reference] [-h history] [-m mail@example.com]\n";
echo "\n\033[35;2;18mCommands:\033[0m\n"; echo "\n\033[35;2;18mCommands:\033[0m\n";
echo " icml\t\tGenerate icml export file\n"; echo " icml\t\tGenerate icml export file\n";
echo " history\tGet data from crm\n"; echo " history\tGet data from crm\n";
@ -25,16 +25,6 @@ class CommandHelper
echo " -h\t\tHistory type, if type is set only this history will be recieved\n"; echo " -h\t\tHistory type, if type is set only this history will be recieved\n";
} }
public static function dumpNotice()
{
echo "\033[0;31mUnfortunately for the database can not be used to make the dump\033[0m\n";
}
public static function notWorkGetOptNotice()
{
echo "\033[0;31mDoes not function getopt. It is used to obtain the parameters from the command line. Please refer to the server administrator.\033[0m\n";
}
public static function updateNotice() public static function updateNotice()
{ {
echo "\033[0;31mFull update is not allowed, please select one of the following flags: limit, set of identifiers or a specific id\033[0m\n"; echo "\033[0;31mFull update is not allowed, please select one of the following flags: limit, set of identifiers or a specific id\033[0m\n";

View file

@ -4,7 +4,7 @@ class DataHelper
{ {
public static function getDate($file) public static function getDate($file)
{ {
if (file_exists($file) && 1 < filesize($file)) { if (file_exists($file)) {
$result = file_get_contents($file); $result = file_get_contents($file);
} else { } else {
$result = date( $result = date(
@ -25,8 +25,6 @@ class DataHelper
if (is_null($haystack[$key]) || $haystack[$key] === '' || count($haystack[$key]) == 0) { if (is_null($haystack[$key]) || $haystack[$key] === '' || count($haystack[$key]) == 0) {
unset($haystack[$key]); unset($haystack[$key]);
} elseif (!is_array($value)) {
$haystack[$key] = trim($value);
} }
} }

View file

@ -1,48 +0,0 @@
<?php
class DebugHelper
{
private $baseMemoryUsage;
private $tusage;
private $rusage;
public function __construct()
{
$this->baseMemoryUsage = memory_get_usage(true);
$proc = getrusage();
$this->tusage = microtime(true);
$this->rusage = $proc['ru_utime.tv_sec'] * 1e6 + $proc['ru_utime.tv_usec'];
}
private function formatSize($size)
{
$postfix = array('b', 'Kb', 'Mb', 'Gb', 'Tb');
$position = 0;
while ($size >= 1024 && $position < 4) {
$size /= 1024;
$position++;
}
return sprintf('%s %s', round($size, 2), $postfix[$position]);
}
public function getMemoryUsage()
{
return $this->formatSize(memory_get_usage(true) - $this->baseMemoryUsage);
}
public function getCpuUsage()
{
$proc = getrusage();
$proc["ru_utime.tv_usec"] = ($proc["ru_utime.tv_sec"] * 1e6 + $proc["ru_utime.tv_usec"]) - $this->rusage;
$time = (microtime(true) - $this->tusage) * 1000000;
return $time > 0 ? sprintf("%01.2f", ($proc["ru_utime.tv_usec"] / $time) * 100) : '0.00';
}
public function write($string)
{
echo sprintf("%s\t%s\t%s%s", $string, $this->getCpuUsage(), $this->getMemoryUsage(), PHP_EOL);
}
}

View file

@ -4,9 +4,20 @@ class IcmlHelper
{ {
protected $shop; protected $shop;
protected $file; protected $file;
protected $tmpFile;
protected $properties = array( protected $properties;
protected $params;
protected $document;
protected $categories;
protected $offers;
public function __construct($shop, $file)
{
$this->shop = $shop;
$this->file = $file;
$this->properties = array(
'name', 'name',
'productName', 'productName',
'price', 'price',
@ -16,196 +27,111 @@ class IcmlHelper
'url', 'url',
'xmlId', 'xmlId',
'productActivity' 'productActivity'
); );
protected $xml; $this->params = array(
protected $categories; 'article' => 'Артикул',
protected $offers; 'color' => 'Цвет',
'weight' => 'Вес',
protected $chunk = 500; 'size' => 'Размер',
protected $fileLifeTime = 3600; );
public function __construct($shop, $file)
{
$this->shop = $shop;
$this->file = $file;
$this->tmpFile = sprintf('%s.tmp', $file);
} }
public function generate($categories, $offers) public function generate($categories, $offers)
{ {
if (file_exists($this->tmpFile)) { $string = '<?xml version="1.0" encoding="UTF-8"?>
if (filectime($this->tmpFile) + $this->fileLifeTime < time()) { <yml_catalog date="'.date('Y-m-d H:i:s').'">
unlink($this->tmpFile); <shop>
$this->writeHead(); <name>'.$this->shop.'</name>
} <categories/>
} else { <offers/>
$this->writeHead(); </shop>
} </yml_catalog>
';
try { $xml = new SimpleXMLElement(
if (!empty($categories)) { $string,
$this->writeCategories($categories); LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
unset($categories);
}
if (!empty($offers)) {
$this->writeOffers($offers);
unset($offers);
}
$dom = dom_import_simplexml(simplexml_load_file($this->tmpFile))->ownerDocument;
$dom->formatOutput = true;
$formatted = $dom->saveXML();
unset($dom, $this->xml);
file_put_contents($this->tmpFile, $formatted);
rename($this->tmpFile, $this->file);
} catch (Exception $e) {
unlink($this->tmpFile);
}
}
private function loadXml()
{
return new SimpleXMLElement(
$this->tmpFile,
LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE,
true
);
}
private function writeHead()
{
$string = sprintf(
'<?xml version="1.0" encoding="UTF-8"?><yml_catalog date="%s"><shop><name>%s</name><categories/><offers/></shop></yml_catalog>',
date('Y-m-d H:i:s'),
$this->shop
); );
file_put_contents($this->tmpFile, $string, LOCK_EX); $this->document = new DOMDocument();
} $this->document->preserveWhiteSpace = false;
$this->document->formatOutput = true;
$this->document->loadXML($xml->asXML());
private function writeCategories($categories) $this->categories = $this->document
{ ->getElementsByTagName('categories')->item(0);
$chunkCategories = array_chunk($categories, $this->chunk); $this->offers = $this->document
foreach ($chunkCategories as $categories) { ->getElementsByTagName('offers')->item(0);
$this->xml = $this->loadXml();
$this->categories = $this->xml->shop->categories; $this->addCategories($categories);
$this->addCategories($categories); $this->addOffers($offers);
$this->xml->asXML($this->tmpFile); $this->document->saveXML();
} $this->document->save($this->file);
unset($this->categories);
}
private function writeOffers($offers)
{
$chunkOffers = array_chunk($offers, $this->chunk);
foreach ($chunkOffers as $offers) {
$this->xml = $this->loadXml();
$this->offers = $this->xml->shop->offers;
$this->addOffers($offers);
$this->xml->asXML($this->tmpFile);
}
unset($this->offers);
} }
private function addCategories($categories) private function addCategories($categories)
{ {
$categories = DataHelper::filterRecursive($categories);
foreach($categories as $category) { foreach($categories as $category) {
if (!array_key_exists('name', $category) || !array_key_exists('id', $category)) { $e = $this->categories->appendChild(
continue; $this->document->createElement(
} 'category', $category['name']
)
);
$e = $this->categories->addChild('category', $category['name']); $e->setAttribute('id', $category['id']);
$e->addAttribute('id', $category['id']); if ($category['parentId'] > 0) {
$e->setAttribute('parentId', $category['parentId']);
if (array_key_exists('parentId', $category) && $category['parentId'] > 0) {
$e->addAttribute('parentId', $category['parentId']);
} }
} }
} }
private function addOffers($offers) private function addOffers($offers)
{ {
$offers = DataHelper::filterRecursive($offers); foreach ($offers as $offer) {
foreach ($offers as $key => $offer) { $e = $this->offers->appendChild(
$this->document->createElement('offer')
);
if (!array_key_exists('id', $offer)) { $e->setAttribute('id', $offer['id']);
continue; $e->setAttribute('productId', $offer['productId']);
}
$e = $this->offers->addChild('offer');
$e->addAttribute('id', $offer['id']);
if (!array_key_exists('productId', $offer) || empty($offer['productId'])) {
$offer['productId'] = $offer['id'];
}
$e->addAttribute('productId', $offer['productId']);
if (!empty($offer['quantity'])) { if (!empty($offer['quantity'])) {
$e->addAttribute('quantity', (int) $offer['quantity']); $e->setAttribute('quantity', (int) $offer['quantity']);
} else { } else {
$e->addAttribute('quantity', 0); $e->setAttribute('quantity', 0);
} }
if (is_array($offer['categoryId'])) { foreach ($offer['categoryId'] as $categoryId) {
foreach ($offer['categoryId'] as $categoryId) { $e->appendChild(
$e->addChild('categoryId', $categoryId); $this->document->createElement('categoryId', $categoryId)
);
}
$offerKeys = array_keys($offer);
foreach ($offerKeys as $key) {
if (in_array($key, $this->properties)) {
$e->appendChild(
$this->document->createElement($key)
)->appendChild(
$this->document->createTextNode($offer[$key])
);
}
if (in_array($key, array_keys($this->params))) {
$param = $this->document->createElement('param');
$param->setAttribute('code', $key);
$param->setAttribute('name', $this->params[$key]);
$param->appendChild(
$this->document->createTextNode($offer[$key])
);
$e->appendChild($param);
} }
} else {
$e->addChild('categoryId', $offer['categoryId']);
} }
if (!array_key_exists('name', $offer) || empty($offer['name'])) {
$offer['name'] = 'Без названия';
}
if (!array_key_exists('productName', $offer) || empty($offer['productName'])) {
$offer['productName'] = $offer['name'];
}
unset($offer['id'], $offer['productId'], $offer['categoryId'], $offer['quantity']);
array_walk($offer, array($this, 'setOffersProperties'), $e);
if (array_key_exists('params', $offer) && !empty($offer['params'])) {
array_walk($offer['params'], array($this, 'setOffersParams'), $e);
}
unset($offers[$key]);
}
}
private function setOffersProperties($value, $key, &$e) {
if (in_array($key, $this->properties) && $key != 'params') {
$e->addChild($key, htmlspecialchars($value));
}
}
private function setOffersParams($value, $key, &$e) {
if (
array_key_exists('code', $value) &&
array_key_exists('name', $value) &&
array_key_exists('value', $value) &&
!empty($value['code']) &&
!empty($value['name']) &&
!empty($value['value'])
) {
$param = $e->addChild('param', htmlspecialchars($value['value']));
$param->addAttribute('code', $value['code']);
$param->addAttribute('name', htmlspecialchars($value['name']));
} }
} }
} }

View file

@ -1,96 +0,0 @@
<?php
class OptHelper
{
private $shortopts = array();
private $longopts = array();
public function __construct($shortopts = '', $longopts = array())
{
if (!empty($shortopts)) {
$this->shortopts = preg_split(
'@([a-z0-9][:]{0,2})@i',
$shortopts, 0,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
}
if (!empty($longopts)) {
$this->longopts = $longopts;
}
}
public function get()
{
if (!array_key_exists('argv', $_SERVER)) {
return false;
}
$result = array();
$params = $_SERVER['argv'];
foreach ($params as $key => $param) {
if ($param{0} == '-') {
$name = substr($param, 1);
$value = true;
if ($name{0} == '-') {
$name = substr($name, 1);
if (strpos($param, '=') !== false) {
$long = explode('=', substr($param, 2), 2);
$name = $long[0];
$value = $long[1];
unset($value);
}
}
if (
isset($params[$key + 1]) &&
$value === true &&
$params[$key + 1] !== false &&
$params[$key + 1]{0} != '-'
) {
$value = $params[$key + 1];
}
$result[$name] = $value;
} else {
$result[] = $param;
}
}
unset($params);
return empty($result) ? false : $this->filter($result);
}
private function filter($params)
{
$result = array();
$opts = array_merge($this->shortopts, $this->longopts);
foreach ($opts as $opt) {
if (substr($opt, -2) === '::') {
$key = substr($opt, 0, -2);
if (isset($params[$key]) && !empty($params[$key])) {
$result[$key] = $params[$key];
} elseif (isset($params[$key])) {
$result[$key] = true;
}
} elseif (substr($opt, -1) === ':') {
$key = substr($opt, 0, -1);
if (isset($params[$key]) && !empty($params[$key])) {
$result[$key] = $params[$key];
}
} elseif (ctype_alnum($opt) && isset($params[$opt])) {
$result[$opt] = true;
}
}
return $result;
}
}

View file

@ -380,7 +380,7 @@ class Server
public function getMessageByUid($uid) public function getMessageByUid($uid)
{ {
try { try {
$message = new Message($uid, $this); $message = new Fetch\Message($uid, $this);
return $message; return $message;
} catch (\Exception $e) { } catch (\Exception $e) {