<?php
class vkParserAuth
{
    private $strlUrl, $ch;
    private $httpUserAgent = 'Mozilla/5.0 Windows NT 6.1; Win64; x64 AppleWebKit/537.36 KHTML, like Gecko Chrome/61.0.3163.91 Safari/537.36';
    private $html, $action, $doc;

    public function __construct($strUrl, $type = true)
    {
        $this->strUrl = $strUrl;
        $this->ch     = curl_init();
        $options      = [
            CURLOPT_URL            => $this->strUrl,
            CURLOPT_USERAGENT      => $this->httpUserAgent,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_FAILONERROR    => true,
        //    CURLOPT_PROXY => '194.116.163.110:65234',
         //   CURLOPT_PROXYUSERPWD => 'Kalitinua:W9e0DoM',
       //     CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5,
            CURLOPT_REFERER        => 'https://m.vk.com',
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_COOKIEJAR      =>  __DIR__ . '/cookie/cookieUserVk.cook',
            CURLOPT_COOKIEFILE     => __DIR__ . '/cookie/cookieUserVk.cook',
        ];

        if(is_dir(__DIR__ . '/cookie') === false)
        {
            mkdir(__DIR__ . '/cookie');
            file_put_contents(__DIR__ . '/cookie/.htaccess', 'Deny From All');
        }

        curl_setopt_array($this->ch, $options);
        $this->_exec();
        if(!empty($this->html))
        {
            $this->doc = new DOMDocument();
            $this->_newHtmlDoc();
        }

    }

    public function getUser()
    {
        $doc  = &$this->doc;
        $domxpath = new DOMXPath($doc);
        $element = $domxpath->query("//div[@class='op_fcont']/h2[@class='op_header']/a[@class='op_owner']");
        if ($element->length <= 0)
            return false;
        $element = $element->item(0);
        return [
            'name' => $element->getAttribute('data-name'),
            'photo' => $element->getAttribute('data-photo'),
            'url' => 'https://vk.com' . $element->getAttribute('href')
        ];
    }

    public function sendFormData($email, $pass, $code)
    {
        $doc  = &$this->doc;
        $form = $doc->getElementsByTagName('form')->item(0);
        if(!empty($form) && $form->hasAttribute('novalidate') === true)
        {
            $this->action = $form->getAttribute('action');
            if($this->_post(['email' => $email, 'pass' => $pass]) === true)
            {
                $this->_exec();
                $this->_newHtmlDoc();
                $form = $doc->getElementsByTagName('form')->item(0);
                if(!empty($form))
                {
                    $this->action = 'https://m.vk.com' . $form->getAttribute('action');
                    if($this->post(['code' => $code]))
                        $this->_exec();
                }
                exit(header('Location: /audio/#succes'));
            }
        }
        return true;
    }

    public function logOut()
    {
        $doc  = &$this->doc;
        $domxpath = new DOMXPath($doc);
        $elements = $domxpath->query("//li[@class='mmi_logout']/a");
        if ($elements->length > 0)
        {
            curl_setopt($this->ch, CURLOPT_URL, $elements->item(0)->getAttribute('href'));
            $this->_exec();
            exit(header('Location: /audio/#logOut'));
        }
    }

    private function _newHtmlDoc()
    {
        $old_libxml_error = libxml_use_internal_errors(true);
        $this->doc->loadHTML($this->html);
        libxml_use_internal_errors($old_libxml_error);
    }

    private function _post($params = [])
    {
        if(empty($params))
            return false;

        curl_setopt_array($this->ch,
            [
                CURLOPT_URL        => $this->action,
                CURLOPT_POST       => true,
                CURLOPT_POSTFIELDS => http_build_query($params, '', '&')
            ]
        );
        return true;
    }

    private function _exec()
    {
        $options = [
            CURLOPT_HEADER         => true,
            CURLOPT_USERAGENT      => $this->httpUserAgent,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
          //  CURLOPT_PROXY => '194.116.163.110:65234',
          //  CURLOPT_PROXYUSERPWD => 'Kalitinua:W9e0DoM',
           // CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_FAILONERROR    => true,
            CURLOPT_REFERER        => 'https://m.vk.com',
            CURLOPT_FOLLOWLOCATION => false,
        ];
        curl_setopt_array($this->ch, $options);
        $this->html = curl_exec($this->ch);
        if($this->html === false)
            return false;
        $http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302)
        {
            list($header) = explode("\r\n\r\n", $this->html, 2);
            $matches = array();
            $header = preg_replace('#(Location:|URI:)\s/#i', 'Location: https://m.vk.com', $header);
            preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
            $url = trim(array_pop($matches));
            $url_parsed = parse_url($url);
            if (!empty($url_parsed))
            {
                curl_setopt($this->ch, CURLOPT_URL, $url);
                $this->_exec();
                return true;
            }
        }
        list(,$body) = explode("\r\n\r\n", $this->html, 2);
        $this->html = $body;
        return true;
    }

    public function __destruct()
    {
        curl_close($this->ch);
        $this->doc = null;
    }
}
?>