mirror of
https://github.com/retailcrm/legacy.git
synced 2025-04-11 05:00:57 +00:00
Compare commits
52 commits
Author | SHA1 | Date | |
---|---|---|---|
|
095ebf61f1 | ||
|
1436213f1c | ||
|
59fc87a0c5 | ||
|
be7345aaaa | ||
|
5d91549f01 | ||
|
b3a041482e | ||
|
3e08653ca9 | ||
|
3d3a3b72ab | ||
|
34996d2b84 | ||
|
d6dad7bd4d | ||
|
56ec1a7247 | ||
|
d19f9f7699 | ||
|
7d7494ae64 | ||
|
2f9596be2b | ||
|
e836c6ae64 | ||
|
f21576b2c2 | ||
|
6f958c739b | ||
|
1648e9f178 | ||
|
623416a85c | ||
|
e8c219ce4f | ||
|
c25617ff45 | ||
|
1fd90324ca | ||
|
1ddffd8085 | ||
|
fff8918c60 | ||
|
73f8464a34 | ||
|
07e172858b | ||
|
a0c9e4eaa2 | ||
|
d579aafdc5 | ||
|
4556d3e85b | ||
|
6d27598157 | ||
|
87d972b142 | ||
|
2d1aceb100 | ||
|
b079105b4f | ||
|
76c07136db | ||
|
1d2ca95216 | ||
|
5fe9ed3045 | ||
|
9a2bbce480 | ||
|
c672c93554 | ||
|
d8f6fee0b9 | ||
|
4dc0d2130b | ||
|
bc668cfde7 | ||
|
435081dbb6 | ||
|
e796ab3ed0 | ||
|
318dbc9682 | ||
|
f25a3937dc | ||
|
af8ec4657a | ||
|
4803d0758f | ||
|
057de9af6f | ||
|
2b7d0f1436 | ||
|
762cd0ab97 | ||
|
ae8b4bf87b | ||
|
1c6c970978 |
17 changed files with 418 additions and 191 deletions
87
README.md
87
README.md
|
@ -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)
|
||||
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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');
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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');
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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";
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
48
retailcrm/src/Helpers/DebugHelper.php
Normal file
48
retailcrm/src/Helpers/DebugHelper.php
Normal 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);
|
||||
}
|
||||
}
|
|
@ -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']));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
96
retailcrm/src/Helpers/OptHelper.php
Normal file
96
retailcrm/src/Helpers/OptHelper.php
Normal 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;
|
||||
}
|
||||
}
|
2
retailcrm/src/Vendor/Fetch/Server.php
vendored
2
retailcrm/src/Vendor/Fetch/Server.php
vendored
|
@ -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) {
|
||||
|
|
Loading…
Add table
Reference in a new issue