Compare commits

...

52 commits

Author SHA1 Message Date
Alex Lushpai
095ebf61f1
Update README.md 2020-02-19 17:36:16 +03:00
Alex Lushpai
1436213f1c
Update Logger.php 2017-12-27 10:34:40 +03:00
Alex Lushpai
59fc87a0c5
Update settings-dist.ini 2017-12-27 10:31:18 +03:00
Alex Lushpai
be7345aaaa
Update Logger.php 2017-12-27 09:59:54 +03:00
Alex Lushpai
5d91549f01 Update settings-dist.ini 2017-08-10 11:34:26 +03:00
Alex Lushpai
b3a041482e Merge pull request #15 from cherginets/15-fix-group-concat
fix group concat setting
2016-09-05 16:49:55 +03:00
Anton Cherginets
3e08653ca9 fix group concat setting 2016-09-05 16:36:13 +03:00
Alex Lushpai
3d3a3b72ab Merge pull request #14 from VitalyArt/bugfix
fix uploadPaymentStatuses
2016-08-19 11:52:20 +03:00
Vitaly Artemev
34996d2b84 fix uploadPaymentStatuses 2016-08-19 12:49:44 +04:00
Alex Lushpai
d6dad7bd4d Merge pull request #13 from VitalyArt/bugfix
Bugfix
2016-08-19 11:28:10 +03:00
Vitaly Artemev
56ec1a7247 fix explodeUids 2016-08-09 11:14:58 +04:00
Vitaly Artemev
d19f9f7699 fix uploadPaymentStatuses 2016-08-09 10:48:51 +04:00
Alex Lushpai
7d7494ae64 Merge pull request #12 from cyradin/master
fix catalog export bug
2016-04-11 02:37:09 +04:00
cyradin
2f9596be2b fix catalog export bug 2016-03-25 19:52:31 +03:00
Alex Lushpai
e836c6ae64 Merge pull request #11 from gwinn/master
nvalidArgumentException, custom mail folder
2016-03-15 13:03:43 +03:00
Alex Lushpai
f21576b2c2 fix after upstream merge 2016-03-15 13:02:31 +03:00
Alex Lushpai
6f958c739b exception, custom mail folder 2016-03-15 12:59:19 +03:00
Alex Lushpai
1648e9f178 Update RequestProxy.php 2016-03-14 12:25:32 +03:00
Alex Lushpai
623416a85c Update Container.php 2016-02-16 16:17:18 +03:00
Alex Lushpai
e8c219ce4f Merge pull request #8 from VitalyArt/bugfix
fix namespace
2016-02-10 23:14:42 +03:00
Alex Lushpai
c25617ff45 Merge pull request #9 from gwinn/master
Bugfixes
2016-02-10 23:14:22 +03:00
Alex Lushpai
1fd90324ca temporary disable OptHelper
fix getDate method (add file not empty check)
2016-02-10 23:13:02 +03:00
Vitaly Artemev
1ddffd8085 fix namespace 2016-02-02 15:16:58 +03:00
Alex Lushpai
fff8918c60 Merge pull request #7 from gwinn/master
doc fix
2016-01-15 13:11:18 +03:00
Alex Lushpai
73f8464a34 Merge branch 'master' of github.com:gwinn/legacy 2016-01-15 12:53:41 +03:00
Alex Lushpai
07e172858b fix typo for help option 2016-01-15 12:53:31 +03:00
Alex Lushpai
a0c9e4eaa2 Merge pull request #6 from liven/patch-1
Update ApiHelper.php
2015-12-21 16:24:16 +03:00
Vasily
d579aafdc5 Update ApiHelper.php 2015-12-21 16:09:53 +03:00
Alex Lushpai
4556d3e85b Merge pull request #5 from dmamontov/master
add custom getopt & orders builder fix
2015-11-26 12:41:53 +03:00
Dmitry Mamontov
6d27598157 fix buildOrdersById 2015-11-26 04:37:39 -05:00
Dmitry Mamontov
87d972b142 refactoring custom getopt && add lonoptions 2015-11-24 04:37:32 -05:00
Dmitry Mamontov
2d1aceb100 refactoring custom getopt 2015-11-23 10:01:46 -05:00
Dmitry Mamontov
b079105b4f add custom getopt 2015-11-23 09:31:55 -05:00
Alex Lushpai
76c07136db Merge pull request #4 from dmamontov/master
add support for pgsql dump
2015-11-18 10:35:06 +03:00
Dmitry Mamontov
1d2ca95216 add support dump pgsql 2015-11-17 15:51:37 -05:00
Alex Lushpai
5fe9ed3045 Merge pull request #3 from dmamontov/master
fix memory usage
2015-11-16 18:13:19 +03:00
Dmitry Mamontov
9a2bbce480 refactoring icml && fix memory usage 2015-11-16 10:03:22 -05:00
Dmitry Mamontov
c672c93554 fix concat 2015-11-16 10:02:44 -05:00
Dmitry Mamontov
d8f6fee0b9 add debug mode 2015-11-16 09:45:35 -05:00
Alex Lushpai
4dc0d2130b Update README.md 2015-11-13 14:11:27 +03:00
Alex Lushpai
bc668cfde7 Merge pull request #2 from dmamontov/master
refactoring icml
2015-11-13 14:10:16 +03:00
Dmitry Mamontov
435081dbb6 refactoring icml 2015-11-12 09:26:04 -05:00
Dmitry Mamontov
e796ab3ed0 fix name 2015-11-12 08:14:28 -05:00
Dmitry Mamontov
318dbc9682 fix notice && category generate offers 2015-11-12 08:09:48 -05:00
Dmitry Mamontov
f25a3937dc fix motice generate category 2015-11-12 07:56:31 -05:00
Alex Lushpai
af8ec4657a Merge pull request #1 from dmamontov/master
fix api error parse, add trim in filter, add search edit in updateCustomers
2015-10-30 14:30:50 +03:00
Dmitry Mamontov
4803d0758f add search edit in updateCustomers 2015-10-30 07:26:09 -04:00
Dmitry Mamontov
057de9af6f fix api error parse 2015-10-30 07:23:20 -04:00
Dmitry Mamontov
2b7d0f1436 add trim in filter 2015-10-30 07:22:00 -04:00
Alex Lushpai
762cd0ab97 Update README.md 2015-10-30 12:10:58 +03:00
Alex Lushpai
ae8b4bf87b Update README.md 2015-10-30 12:09:50 +03:00
Alex Lushpai
1c6c970978 Update README.md 2015-10-30 11:37:54 +03:00
17 changed files with 418 additions and 191 deletions

View file

@ -1,80 +1,17 @@
Legacy
======
Legacy (устаревший, не рекомендуется к использованию)
=====================================================
Микрофреймворк для устаревших платформ (php <= 5.2.17), либо, в случае отсутствия
возможности создать модуль для конкретной платформы.
Микрофреймворк для интеграции устаревших платформ (php <= 5.2.17), либо, в случае отсутствия модуля для конкретной платформы.
### Установка
* Распаковать директорию retailcrm в корень проекта
* На основе файла data/config/settings-dist.ini создать конфигурационный файл data/config/settings.ini
* Создать необходимые sql файлы, файлы с критериями поиска писем и их обработчки (в случае их отсутствия скрипт даст подсказку)
### Документация
### Настройка
Скрипт выполняет определенные действия в зависимости от переданных параметров.
Пример параметров можно увидеть, запустив скрипт без них:
```
php app.php
```
Обмен работает через вызов скрипта по 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
```
* [Базовая информация](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)
* [Базовые классы](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)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,7 +5,7 @@ class CommandHelper
public static function runHelp()
{
echo "\n\033[35;2;18mUsage:\033[0m\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 " /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 "\n\033[35;2;18mCommands:\033[0m\n";
echo " icml\t\tGenerate icml export file\n";
echo " history\tGet data from crm\n";
@ -25,6 +25,16 @@ class CommandHelper
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()
{
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)
{
if (file_exists($file)) {
if (file_exists($file) && 1 < filesize($file)) {
$result = file_get_contents($file);
} else {
$result = date(
@ -25,6 +25,8 @@ class DataHelper
if (is_null($haystack[$key]) || $haystack[$key] === '' || count($haystack[$key]) == 0) {
unset($haystack[$key]);
} elseif (!is_array($value)) {
$haystack[$key] = trim($value);
}
}

View file

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

@ -0,0 +1,96 @@
<?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)
{
try {
$message = new Fetch\Message($uid, $this);
$message = new Message($uid, $this);
return $message;
} catch (\Exception $e) {