WhoisController.php 2.67 KB
<?php

namespace app\commands;

use PHPHtmlParser\Dom;
use yii\db\Query;
use yii;
use yii\console\Controller;
use yii\db\Expression;
use yii\helpers\Console;
use app\components\Collection;
use app\models\Host;

/**
 * Парсинг запрещенных ресурсов в РФ.
 */
class WhoisController extends Controller
{
    public $count = 30;

    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }
        return true;
    }

    public function options($actionID)
    {
        return ['count'];
    }

    public function optionAliases()
    {
        return ['c' => 'count'];
    }

    /**
     * Парсинг запрещенных ресурсов в РФ.
     */
    public function actionIndex()
    {
        $hosts = (new Query())
            ->select('id, domain')
            ->from('{{%host}}')
            ->where(['in', 'wis_status', [Host::STATUS_NONE, Host::STATUS_BUSY]])
            ->orderBy('rand()')
            ->limit($this->count)
            ->all();
        $domainsArr = [];
        foreach ($hosts as $h) {
            $domainsArr[] = $h['domain'];
        }
        if ($domainsArr) {
            $result = Collection::getRawData(Yii::$app->params['registrators_urls'][0], $domainsArr);
            if (!$result['errorno']) {//без ошибок
                $dom = new Dom;
                $dom->loadStr($result['data']);
                $trArr = $dom->find('.tablesorter tbody tr');
                if (!count($trArr)) {
                    foreach ($domainsArr as $d) {
                        $this->upWhois($d);
                    }
                }
                $hasAnswer = [];
                foreach ($trArr as $tr) {
                    $domain = $tr->find('td')[0]->text;
                    $status = $tr->find('td')[1]->text;
                    $hasAnswer[] = $domain;
                    $this->upWhois($domain, $status);
                }
                foreach (array_diff($domainsArr, $hasAnswer) as $domainDisable) {
                    $this->upWhois($domainDisable);
                }
            } else {
                echo $result['errorno'] . ' ' . $result['errormessage'];
            }
        }
    }

    private function upWhois($domain, $statusStr = 'Занят')
    {
        switch ($statusStr) {
            case 'Свободен':
                $status = Host::STATUS_FREE;
                break;
            default:
                $status = Host::STATUS_BUSY;
        }

        Yii::$app->db->createCommand()
            ->update('{{%host}}', ['wis_status' => $status, 'wis_date' => new Expression('NOW()')], ['domain' => $domain])
            ->execute();
    }

}