Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
vk.php
1<?php
2
4
12
13Loc::loadMessages(__FILE__);
14
19class Vk extends Platform
20{
22 private $accessToken;
23 private $api = array();
24 private $executer = array();
25
26 const OAUTH_URL = "https://oauth.vk.com/authorize";
27 const TOKEN_URL = "https://oauth.vk.com/access_token";
28 const VK_URL = 'https://vk.com/';
29 const VK_URL__MARKET_PREFIX = 'market-';
30 const VK_URL__ALBUM_PREFIX = '?section=album_';
31
32 const GROUP_GET_STEP = 1000;
34 const MAX_ALBUMS = 100;
35 const MAX_PRODUCTS = 15000;
37 const PRODUCTS_GET_STEP = 200;
40 const MAX_VK_CATEGORIES = 1000;
41
44 const MAX_ALBUM_PHOTO_SIZES_SUM = 14000; //sum height and width
45 const MAX_ALBUM_PHOTO_SIZE = 52428800; //Bites
46 const MAX_ALBUM_RATIO_V = 0.25; // width / height
48
51 const MAX_PRODUCT_PHOTO_SIZES_SUM = 14000; //sum height and width
52 const MAX_PRODUCT_PHOTO_SIZE = 52428800; //Bites
53 const MAX_PRODUCT_RATIO_V = 0.1; // width / height
55
56 const DEFAULT_TIMELIMIT = 40; //seconds
58
59 const VERY_DEFAULT_VK_CATEGORY = 1; //very very default, not true, but only for preserve errors
60 const VK_CATEGORY_TO_CHANGE = -1; //category "change category"
61
68 public static function getInstance()
69 {
70 return parent::getInstanceByCode(self::TRADING_PLATFORM_CODE);
71 }
72
80 public function getSettings($exportId = NULL)
81 {
82 $filter = array();
83 if ($exportId)
84 $filter["=ID"] = $exportId;
85
86 $settings = array();
87 $profiles = ExportProfileTable::getList(array('filter' => $filter));
88 while ($profile = $profiles->fetch())
89 {
90 $settings[$profile["ID"]] = array(
91 'DESCRIPTION' => $profile['DESCRIPTION'],
92 'VK_SETTINGS' => $profile['VK_SETTINGS'],
93 'EXPORT_SETTINGS' => $profile['EXPORT_SETTINGS'],
94 'OAUTH' => $profile['OAUTH'],
95 'PROCESS' => $profile['PROCESS'],
96 );
97 }
98
99// only one profile if required
100 if ($exportId)
101 $settings = $settings[$exportId];
102
103 return $settings;
104 }
105
114 public function saveSettings(array $settings)
115 {
116 $exportId = isset($settings['EXPORT_ID']) ? $settings['EXPORT_ID'] : NULL;
117 $settings = $settings['SETTINGS'];
118
119 $settingsToSave = array();
120 if (isset($settings["DESCRIPTION"]))
121 $settingsToSave["DESCRIPTION"] = $settings["DESCRIPTION"];
122
123 if (isset($settings["VK_SETTINGS"]))
124 $settingsToSave["VK_SETTINGS"] = $settings["VK_SETTINGS"];
125
126 if (isset($settings["EXPORT_SETTINGS"]))
127 $settingsToSave["EXPORT_SETTINGS"] = $settings["EXPORT_SETTINGS"];
128
129 if (isset($settings["OAUTH"]))
130 $settingsToSave["OAUTH"] = $settings["OAUTH"];
131
132 if (isset($settings["PROCESS"]))
133 $settingsToSave["PROCESS"] = $settings["PROCESS"];
134
135// check UPDATE or ADD
136 $settingsExists = $this->getSettings();
137 if ($exportId && array_key_exists($exportId, $settingsExists))
138 {
139 $resUpdate = ExportProfileTable::update($exportId, $settingsToSave);
140
141 return $resUpdate->isSuccess() && $resUpdate->getAffectedRowsCount();
142 }
143 else
144 {
145 $settingsToSave["PLATFORM_ID"] = $this->id;
146 $resAdd = ExportProfileTable::add($settingsToSave);
147 if ($resAdd->isSuccess())
148 return $resAdd->getId();
149 else
150 return false;
151 }
152
153
154 }
155
156
162 public function setActive()
163 {
164 if ($this->isActive())
165 return true;
166
167 return parent::setActive();
168 }
169
174 public function unsetActive()
175 {
176 if (!$this->isActive())
177 return true;
178
179 return parent::unsetActive();
180 }
181
186 public function install()
187 {
188 RegisterModuleDependences('main', 'OnEventLogGetAuditTypes', 'sale', '\Bitrix\Sale\TradingPlatform\Vk\Vk', 'OnEventLogGetAuditTypes');
189
190// adding new PLATFORM
191 $tptAddRes = TradingPlatformTable::add(array(
192 "CODE" => $this->getCode(),
193 "ACTIVE" => "N",
194 "NAME" => Loc::getMessage("SALE_VK_NAME"),
195 "DESCRIPTION" => Loc::getMessage("SALE_VK_DESC"),
196 "CATALOG_SECTION_TAB_CLASS_NAME" => '\Bitrix\Sale\TradingPlatform\Vk\CatalogSectionTabHandler',
197 "CLASS" => '\Bitrix\Sale\TradingPlatform\Vk\Vk',
198 ));
199
200// force set flag install
201 if ($tptAddRes->isSuccess())
202 {
203 $this->isInstalled = true;
204 $this->id = $tptAddRes->getId();
205 }
206
207// adding VK IMAGE PROPERTY for all catalogs iblocks
208 $iblockIds = TradingPlatform\Helper::getIblocksIds(true);
209 foreach ($iblockIds as $iblock)
210 {
211 self::createSectionFieldVkImage($iblock["IBLOCK_ID"]);
212 }
213
214 return $tptAddRes->isSuccess();
215 }
216
222 public function uninstall()
223 {
224// delete vk image field for all iblocks
225 $iblockIds = TradingPlatform\Helper::getIblocksIds(true);
226 foreach ($iblockIds as $iblock)
227 {
228 self::deleteSectionFieldVkImage($iblock["IBLOCK_ID"]);
229 }
230
231// todo: del profiles
233
234// unset active, delete from TP table, unset instance
235 parent::uninstall();
236 }
237
238
246 public function removeProfile($exportId)
247 {
248 $resDel = ExportProfileTable::delete($exportId);
249
250// uninstall vk-categories update agent
251 $vkCategories = new VkCategories((int)$exportId);
252 $vkCategories->deleteAgent();
253
254// clear log
255 $logger = new Logger($exportId);
256 $logger->clearLog();
257
258// uninstall platform if deleted last exportId
259 $settings = $this->getSettings();
260 if (empty($settings))
261 {
262 $this->uninstall();
263 }
264
265 return $resDel;
266 }
267
268
275 private function createCatalogField($props)
276 {
277 $result = array('RESULT' => true, 'VALUE' => '');
278
279// find existing props to exclude duplicates
280 if ($existPropId = self::checkExistingCatalogField(
281 $props['IBLOCK_ID'],
282 self::createCodeForSectionFieldVkImage($props['IBLOCK_ID'])
283 )
284 )
285 {
286 $result['VALUE'] = $existPropId;
287 }
288
289// if not exist - create new
290 else
291 {
292 $ibp = new \CIBlockProperty();
293 $result['VALUE'] = (int)$ibp->Add($props);
294 if ($result['VALUE'] <= 0)
295 {
296 $result['RESULT'] = false;
297 $result['VALUE'] = $ibp->LAST_ERROR;
298 }
299 }
300
301 return $result;
302 }
303
304
311 private function checkExistingCatalogField($iblockId, $code)
312 {
313 $existingProps = \CIBlockProperty::GetList(
314 array(),
315 array(
316 'IBLOCK_ID' => $iblockId,
317 'CODE' => $code,
318 )
319 );
320
321 if ($existPropId = $existingProps->Fetch())
322 return $existPropId['ID'];
323 else
324 return false;
325 }
326
327
334 private function deleteSectionFieldVkImage($iblockId)
335 {
336// delete property with values
337 if ($propertyId = self::checkExistingCatalogField($iblockId, self::createCodeForSectionFieldVkImage($iblockId)))
338 return \CIBlockProperty::Delete($propertyId);
339
340 else
341 return false;
342 }
343
344
351 private function createSectionFieldVkImage($iblockId)
352 {
353 $properties = array(
354// 'ID' => 0,
355 'NAME' => Loc::getMessage('PROP_VK_IMAGES__NAME'),
356 'CODE' => self::createCodeForSectionFieldVkImage($iblockId),
357 'IBLOCK_ID' => $iblockId,
358 'ACTIVE' => 'Y',
359 'PROPERTY_TYPE' => 'F',
360 'MULTIPLE' => 'Y',
361 'HINT' => Loc::getMessage('PROP_VK_IMAGES__HINT'),
362 'FILE_TYPE' => 'jpg, jpeg, bmp, gif, png',
363 );
364
365 return self::createCatalogField($properties);
366 }
367
368
375 private function createCodeForSectionFieldVkImage($iblockId)
376 {
377 return 'PHOTOS_FOR_VK_' . $iblockId;
378 }
379
380
387 public function getGroupId($exportId)
388 {
389 $settings = $this->getSettings($exportId);
390 $groupId = false;
391
392 if (isset($settings["VK_SETTINGS"]["GROUP_ID"]))
393 {
394 $groupId = $settings["VK_SETTINGS"]["GROUP_ID"];
395 $groupId = mb_substr($groupId, 0, 1) == '-' ? $groupId : '-'.$groupId;
396 }
397
398 return $groupId;
399 }
400
401
408 public function isAgressiveExport($exportId)
409 {
410 $settings = $this->getSettings($exportId);
411
412 if (isset($settings["EXPORT_SETTINGS"]["AGRESSIVE"]) && $settings["EXPORT_SETTINGS"]["AGRESSIVE"])
413 return true;
414 else
415 return false;
416
417 }
418
419
426 public function getApi($exportId)
427 {
428 if (!isset($this->api[$exportId]))
429 $this->api[$exportId] = new Api($this->getAccessToken($exportId), $exportId);
430
431 return $this->api[$exportId];
432 }
433
434
441 public function getExecuter($exportId)
442 {
443 if (!isset($this->executer[$exportId]))
444 $this->executer[$exportId] = new Executer($this->getApi($exportId));
445
446 return $this->executer[$exportId];
447 }
448
449
456 private function getAccessToken($exportId)
457 {
458 if (!isset($this->accessToken[$exportId]))
459 {
460 $settings = $this->getSettings();
461
462 if (isset($settings[$exportId]["OAUTH"]["ACCESS_TOKEN"]))
463 $this->accessToken[$exportId] = $settings[$exportId]["OAUTH"]["ACCESS_TOKEN"];
464 else
465 throw new ArgumentNullException('accessToken');
466 }
467
468 return $this->accessToken[$exportId];
469 }
470
471
477 public static function getExportTypes()
478 {
479 return array(
480 'PRODUCTS',
481 'PRODUCTS_DELETE',
482 'PRODUCTS_DELETE_ALL',
483 'ALBUMS',
484 'ALBUMS_DELETE',
485 'ALBUMS_DELETE_ALL',
486 'ALL',
487 );
488 }
489
490
499// todo: need a use only one logger, tp or vk
500 public function log($level, $type, $itemId, $description)
501 {
502 //hardcode, because we not use other levels
503 $logLevel = TradingPlatform\Logger::LOG_LEVEL_DEBUG;
504 $this->logger->setLevel($logLevel);
505
506// todo: maybe we need email reporting of fatal errors
507
508 return $this->addLogRecord($level, $type, $itemId, $description);
509 }
510
511
517 public function changeActiveById($exportId)
518 {
519 $settings = $this->getSettings($exportId);
520
521 if (
522 (isset($settings["VK_SETTINGS"]["GROUP_ID"]) && !empty($settings["VK_SETTINGS"]["GROUP_ID"])) &&
523 (isset($settings["VK_SETTINGS"]["APP_ID"]) && $settings["VK_SETTINGS"]["APP_ID"]) &&
524 (isset($settings["VK_SETTINGS"]["SECRET"]) && !empty($settings["VK_SETTINGS"]["SECRET"])) &&
525 (isset($settings["OAUTH"]["ACCESS_TOKEN"]) && $settings["OAUTH"]["ACCESS_TOKEN"]) &&
526 (isset($settings["EXPORT_SETTINGS"]["CATEGORY_DEFAULT"]) && $settings["EXPORT_SETTINGS"]["CATEGORY_DEFAULT"] > 0)
527 )
528 $this->setActiveById($exportId);
529 else
530 $this->unsetActiveById($exportId);
531
532 }
533
534
541 private function setActiveById($exportId)
542 {
543 $settings = $this->getSettings($exportId);
544 if (isset($settings) && is_array($settings))
545 $settings["EXPORT_SETTINGS"]["ACTIVE"] = "Y";
546
547// if we set active to one profile - all platform is active
548 if (!parent::isActive())
549 parent::setActive();
550
551 return $this->saveSettings(array('SETTINGS' => $settings, 'EXPORT_ID' => $exportId));
552 }
553
554
561 public function unsetActiveById($exportId)
562 {
563 $settings = $this->getSettings();
564 if (isset($settings[$exportId]) && is_array($settings[$exportId]))
565 $settings[$exportId]["EXPORT_SETTINGS"]["ACTIVE"] = "N";
566
567// check all profiles for active
568 $bActiveAll = false;
569 foreach ($settings as $id => $exportSettings)
570 {
571 if ($this->isActiveById($id))
572 $bActiveAll = true;
573 }
574
575// if no one profile is active - unactive all platform
576 if (!$bActiveAll)
577 $this->unsetActive();
578
579 if (isset($settings[$exportId]) && is_array($settings[$exportId]))
580 return $this->saveSettings(array('SETTINGS' => $settings[$exportId], 'EXPORT_ID' => $exportId));
581
582 else
583 return false;
584 }
585
586
593 public function isActiveById($exportId)
594 {
595 $settings = $this->getSettings($exportId);
596
597 if (isset($settings["EXPORT_SETTINGS"]["ACTIVE"]) && $settings["EXPORT_SETTINGS"]["ACTIVE"] == "Y")
598 return true;
599 else
600 return false;
601 }
602
603
611 public function getAuthUrl($exportId, $redirectUrl)
612 {
613 $settings = $this->getSettings();
614 $urlParams = array();
615
616 if (isset($settings[$exportId]["VK_SETTINGS"]["APP_ID"]) && !empty($settings[$exportId]["VK_SETTINGS"]["APP_ID"]))
617 $urlParams['client_id'] = $settings[$exportId]["VK_SETTINGS"]["APP_ID"];
618 else return false;
619
620 if (!empty($redirectUrl))
621 $urlParams['redirect_uri'] = self::formatRedirectUrl($redirectUrl);
622 else return false;
623
624 $urlParams["display"] = "page";
625 $urlParams["scope"] = self::getScope(array("market", "photos", "offline", "wall", "docs", "groups"));
626 $urlParams["response_type"] = "code";
627 $urlParams["v"] = Api::$apiVersion;
628
629 return self::OAUTH_URL . "?" . http_build_query($urlParams);
630 }
631
632
641 public function getTokenUrl($exportId, $redirectUrl, $code)
642 {
643 $settings = $this->getSettings($exportId);
644 $urlParams = array();
645
646 if (isset($settings["VK_SETTINGS"]["APP_ID"]) && !empty($settings["VK_SETTINGS"]["APP_ID"]))
647 $urlParams['client_id'] = $settings["VK_SETTINGS"]["APP_ID"];
648 else return false;
649
650 if (isset($settings["VK_SETTINGS"]["SECRET"]) && !empty($settings["VK_SETTINGS"]["SECRET"]))
651 $urlParams['client_secret'] = $settings["VK_SETTINGS"]["SECRET"];
652 else return false;
653
654 if (!empty($redirectUrl))
655 $urlParams['redirect_uri'] = self::formatRedirectUrl($redirectUrl);
656 else return false;
657
658 if (!empty($code))
659 $urlParams['code'] = $code;
660 else return false;
661
662 return self::TOKEN_URL . "?" . http_build_query($urlParams);
663 }
664
665
672 private static function formatRedirectUrl($redirectUrl)
673 {
674 $protocol = \CMain::IsHTTPS() ? "https://" : "http://";
675 $redirectUrl = $protocol . urldecode($redirectUrl);
676
677 return $redirectUrl;
678 }
679
680
687 public static function getScope($params)
688 {
689 $scopes = array(
690 "notify" => 1,
691 "friends" => 2,
692 "photos" => 4,
693 "audio" => 8,
694 "video" => 16,
695 "docs" => 131072,
696 "notes" => 2048,
697 "pages" => 128,
698 "status" => 1024,
699 "offers" => 32,
700 "questions" => 64,
701 "wall" => 8192,
702 "groups" => 262144,
703 "messages" => 4096,
704 "email" => 4194304,
705 "notifications" => 524288,
706 "stats" => 1048576,
707 "ads" => 32768,
708 "market" => 134217728,
709 "offline" => 65536,
710 );
711 $scope = 0;
712
713 foreach ($params as $param)
714 {
715 if (isset($scopes[$param]))
716 $scope += $scopes[$param];
717 }
718
719 return $scope;
720 }
721
727 public function getTimelimit($exportId)
728 {
729 $settings = $this->getSettings($exportId);
730
731 if (isset($settings["EXPORT_SETTINGS"]["TIMELIMIT"]))
732 return $settings["EXPORT_SETTINGS"]["TIMELIMIT"];
733 else
734 return false;
735 }
736
742 public function getExecutionItemsLimit($exportId)
743 {
744 $settings = $this->getSettings();
745 $settings = $settings[$exportId];
746
747 if (isset($settings["EXPORT_SETTINGS"]["COUNT_ITEMS"]))
748 return $settings["EXPORT_SETTINGS"]["COUNT_ITEMS"];
749 else
750 return false;
751 }
752
760 public function getRichLog($exportId)
761 {
762 $settings = $this->getSettings($exportId);
763
764 if (isset($settings["EXPORT_SETTINGS"]["RICH_LOG"]) && $settings["EXPORT_SETTINGS"]["RICH_LOG"])
765 return true;
766 else
767 return false;
768 }
769
770
771 public function getAvailableFlag($exportId)
772 {
773 $settings = $this->getSettings($exportId);
774
775 if (isset($settings["EXPORT_SETTINGS"]["ONLY_AVAILABLE_FLAG"]) && !$settings["EXPORT_SETTINGS"]["ONLY_AVAILABLE_FLAG"])
776 return false;
777 else
778 return true;
779 }
780
781
789 public function getExportProfilesList($onlyActive = true)
790 {
791 $exportIds = array();
792 $resExports = ExportProfileTable::getList(array(
793 'filter' => array('PLATFORM_ID' => $this->getId()),
794 'select' => array('ID', 'DESCRIPTION', 'EXPORT_SETTINGS'),
795 )
796 );
797
798 while ($export = $resExports->fetch())
799 {
800 if ($onlyActive && $export["EXPORT_SETTINGS"]["ACTIVE"] != "Y")
801 continue;
802 else
803 $exportIds[$export["ID"]] = array(
804 'ID' => $export["ID"],
805 'DESC' => $export['DESCRIPTION'],
806 );
807 }
808
809 return $exportIds;
810 }
811
812
818 public static function OnEventLogGetAuditTypes()
819 {
820 $prefix = 'VK: ';
821
822 $result = array(
823 "VK_PROCESS__START" => Loc::getMessage("SALE_VK_PROCESS__START"),
824 "VK_PROCESS__TIMELIMIT" => Loc::getMessage("SALE_VK_PROCESS__TIMELIMIT"),
825 "VK_PROCESS__ERRORS" => Loc::getMessage("SALE_VK_PROCESS__ERRORS"),
826 "VK_PROCESS__FINISH" => Loc::getMessage("SALE_VK_PROCESS__FINISH"),
827 "VK_FEED__CREATED" => Loc::getMessage("SALE_VK_FEED_CREATED"),
828 "VK_FEED__FEED_ERRORS" => Loc::getMessage("SALE_VK_FEED_ERRORS"),
829 "VK_FEED__FEED_TIMELIMIT" => Loc::getMessage("SALE_VK_FEED_TIMELIMIT"),
830 "VK_FEED__FEED_FINISH" => Loc::getMessage("SALE_VK_FEED_FINISH"),
831 "VK_FEED__FEED_FINISH_OK" => Loc::getMessage("SALE_VK_FEED_FINISH_OK"),
832 "VK_FEED__FEED_ALBUM_PART_FINISH" => Loc::getMessage("SALE_VK_FEED_ALBUM_PART_FINISH"),
833 );
834
835 array_walk($result, function (&$value, $key, $prefix)
836 {
837 $value = $prefix . $value;
838 },
839 $prefix
840 );
841
842 return $result;
843 }
844}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
addLogRecord($level, $type, $itemId, $description)
Definition platform.php:109
getSettings($exportId=NULL)
Definition vk.php:80
saveSettings(array $settings)
Definition vk.php:114
static getScope($params)
Definition vk.php:687
getTokenUrl($exportId, $redirectUrl, $code)
Definition vk.php:641
getAuthUrl($exportId, $redirectUrl)
Definition vk.php:611
getExportProfilesList($onlyActive=true)
Definition vk.php:789
log($level, $type, $itemId, $description)
Definition vk.php:500
getExecutionItemsLimit($exportId)
Definition vk.php:742