PageRenderTime 25ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/seo/lib/service.php

https://gitlab.com/alexprowars/bitrix
PHP | 416 lines | 279 code | 48 blank | 89 comment | 30 complexity | b5e1aeb22d52048c2553ae35e35dc285 MD5 | raw file
  1. <?php
  2. /**
  3. * Bitrix Framework
  4. * @package bitrix
  5. * @subpackage seo
  6. * @copyright 2001-2013 Bitrix
  7. */
  8. namespace Bitrix\Seo;
  9. use Bitrix\Main\Application;
  10. use Bitrix\Main\Context;
  11. use Bitrix\Main\Loader;
  12. use Bitrix\Main\Localization\Loc;
  13. use Bitrix\Main\SystemException;
  14. use Bitrix\Main\Web\HttpClient;
  15. use Bitrix\Main\Web\Json;
  16. use Bitrix\Seo\Engine\Bitrix;
  17. use Bitrix\Seo\Retargeting\AdsAudience;
  18. Loc::loadMessages(__FILE__);
  19. if(!defined("BITRIX_CLOUD_ADV_URL"))
  20. {
  21. define("BITRIX_CLOUD_ADV_URL", 'https://cloud-adv.bitrix.info');
  22. }
  23. if(!defined("SEO_SERVICE_URL"))
  24. {
  25. define('SEO_SERVICE_URL', BITRIX_CLOUD_ADV_URL);
  26. }
  27. class Service
  28. {
  29. const SERVICE_URL = SEO_SERVICE_URL;
  30. const REGISTER = "/oauth/register/";
  31. const AUTHORIZE = "/register/";
  32. const REDIRECT_URI = "/bitrix/tools/seo_client.php";
  33. const SERVICE_AUTH_CACHE_TLL = 86400;
  34. const SERVICE_AUTH_CACHE_TLL_ERROR = 3600;
  35. const SERVICE_AUTH_CACHE_ID = 'seo|service_auth';
  36. const SERVICE_AUTH_CACHE_ID_ERROR = 'seo|service_auth_error';
  37. const CLIENT_LIST_CACHE_TLL = 86400;
  38. const CLIENT_LIST_CACHE_ID = 'seo|client_list|2';
  39. const CLIENT_TYPE_SINGLE = 'S';
  40. const CLIENT_TYPE_MULTIPLE = 'M';
  41. const CLIENT_TYPE_COMPATIBLE = 'C';
  42. protected static $engine = null;
  43. protected static $auth = null;
  44. protected static $clientList = null;
  45. /**
  46. * CAn connect to seoproxy?
  47. * @return bool
  48. */
  49. public static function isRegistered()
  50. {
  51. return static::getEngine() ? static::getEngine()->isRegistered() : false;
  52. }
  53. /**
  54. * Get client info
  55. * @use \Bitrix\Seo\Service::getClientList(...)
  56. *
  57. * @param string $engineCode Provider code.
  58. * @return boolean|array
  59. * @deprecated
  60. */
  61. public static function getAuth(string $engineCode)
  62. {
  63. global $CACHE_MANAGER;
  64. if (static::$auth === null)
  65. {
  66. if ($CACHE_MANAGER->Read(static::SERVICE_AUTH_CACHE_TLL, static::SERVICE_AUTH_CACHE_ID))
  67. {
  68. static::$auth = $CACHE_MANAGER->Get(static::SERVICE_AUTH_CACHE_ID);
  69. }
  70. elseif (!$CACHE_MANAGER->Read(static::SERVICE_AUTH_CACHE_TLL_ERROR, static::SERVICE_AUTH_CACHE_ID_ERROR))
  71. {
  72. static::$auth = static::getEngine()->getInterface()->getClientInfo();
  73. if (!static::$auth)
  74. {
  75. static::$auth = false;
  76. $CACHE_MANAGER->Read(static::SERVICE_AUTH_CACHE_TLL_ERROR, static::SERVICE_AUTH_CACHE_ID_ERROR);
  77. $CACHE_MANAGER->Set(static::SERVICE_AUTH_CACHE_ID_ERROR, static::$auth);
  78. }
  79. else
  80. {
  81. $CACHE_MANAGER->Set(static::SERVICE_AUTH_CACHE_ID, static::$auth);
  82. }
  83. }
  84. else
  85. {
  86. static::$auth = false;
  87. }
  88. }
  89. if (static::$auth)
  90. {
  91. return static::$auth["engine"][$engineCode];
  92. }
  93. return false;
  94. }
  95. /**
  96. * Get clients list
  97. * @param string|bool $engineCode Provider code.
  98. * @return array
  99. * @throws SystemException
  100. */
  101. public static function getClientList($engineCode = false)
  102. {
  103. if( static::$clientList == null)
  104. {
  105. $cache = Application::getInstance()->getManagedCache();
  106. if ($cache->read(static::CLIENT_LIST_CACHE_TLL, static::CLIENT_LIST_CACHE_ID))
  107. {
  108. static::$clientList = $cache->get(static::CLIENT_LIST_CACHE_ID);
  109. static::$clientList = is_array(static::$clientList) ? static::$clientList : [];
  110. }
  111. else
  112. {
  113. $clientDataProvider = static::getEngine()->getInterface();
  114. $result = $clientDataProvider->getClientList();
  115. if (!is_array($result)) // backward compatibility
  116. {
  117. $result = [];
  118. $data = $clientDataProvider->getClientInfo();
  119. if (is_array($data))
  120. {
  121. foreach ($data as $code => $client)
  122. {
  123. $data['proxy_client_type'] = static::CLIENT_TYPE_COMPATIBLE;
  124. $data['engine_code'] = $code;
  125. $data['proxy_client_id'] = null;
  126. $result[] = $data;
  127. }
  128. }
  129. }
  130. else
  131. {
  132. $result = $result['items'];
  133. }
  134. $cache->set(static::CLIENT_LIST_CACHE_ID, $result);
  135. static::$clientList = $result;
  136. }
  137. }
  138. if ($engineCode)
  139. {
  140. return array_filter(static::$clientList, function ($item) use ($engineCode) {
  141. return $item['engine_code'] == $engineCode;
  142. });
  143. }
  144. return static::$clientList;
  145. }
  146. /**
  147. * @return void
  148. * @use \Bitrix\Seo\Service::clearClientsCache()
  149. * @deprecated
  150. */
  151. public static function clearLocalAuth()
  152. {
  153. global $CACHE_MANAGER;
  154. $CACHE_MANAGER->Clean(static::SERVICE_AUTH_CACHE_ID);
  155. static::$auth = null;
  156. }
  157. /**
  158. * Clear clients list cache
  159. * @param string|null $engine Engine code.
  160. * @param int|null $clientId Proxy client id.
  161. * @return void
  162. * @throws SystemException
  163. */
  164. public static function clearClientsCache($engine = null, $clientId = null)
  165. {
  166. $cache = Application::getInstance()->getManagedCache();
  167. $cache->Clean(static::CLIENT_LIST_CACHE_ID);
  168. $cache->Clean(static::SERVICE_AUTH_CACHE_ID);
  169. $cache->Clean(static::SERVICE_AUTH_CACHE_ID_ERROR);
  170. [$group, $type] = explode('.', $engine, 2);
  171. if ($group == \Bitrix\Seo\Retargeting\Service::GROUP)
  172. {
  173. $service = AdsAudience::getService();
  174. $service->setClientId($clientId);
  175. $account = $service->getAccount($type);
  176. if ($account)
  177. $account->clearCache();
  178. }
  179. static::$clientList = null;
  180. static::$auth = null;
  181. }
  182. /**
  183. * @param string $engineCode Provider code.
  184. * @param bool $localOnly Do not delete client in seoproxy service.
  185. * @return void
  186. * @use \Bitrix\Seo\Service::clearAuthForClient(...)
  187. * @throws SystemException
  188. * @deprecated
  189. */
  190. public static function clearAuth($engineCode, $localOnly = false)
  191. {
  192. static::clearClientsCache($engineCode);
  193. if(!$localOnly)
  194. {
  195. static::getEngine()->getInterface()->clearClientAuth($engineCode);
  196. }
  197. }
  198. /**
  199. * Remove auth for a client
  200. * @param array $client Client data.
  201. * @param bool $localOnly Only clear cache.
  202. * @return void
  203. * @throws SystemException
  204. */
  205. public static function clearAuthForClient($client, $localOnly = false)
  206. {
  207. if(!$localOnly)
  208. {
  209. static::getEngine()->getInterface()->clearClientAuth($client['engine_code'], $client['proxy_client_id']);
  210. }
  211. static::clearClientsCache($client['engine_code'], $client['proxy_client_id']);
  212. }
  213. /**
  214. * Set access settings
  215. * @param array $accessParams Access params.
  216. * @return void
  217. * @throws SystemException
  218. */
  219. protected static function setAccessSettings(array $accessParams)
  220. {
  221. if(static::isRegistered())
  222. {
  223. $id = static::getEngine()->getId();
  224. $result = SearchEngineTable::update($id, array(
  225. "CLIENT_ID" => $accessParams["client_id"],
  226. "CLIENT_SECRET" => $accessParams["client_secret"],
  227. "SETTINGS" => "",
  228. ));
  229. }
  230. else
  231. {
  232. $result = SearchEngineTable::add(array(
  233. "CODE" => Bitrix::ENGINE_ID,
  234. "NAME" => "Bitrix",
  235. "ACTIVE" => SearchEngineTable::ACTIVE,
  236. "CLIENT_ID" => $accessParams["client_id"],
  237. "CLIENT_SECRET" => $accessParams["client_secret"],
  238. "REDIRECT_URI" => static::getRedirectUri(),
  239. ));
  240. }
  241. if($result->isSuccess())
  242. {
  243. static::clearAuth(Bitrix::ENGINE_ID, true);
  244. static::$engine = null;
  245. }
  246. }
  247. /**
  248. * @return \Bitrix\Seo\Engine\Bitrix
  249. */
  250. public static function getEngine()
  251. {
  252. if(!static::$engine && Loader::includeModule("socialservices"))
  253. {
  254. static::$engine = new Bitrix();
  255. }
  256. return static::$engine;
  257. }
  258. /**
  259. * @return void
  260. * @throws SystemException
  261. * @throws \Bitrix\Main\ArgumentException
  262. */
  263. public static function register()
  264. {
  265. static::clearClientsCache();
  266. $httpClient = new HttpClient();
  267. $queryParams = [
  268. "key" => static::getLicense(),
  269. "scope" => static::getEngine()->getInterface()->getScopeEncode(),
  270. "redirect_uri" => static::getRedirectUri(),
  271. ];
  272. $result = $httpClient->post(static::SERVICE_URL.static::REGISTER, $queryParams);
  273. $result = Json::decode($result);
  274. if($result["error"])
  275. {
  276. throw new SystemException($result["error"]);
  277. }
  278. static::setAccessSettings($result);
  279. }
  280. /**
  281. * @return void
  282. * @throws SystemException
  283. */
  284. public static function unregister()
  285. {
  286. if(static::isRegistered())
  287. {
  288. $id = static::getEngine()->getId();
  289. SearchEngineTable::delete($id);
  290. static::clearClientsCache();
  291. }
  292. }
  293. /**
  294. * @return string
  295. */
  296. public static function getAuthorizeLink()
  297. {
  298. return static::SERVICE_URL.static::AUTHORIZE;
  299. }
  300. /**
  301. * @param string $engine Provider code.
  302. * @param bool $clientType Client type.
  303. * @return array
  304. * @throws \Bitrix\Main\LoaderException
  305. */
  306. public static function getAuthorizeData($engine, $clientType = false): array
  307. {
  308. $checkKey = "";
  309. if(Loader::includeModule("socialservices"))
  310. {
  311. $checkKey = \CSocServAuthManager::GetUniqueKey();
  312. }
  313. $clientType = $clientType ?: Service::CLIENT_TYPE_COMPATIBLE;
  314. return [
  315. "action" => "authorize",
  316. "type" => $clientType,
  317. "engine" => $engine,
  318. "client_id" => static::getEngine()->getClientId(),
  319. "client_secret" => static::getEngine()->getClientSecret(),
  320. "key" => static::getLicense(),
  321. "check_key" => urlencode($checkKey),
  322. "redirect_uri" => static::getRedirectUri(),
  323. ];
  324. }
  325. /**
  326. * @return string
  327. */
  328. protected static function getRedirectUri(): string
  329. {
  330. $request = Context::getCurrent()->getRequest();
  331. $host = $request->getHttpHost();
  332. $port = (int)$request->getServerPort();
  333. $host .= ($port && $port !== 80 && $port !== 443) ? ":{$port}" : '';
  334. $isHttps = $request->isHttps();
  335. return ($isHttps ? 'https' : 'http').'://'.$host.static::REDIRECT_URI;
  336. }
  337. /**
  338. * @return string
  339. */
  340. protected static function getLicense(): string
  341. {
  342. return md5(LICENSE_KEY);
  343. }
  344. /**
  345. * If site change domain - need update engine
  346. * @param array $domains
  347. * @throws \Exception
  348. */
  349. public static function changeRegisteredDomain(array $domains = []): void
  350. {
  351. if (!self::isRegistered())
  352. {
  353. return;
  354. }
  355. if(!$engine = static::getEngine())
  356. {
  357. return;
  358. }
  359. $newRedirectUri = static::getRedirectUri();
  360. if(!empty($domains))
  361. {
  362. $newRedirectUri = str_replace($domains['old_domain'], $domains['new_domain'], $newRedirectUri);
  363. }
  364. SearchEngineTable::update($engine->getId(), [
  365. 'REDIRECT_URI' => $newRedirectUri
  366. ]);
  367. }
  368. }