Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
yandex.php
1<?
9namespace Bitrix\Seo\Engine;
10
19
20class Yandex extends Engine\YandexBase implements IEngine
21{
22 const ENGINE_ID = 'yandex';
23
24 const SERVICE_URL = "https://webmaster.yandex.ru/api/v2";
25 const API_BASE_URL = "https://api.webmaster.yandex.net/v3/user/";
26 const API_HOSTS_URL = "hosts/";
27 const API_SUMMARY_URL = "summary/";
28 const API_SAMPLES_URL = "links/external/samples/";
29 const API_POPULAR_URL = "search-queries/popular/";
30 const API_VERIFICATION_URL = "verification/";
31 const API_ORIGINAL_TEXTS_URL = "original-texts/";
32
33 const HOSTS_SERVICE = "host-list";
34 const HOST_VERIFY = "verify-host";
35 const HOST_INFO = "host-information";
36 const HOST_TOP_QUERIES = "top-queries";
37 const HOST_ORIGINAL_TEXTS = "original-texts";
38 const HOST_INDEXED = "indexed-urls";
39 const HOST_EXCLUDED = "excluded-urls";
40
44
45 const QUERY_USER = 'https://login.yandex.ru/info';
46
47 const VERIFIED_STATE_VERIFIED = "VERIFIED";
48 const VERIFIED_STATE_WAITING = "WAITING";
49 const VERIFIED_STATE_FAILED = "VERIFICATION_FAILED";
50 const VERIFIED_STATE_NEVER_VERIFIED = "NEVER_VERIFIED";
51 const VERIFIED_STATE_IN_PROGRESS = "IN_PROGRESS";
52
53 const INDEXING_STATE_OK = "OK";
54
55 private static $verificationTypes = array('DNS', 'HTML_FILE', 'META_TAG', 'WHOIS', 'TXT_FILE');
56
57 protected $engineId = 'yandex';
58 protected $arServiceList = array();
59 private $userId = NULL;
60 private $hostIds = array();
61
62 public function __construct()
63 {
64 parent::__construct();
65
66// save user ID from auth
67 if (isset($this->engineSettings['AUTH_USER']['id']))
68 $this->userId = $this->engineSettings['AUTH_USER']['id'];
69 }
70
80 private function getServiceUrl($userId = NULL, $hostId = NULL, $service = NULL, $params = NULL)
81 {
82 $url = self::API_BASE_URL;
83
84 if ($userId)
85 $url .= $userId . '/';
86 if ($hostId)
87 $url .= 'hosts/' . $hostId . '/';
88 if ($service)
89 $url .= $service;
90 if ($params)
91 {
92 if (is_array($params))
93 $params = '?' . http_build_query($params);
94 else
95 $params = '?' . str_replace('?', '', $params);
96
97 $url .= $params;
98 }
99
100 return $url;
101 }
102
103 // temporary hack
104 public function getAuthSettings()
105 {
106 return $this->engineSettings['AUTH'];
107 }
108
115 private function getHostId($domain)
116 {
117// get saved host ID
118 if (isset($this->hostIds[$domain]) && !empty($this->hostIds[$domain]))
119 return $this->hostIds[$domain];
120
121// else get host ID from API (host will be saved in local)
122 $hosts = $this->getFeeds();
123
124 return $hosts[$domain]['host_id'];
125 }
126
127 public function getFeeds()
128 {
129 $serviceUrl = $this->getServiceUrl($this->userId, NULL, self::API_HOSTS_URL);
130 $queryResult = $this->query($serviceUrl, 'GET');
131
132 if ($queryResult && $queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
133 {
134 $resultConverted = array();
135 $result = Json::decode($queryResult->getResult());
136 foreach ($result['hosts'] as $host)
137 {
138// if set main mirror - we must use them
139 if(array_key_exists("main_mirror", $host) && is_array($host["main_mirror"]) && !empty($host["main_mirror"]))
140 $host = array_merge($host, $host["main_mirror"]);
141
142// ascii_host_url must be equal unicode_host_url for latin URLs.
143// if it cyrillic URL - we need ASCII host.
144 $hostUrl = str_replace(array('http://', 'https://'), '', $host['ascii_host_url']);
145 $hostUrl = rtrim($hostUrl, '/');
146 $resultConverted[$hostUrl] = $host;
147
148// convert verified status in correct format
149 if ($host['verified'])
150 $resultConverted[$hostUrl]['verification'] = self::VERIFIED_STATE_VERIFIED;
151// save hostId in local var
152 $this->hostIds[$hostUrl] = $host['host_id'];
153 }
154
155// save found hosts to table
156 $this->processHosts();
157
158 return $resultConverted;
159 }
160 else
161 {
162 throw new Engine\YandexException($queryResult);
163 }
164 }
165
171 public function getSiteInfo($domain)
172 {
173 $result = array();
174
175 $result += $this->getSiteInfoGeneral($domain);
176 $result += $this->getSiteInfoStats($domain);
177
178 return array($domain => $result);
179 }
180
181 private function getSiteInfoGeneral($domain)
182 {
183 $domain = ToLower($domain);
184 $hostId = $this->getHostId($domain);
185
186 $serviceUrl = $this->getServiceUrl($this->userId, $hostId);
187 $queryResult = $this->query($serviceUrl, 'GET');
188
189 if ($queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
190 return Json::decode($queryResult->getResult());
191 else
192 throw new Engine\YandexException($queryResult);
193 }
194
195 private function getSiteInfoStats($domain)
196 {
197 $domain = ToLower($domain);
198 $hostId = $this->getHostId($domain);
199
200 $serviceUrl = $this->getServiceUrl($this->userId, $hostId, self::API_SUMMARY_URL);
201 $queryResult = $this->query($serviceUrl, 'GET');
202
203 if ($queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
204 return Json::decode($queryResult->getResult());
205 else
206 throw new Engine\YandexException($queryResult);
207 }
208
209// todo: we can add info about external links like a popular queries
210
217 public function getSiteInfoQueries($domain)
218 {
219 $domain = ToLower($domain);
220 $hostId = $this->getHostId($domain);
221
222// get TOTAL_SHOWS
223 $params = array(
224 "order_by" => "TOTAL_SHOWS",
225 "query_indicator" => "TOTAL_SHOWS",
226 );
227
228 $serviceUrl = $this->getServiceUrl($this->userId, $hostId, self::API_POPULAR_URL, $params);
229// dirt hack - our construcotr not understand multiply params
230 $serviceUrl .= '&query_indicator=TOTAL_CLICKS';
231 $serviceUrl .= '&query_indicator=AVG_SHOW_POSITION';
232 $serviceUrl .= '&query_indicator=AVG_CLICK_POSITION';
233
234 $queryResult = $this->query($serviceUrl, 'GET');
235 if ($queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
236 $queriesShows = Json::decode($queryResult->getResult());
237 else
238 throw new Engine\YandexException($queryResult);
239
240// format out array
241 $result = array();
242 $totalShows = 0;
243 $totalClicks = 0;
244 foreach($queriesShows['queries'] as $key => $query)
245 {
246 $result[$key] = array(
247 'TEXT' => $query['query_text'],
248 'TOTAL_SHOWS' => $query['indicators']['TOTAL_SHOWS'],
249 'TOTAL_CLICKS' => $query['indicators']['TOTAL_CLICKS'],
250 'AVG_SHOW_POSITION' => is_null($query['indicators']['AVG_SHOW_POSITION']) ? '' :round($query['indicators']['AVG_SHOW_POSITION'], 1),
251 'AVG_CLICK_POSITION' => is_null($query['indicators']['AVG_CLICK_POSITION']) ? '' :round($query['indicators']['AVG_CLICK_POSITION'], 1),
252 );
253 $totalShows += $query['indicators']['TOTAL_SHOWS'];
254 $totalClicks += $query['indicators']['TOTAL_CLICKS'];
255 }
256
257 return array(
258 'QUERIES' => $result,
259 'DATE_FROM' => $queriesShows['date_from'],
260 'DATE_TO' => $queriesShows['date_to'],
261 'TOTAL_SHOWS' => $totalShows,
262 'TOTAL_CLICKS' => $totalClicks,
263 );
264 }
265
266 private function processHosts()
267 {
268 $existedDomains = \CSeoUtils::getDomainsList();
269
270 foreach($existedDomains as $domain)
271 {
272 $domain['DOMAIN'] = ToLower($domain['DOMAIN']);
273
274 if(isset($this->hostIds[$domain['DOMAIN']]))
275 {
276 if(!is_array($this->engineSettings['SITES']))
277 $this->engineSettings['SITES'] = array();
278
279 $this->engineSettings['SITES'][$domain['DOMAIN']] = $this->hostIds[$domain['DOMAIN']];
280 }
281 }
282
283 $this->saveSettings();
284 }
285
286 public function getOriginalTexts($domain)
287 {
288 $domain = ToLower($domain);
289 $hostId = $this->getHostId($domain);
290
291 $counter = 0;
293 $result = array(
294 'count' => 0,
295 'quota_remainder' => 0,
296 'can-add' =>false,
297 'original_texts' => array(),
298 );
299
300// recursive collect text ehilw not catch limit
301 while($counter < $limit)
302 {
303// default limit 10, may set other value
304 $params = array('offset' => $counter);
305
306 $stepResult = $this->getOriginalTextsRecursive($hostId, $params);
307 $result['count'] = $stepResult['count'];
308 $result['quota_remainder'] = $stepResult['quota_remainder'];
309 $result['can-add'] = intval($result['quota_remainder']) > 0;
310 $result['original_texts'] = array_merge($result['original_texts'], $stepResult['original_texts']);
311 $counter += count($stepResult['original_texts']);
312
313// if catch last text - exit
314 if($counter >= $result['count'])
315 break;
316 }
317
318 return $result;
319 }
320
329 private function getOriginalTextsRecursive($hostId, $params)
330 {
331 $serviceUrl = $this->getServiceUrl($this->userId, $hostId, self::API_ORIGINAL_TEXTS_URL, $params);
332 $queryResult = $this->query($serviceUrl, 'GET', $params);
333
334 if ($queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
335 return Json::decode($queryResult->getResult());
336 else
337 throw new Engine\YandexException($queryResult);
338 }
339
340
349 public function addOriginalText($text, $domain)
350 {
351 $domain = ToLower($domain);
352 $hostId = $this->getHostId($domain);
353
354// create JSON data in correct format
355 $data = array("content" => $text);
356 $data = Json::encode($data);
357 $serviceUrl = $this->getServiceUrl($this->userId, $hostId, self::API_ORIGINAL_TEXTS_URL);
358 $queryResult = $this->query($serviceUrl, 'POST', $data);
359
360 if ($queryResult->getStatus() == self::HTTP_STATUS_CREATED && $queryResult->getResult() <> '')
361 return $queryResult->getResult();
362 else
363 throw new Engine\YandexException($queryResult);
364 }
365
366
374 public function addSite($domain)
375 {
376 $domain = ToLower($domain);
377 $queryDomain = Context::getCurrent()->getRequest()->isHttps() ? 'https://' . $domain : $domain;
378
379// create JSON data in correct format
380 $data = array("host_url" => $queryDomain);
381 $data = Json::encode($data);
382 $serviceUrl = $this->getServiceUrl($this->userId, NULL, self::API_HOSTS_URL);
383 $queryResult = $this->query($serviceUrl, 'POST', $data);
384
385 if ($queryResult->getStatus() == self::HTTP_STATUS_CREATED && $queryResult->getResult() <> '')
386 return array($domain => true);
387 else
388 throw new Engine\YandexException($queryResult);
389 }
390
391
398 public function getVerifySiteUin($domain)
399 {
400 $domain = ToLower($domain);
401 $hostId = $this->getHostId($domain);
402
403 $serviceUrl = $this->getServiceUrl($this->userId, $hostId, self::API_VERIFICATION_URL);
404 $queryResult = $this->query($serviceUrl, 'GET');
405
406 if ($queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
407 {
408 $result = Json::decode($queryResult->getResult());
409 if ($result['verification_state'] != self::VERIFIED_STATE_VERIFIED)
410 return $result['verification_uin'];
411 else
412 return false; //already verify
413 }
414 else
415 {
416 throw new Engine\YandexException($queryResult);
417 }
418 }
419
420 public function verifySite($domain, $verType = 'HTML_FILE')
421 {
422 if (!in_array($verType, self::$verificationTypes))
423 return array('error' => array('message' => 'incorrect verification type'));
424
425 $domain = ToLower($domain);
426 $hostId = $this->getHostId($domain);
427
428 $serviceUrl = $this->getServiceUrl($this->userId, $hostId, self::API_VERIFICATION_URL, array('verification_type' => $verType));
429 $queryResult = $this->query($serviceUrl, 'POST');
430 if ($queryResult->getStatus() == self::HTTP_STATUS_OK && $queryResult->getResult() <> '')
431 {
432 $result = Json::decode($queryResult->getResult());
433
434 return array($domain => array('verification' => $result['verification_state']));
435 }
436 else
437 {
438 throw new Engine\YandexException($queryResult);
439 }
440 }
441
442
451 protected function queryOld($scope, $method = "GET", $data = NULL, $skipRefreshAuth = false)
452 {
453 if ($this->engineSettings['AUTH'])
454 {
455 $http = new \CHTTP();
456 $http->setAdditionalHeaders(
457 array(
458 'Authorization' => 'OAuth ' . $this->engineSettings['AUTH']['access_token'],
459 )
460 );
461 $http->setFollowRedirect(false);
462
463 switch ($method)
464 {
465 case 'GET':
466 $result = $http->get($scope);
467 break;
468 case 'POST':
469 $result = $http->post($scope, $data);
470 break;
471 case 'PUT':
472 $result = $http->httpQuery($method, $scope, $http->prepareData($data));
473 break;
474 case 'DELETE':
475
476 break;
477 }
478
479 if ($http->status == 401 && !$skipRefreshAuth)
480 {
481 if ($this->checkAuthExpired())
482 {
483 $this->queryOld($scope, $method, $data, true);
484 }
485 }
486
487 $http->result = Text\Encoding::convertEncoding($http->result, 'utf-8', LANG_CHARSET);
488
489 return $http;
490 }
491 }
492
502 protected function query($scope, $method = "GET", $data = NULL, $skipRefreshAuth = false)
503 {
504 if ($this->engineSettings['AUTH'])
505 {
506 $http = new HttpClient();
507 $http->setHeader('Authorization', 'OAuth ' . $this->engineSettings['AUTH']['access_token']);
508 $http->setRedirect(false);
509 switch ($method)
510 {
511 case 'GET':
512 $http->get($scope);
513 break;
514 case 'POST':
515 $http->setHeader('Content-type', 'application/json');
516 $http->post($scope, $data);
517 break;
518 case 'DELETE':
519 break;
520 }
521
522 if ($http->getStatus() == 401 && !$skipRefreshAuth)
523 {
524 if ($this->checkAuthExpired())
525 {
526 $this->query($scope, $method, $data, true);
527 }
528 }
529
530 return $http;
531 }
532 }
533}
534
535?>
static getCurrent()
Definition context.php:241
queryOld($scope, $method="GET", $data=NULL, $skipRefreshAuth=false)
Definition yandex.php:451
verifySite($domain, $verType='HTML_FILE')
Definition yandex.php:420
query($scope, $method="GET", $data=NULL, $skipRefreshAuth=false)
Definition yandex.php:502
getSiteInfoQueries($domain)
Definition yandex.php:217
const VERIFIED_STATE_NEVER_VERIFIED
Definition yandex.php:50
const VERIFIED_STATE_IN_PROGRESS
Definition yandex.php:51
addOriginalText($text, $domain)
Definition yandex.php:349