Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
yandexcampaign.php
1<?php
2namespace Bitrix\Seo\Adv;
3
10
11Loc::loadMessages(__FILE__);
12
44{
45 const ENGINE = 'yandex_direct';
46
47 const STRATEGY_WEEKLY_BUDGET = 'WeeklyBudget';
48 const STRATEGY_WEEKLY_PACKET_OF_CLICKS = 'WeeklyPacketOfClicks';
49 const STRATEGY_AVERAGE_CLICK_PRICE = 'AverageClickPrice';
50
53
54 const CACHE_LIFETIME = 3600;
55
56 public static $allowedWarnPlaceIntervalValues = array(15, 30, 60);
57 public static $allowedMoneyWarningInterval = array(1, 50);
58 public static $supportedStrategy = array(
59 "WEEKLY_BUDGET" => self::STRATEGY_WEEKLY_BUDGET,
60 "WEEKLY_PACKET_OF_CLICKS" => self::STRATEGY_WEEKLY_PACKET_OF_CLICKS,
61 "AVERAGE_CLICK_PRICE" => self::STRATEGY_AVERAGE_CLICK_PRICE,
62 );
63
64 public static $strategyConfig = array(
65 self::STRATEGY_WEEKLY_BUDGET => array(
66 'WeeklySumLimit' => array(
67 'type' => 'float',
68 'mandatory' => true,
69 ),
70 'MaxPrice' => array(
71 'type' => 'float',
72 'mandatory' => false,
73 ),
74 ),
75 self::STRATEGY_WEEKLY_PACKET_OF_CLICKS => array(
76 'ClicksPerWeek' => array(
77 'type' => 'int',
78 'mandatory' => true,
79 ),
80 'MaxPrice' => array(
81 'type' => 'float',
82 'mandatory' => false,
83 ),
84 'AveragePrice' => array(
85 'type' => 'float',
86 'mandatory' => false,
87 ),
88 ),
89 self::STRATEGY_AVERAGE_CLICK_PRICE => array(
90 'AveragePrice' => array(
91 'type' => 'float',
92 'mandatory' => true,
93 ),
94 'WeeklySumLimit' => array(
95 'type' => 'float',
96 'mandatory' => false,
97 ),
98 ),
99 );
100
101 private static $engine = null;
102
108 public static function getFilePath()
109 {
110 return __FILE__;
111 }
112
118 public static function getTableName()
119 {
120 return 'b_seo_adv_campaign';
121 }
122
128 public static function getEngine()
129 {
130 if(!self::$engine)
131 {
132 self::$engine = new Engine\YandexDirect();
133 }
134 return self::$engine;
135 }
136
148 public static function onBeforeAdd(Entity\Event $event)
149 {
150 $result = new Entity\EventResult();
151
152 $data = $event->getParameter("fields");
153
154 $engine = self::getEngine();
155
156 $ownerInfo = $engine->getCurrentUser();
157
158 if(!static::$skipRemoteUpdate)
159 {
160 $data["SETTINGS"] = self::createParam($engine, $data, $result);
161 $data["XML_ID"] = 'Error';
162 }
163 else
164 {
165 $data["XML_ID"] = $data["SETTINGS"]["CampaignID"];
166 }
167
168 $data["NAME"] = $data["SETTINGS"]["Name"];
169
170 $data["ENGINE_ID"] = $engine->getId();
171
172 $data['OWNER_ID'] = $ownerInfo['id'];
173 $data['OWNER_NAME'] = $ownerInfo['login'];
174
175 if(!static::$skipRemoteUpdate && $result->getType() == Entity\EventResult::SUCCESS)
176 {
177 try
178 {
179 $data["XML_ID"] = $engine->addCampaign($data["SETTINGS"]);
180
181 $campaignSettings = $engine->getCampaign(array($data['XML_ID']));
182 $data['SETTINGS'] = $campaignSettings[0];
183 }
185 {
186 $result->addError(new Entity\FieldError(
187 static::getEntity()->getField('ENGINE_ID'),
188 $e->getMessage(),
189 $e->getCode()
190 ));
191 }
192 }
193
194 $data['LAST_UPDATE'] = new Main\Type\DateTime();
195 $data['ACTIVE'] = $data['SETTINGS']['StatusArchive'] == Engine\YandexDirect::BOOL_YES
196 ? static::INACTIVE
197 : static::ACTIVE;
198
199 $result->modifyFields($data);
200
201 return $result;
202 }
203
215 public static function onBeforeUpdate(Entity\Event $event)
216 {
217 $result = new Entity\EventResult();
218
219 $primary = $event->getParameter("primary");
220 $data = $event->getParameter("fields");
221
222 $currentData = static::getByPrimary($primary);
223 $currentData = $currentData->fetch();
224
225 if($currentData)
226 {
227 $engine = self::getEngine();
228
229 if($currentData['ENGINE_ID'] != $engine->getId())
230 {
231 $result->addError(new Entity\FieldError(
232 static::getEntity()->getField('ENGINE_ID'),
233 Loc::getMessage("SEO_CAMPAIGN_ERROR_WRONG_ENGINE")
234 ));
235 }
236
237 $ownerInfo = $engine->getCurrentUser();
238
239 if($currentData['OWNER_ID'] != $ownerInfo['id'])
240 {
241 $result->addError(new Entity\FieldError(
242 static::getEntity()->getField('OWNER_ID'),
243 Loc::getMessage("SEO_CAMPAIGN_ERROR_WRONG_OWNER")
244 ));
245 }
246
247 $data['OWNER_NAME'] = $ownerInfo['login'];
248 $data['XML_ID'] = $currentData['XML_ID'];
249
250 if(!static::$skipRemoteUpdate)
251 {
252 $data["SETTINGS"] = self::createParam($engine, $data, $result);
253 }
254
255 $data["NAME"] = $data['SETTINGS']['Name'];
256
257 if(!static::$skipRemoteUpdate && $result->getType() == Entity\EventResult::SUCCESS)
258 {
259 try
260 {
261 $engine->updateCampaign($data["SETTINGS"]);
262
263 $campaignSettings = $engine->getCampaign(array($data['XML_ID']));
264 $data['SETTINGS'] = $campaignSettings[0];
265 }
267 {
268 $result->addError(
269 new Entity\FieldError(
270 static::getEntity()->getField('ENGINE_ID'),
271 $e->getMessage(),
272 $e->getCode()
273 )
274 );
275 }
276 }
277
278 $data['LAST_UPDATE'] = new Main\Type\DateTime();
279 $data['ACTIVE'] = $data['SETTINGS']['StatusArchive'] == Engine\YandexDirect::BOOL_YES
280 ? static::INACTIVE
281 : static::ACTIVE;
282
283 $result->modifyFields($data);
284 }
285
286 return $result;
287 }
288
299 public static function onDelete(Entity\Event $event)
300 {
301 $primary = $event->getParameter("primary");
302
303 $dbRes = static::getByPrimary($primary);
304 $campaign = $dbRes->fetch();
305
306 $engine = self::getEngine();
307
308 if($campaign && $campaign['ENGINE_ID'] == $engine->getId())
309 {
310 if(!static::$skipRemoteUpdate)
311 {
312 $engine->deleteCampaign($campaign['XML_ID']);
313 }
314 }
315 }
316
326 public static function onAfterDelete(Entity\Event $event)
327 {
328 $primary = $event->getParameter("primary");
329
330 $engine = self::getEngine();
331
332 $dbRes = YandexBannerTable::getList(array(
333 'filter' => array(
334 '=CAMPAIGN_ID' => $primary,
335 '=ENGINE_ID' => $engine->getId(),
336 ),
337 'select' => array('ID')
338 ));
339
341 while($banner = $dbRes->fetch())
342 {
343 YandexBannerTable::delete($banner['ID']);
344 }
346 }
347
382 protected static function createParam(Engine\YandexDirect $engine, array $data, Entity\EventResult $result)
383 {
384 $settings = $engine->getSettings();
385
386 $campaignParam = array(
387 "Login" => $settings["AUTH_USER"]["login"],
388 );
389
390 $newCampaign = true;
391
392 if(!empty($data["XML_ID"]))
393 {
394 $newCampaign = false;
395 $campaignParam["CampaignID"] = $data["XML_ID"];
396 }
397
398 if($newCampaign || isset($data['SETTINGS']["Name"]))
399 {
400 $campaignParam["Name"] = trim($data['SETTINGS']["Name"]);
401 if($campaignParam["Name"] == '')
402 {
403 $result->addError(new Entity\FieldError(
404 static::getEntity()->getField('NAME'),
405 Loc::getMessage('SEO_CAMPAIGN_ERROR_NO_NAME')
406 ));
407 }
408 }
409
410 if($newCampaign || isset($data["SETTINGS"]["FIO"]))
411 {
412 $campaignParam["FIO"] = trim($data["SETTINGS"]["FIO"]);
413
414 if($campaignParam["FIO"] == '')
415 {
416 $result->addError(new Entity\FieldError(
417 static::getEntity()->getField('SETTINGS'),
418 Loc::getMessage('SEO_CAMPAIGN_ERROR_NO_FIO')
419 ));
420 }
421 }
422
423 if(is_array($data["SETTINGS"]) && array_key_exists("StartDate", $data["SETTINGS"]))
424 {
425 if(is_a($data["SETTINGS"]["StartDate"], "Bitrix\\Main\\Type\\Date"))
426 {
427 $campaignParam["StartDate"] = $data["SETTINGS"]["StartDate"]->convertFormatToPhp("Y-m-d");
428 }
429 elseif(is_string($data["SETTINGS"]["StartDate"]))
430 {
431 if(preg_match("/^\\d{4}-\\d{2}-\\d{2}$/", $data["SETTINGS"]["StartDate"]))
432 {
433 $campaignParam["StartDate"] = $data["SETTINGS"]["StartDate"];
434 }
435 else
436 {
437 $ts = MakeTimeStamp($data["SETTINGS"]["StartDate"], FORMAT_DATE);
438 if($ts > 0)
439 {
440 $campaignParam["StartDate"] = date('Y-m-d', $ts);
441 }
442 }
443 }
444
445 if(!$campaignParam["StartDate"])
446 {
447 $result->addError(new Entity\FieldError(
448 static::getEntity()->getField('SETTINGS'),
449 Loc::getMessage('SEO_CAMPAIGN_ERROR_NO_START_DATE')
450 ));
451 }
452 }
453
454 if($newCampaign || isset($data["SETTINGS"]["Strategy"]))
455 {
456 if(
457 empty($data["SETTINGS"]["Strategy"])
458 || !is_array($data["SETTINGS"]["Strategy"])
459 || empty($data["SETTINGS"]["Strategy"]["StrategyName"])
460 )
461 {
462 $result->addError(new Entity\FieldError(
463 static::getEntity()->getField('SETTINGS'),
464 Loc::getMessage('SEO_CAMPAIGN_ERROR_NO_STRATEGY')
465 ));
466 }
467
468 if(array_key_exists($data["SETTINGS"]["Strategy"]["StrategyName"], self::$strategyConfig))
469 {
470 $strategy = $data["SETTINGS"]["Strategy"]["StrategyName"];
471 $config = self::$strategyConfig[$strategy];
472
473 $campaignParam["Strategy"] = array(
474 "StrategyName" => $strategy,
475 );
476
477 foreach($data["SETTINGS"]["Strategy"] as $param => $value)
478 {
479 if($param !== "StrategyName")
480 {
481 if(array_key_exists($param, $config))
482 {
483 $campaignParam["Strategy"][$param] = $value;
484 }
485 else
486 {
487 $result->addError(new Entity\FieldError(
488 static::getEntity()->getField('SETTINGS'),
490 'SEO_CAMPAIGN_ERROR_STRATEGY_PARAM_NOT_SUPPORTED',
491 array(
492 '#PARAM#' => $param,
493 '#STRATEGY#' => $strategy,
494 )
495 )
496 ));
497 }
498 }
499 }
500
501 foreach($config as $key => $def)
502 {
503 if($def['mandatory'] || isset($campaignParam["Strategy"][$key]))
504 {
505 switch($def['type'])
506 {
507 case 'int':
508 $campaignParam["Strategy"][$key] = intval($campaignParam["Strategy"][$key]);
509 break;
510 case 'float':
511 $campaignParam["Strategy"][$key] = doubleval($campaignParam["Strategy"][$key]);
512 break;
513 }
514
515 if(!$def['mandatory'] && empty($campaignParam["Strategy"][$key]))
516 {
517 unset($campaignParam["Strategy"][$key]);
518 }
519 }
520
521 if($def['mandatory'] && empty($campaignParam["Strategy"][$key]))
522 {
523 $result->addError(new Entity\FieldError(
524 static::getEntity()->getField('SETTINGS'),
526 'SEO_CAMPAIGN_ERROR_STRATEGY_PARAM_MANDATORY',
527 array(
528 '#PARAM#' => Loc::getMessage('SEO_CAMPAIGN_STRATEGY_PARAM_'.ToUpper($key)),
529 '#STRATEGY#' => Loc::getMessage('SEO_CAMPAIGN_STRATEGY_'.$strategy),
530 )
531 )
532 ));
533 }
534 }
535 }
536 else
537 {
538 $result->addError(new Entity\FieldError(
539 static::getEntity()->getField('SETTINGS'),
541 'SEO_CAMPAIGN_ERROR_STRATEGY_NOT_SUPPORTED',
542 array(
543 '#STRATEGY#' => $data["SETTINGS"]["Strategy"]["StrategyName"],
544 )
545 )
546 ));
547 }
548 }
549
550 if($newCampaign || !empty($data["SETTINGS"]["EmailNotification"]))
551 {
552 if(
553 empty($data["SETTINGS"]["EmailNotification"])
554 || !is_array($data["SETTINGS"]["EmailNotification"])
555 || !check_email($data["SETTINGS"]["EmailNotification"]['Email'])
556 )
557 {
558 $result->addError(new Entity\FieldError(
559 static::getEntity()->getField('SETTINGS'),
560 Loc::getMessage('SEO_CAMPAIGN_ERROR_WRONG_EMAIL')
561 ));
562 }
563
564 $campaignParam["EmailNotification"] = array(
565 "Email" => trim($data["SETTINGS"]["EmailNotification"]['Email']),
566 "WarnPlaceInterval" => intval($data["SETTINGS"]["EmailNotification"]['WarnPlaceInterval']),
567 "MoneyWarningValue" => intval($data["SETTINGS"]["EmailNotification"]['MoneyWarningValue']),
568 "SendWarn" => intval($data["SETTINGS"]["EmailNotification"]['SendWarn']),
569 );
570
571 if($campaignParam["EmailNotification"]['SendWarn'] === true
572 || $campaignParam["EmailNotification"]['SendWarn'] === 1
573 || $campaignParam["EmailNotification"]['SendWarn'] === 'Y'
574 )
575 {
576 $campaignParam["EmailNotification"]['SendWarn'] = Engine\YandexDirect::BOOL_YES;
577 }
578
579 if(
580 $campaignParam["EmailNotification"]['SendWarn'] === false
581 || $campaignParam["EmailNotification"]['SendWarn'] === 0
582 || $campaignParam["EmailNotification"]['SendWarn'] === 'N'
583 )
584 {
585 $campaignParam["EmailNotification"]['SendWarn'] = Engine\YandexDirect::BOOL_NO;
586 }
587
588 if(!in_array($campaignParam["EmailNotification"]["WarnPlaceInterval"], self::$allowedWarnPlaceIntervalValues))
589 {
590 if($campaignParam["EmailNotification"]['SendWarn'] == Engine\YandexDirect::BOOL_YES)
591 {
592 $result->addError(new Entity\FieldError(
593 static::getEntity()->getField('SETTINGS'),
595 'SEO_CAMPAIGN_ERROR_WRONG_INTERVAL',
596 array('#VALUES#' => implode(
597 ',', self::$allowedWarnPlaceIntervalValues
598 ))
599 )
600 ));
601 }
602 else
603 {
604 $campaignParam["EmailNotification"]["WarnPlaceInterval"] = self::MONEY_WARN_PLACE_INTERVAL_DEFAULT;
605 }
606 }
607
608 if(
609 $campaignParam["EmailNotification"]["MoneyWarningValue"] < self::$allowedMoneyWarningInterval[0]
610 || $campaignParam["EmailNotification"]["MoneyWarningValue"] > self::$allowedMoneyWarningInterval[1]
611 )
612 {
613 $result->addError(new Entity\FieldError(
614 static::getEntity()->getField('SETTINGS'),
616 'SEO_CAMPAIGN_ERROR_WRONG_WARNING',
617 array(
618 '#MIN#' => self::$allowedMoneyWarningInterval[0],
619 '#MAX#' => self::$allowedMoneyWarningInterval[1],
620 )
621 )
622 ));
623 }
624 }
625
626 if($newCampaign || isset($data["SETTINGS"]["MinusKeywords"]))
627 {
628 if(!is_array($data["SETTINGS"]["MinusKeywords"]))
629 {
630 if($data["SETTINGS"]["MinusKeywords"] <> '')
631 {
632 $data["SETTINGS"]["MinusKeywords"] = array();
633 }
634 else
635 {
636 $data["SETTINGS"]["MinusKeywords"] = array($data["SETTINGS"]["MinusKeywords"]);
637 }
638 }
639
640 $campaignParam["MinusKeywords"] = $data["SETTINGS"]["MinusKeywords"];
641 }
642
643 if(!$newCampaign && $result->getType() == Entity\EventResult::SUCCESS)
644 {
645 try
646 {
647 $yandexCampaignParam = $engine->getCampaign($data["XML_ID"]);
648
649 if(!is_array($yandexCampaignParam) || count($yandexCampaignParam) <= 0)
650 {
651 $result->addError(new Entity\FieldError(
652 static::getEntity()->getField('XML_ID'),
654 'SEO_CAMPAIGN_ERROR_CAMPAIGN_NOT_FOUND',
655 array('#ID#' => $data["XML_ID"])
656 )
657 ));
658 }
659 else
660 {
661 $campaignParam = array_replace_recursive($yandexCampaignParam[0], $campaignParam);
662 }
663 }
665 {
666 $result->addError(
667 new Entity\FieldError(
668 static::getEntity()->getField('ENGINE_ID'),
669 $e->getMessage(),
670 $e->getCode()
671 )
672 );
673 }
674 }
675
676 return $campaignParam;
677 }
678}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static onDelete(Entity\Event $event)
static onBeforeUpdate(Entity\Event $event)
static createParam(Engine\YandexDirect $engine, array $data, Entity\EventResult $result)
static onBeforeAdd(Entity\Event $event)
static onAfterDelete(Entity\Event $event)
static setSkipRemoteUpdate($value)
Definition adventity.php:88