[
  {
    "path": ".gitignore",
    "content": ".idea/\nvendor/\ncomposer.lock\nindex.php"
  },
  {
    "path": "ChangeLog",
    "content": "== 0.1.7\n* Added ability to select the API version.\n* Fixed bug #8.\n* Update PHPDoc.\n\n== 0.1.6\n* Added namespace.\n\n== 0.1.5\n* Added Composer support.\n* Connection to the api server in keep-alive mode.\n* Added json and xml formats api's response (default php array).\n* Rename and update some methods in VK class.\n\n== 0.1.4\n* Fixed bug changing the option \"v\" in API methods.\n* Added sample use VK library (search, play and download music).\n\n== 0.1.3\n* Update example-1.php\n* Update documentation.\n\n== 0.1.2\n* Added authorization in test mode.\n* Update documentation.\n\n== 0.1.1\n* Added VKException class.\n* Update documentation.\n\n== 0.1.0\n* First release."
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2013 Vlad Pronsky <vladkens@yandex.ru>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE."
  },
  {
    "path": "README.md",
    "content": "# VK\n\n## По-русски\n\nКласс реализует VK API и авторизацию по OAuth протоколу.\nПо всем вопросам можно писать на <vladkens@yandex.ru>\n\n### Использование\n1. Подключите класс\n\n        require('VK.php');\n\n2. Создайте объект VK\n    1. без авторизации\n\n            $vk = new VK\\VK('{APP_ID}', '{API_SECRET}');\n\n    2. с авторизацией\n\n            $vk = new VK\\VK('{APP_ID}', '{API_SECRET}', '{ACCESS_TOKEN}');\n\n3. Если нужна авторизация\n    1. Получаем ссылку авторизации\n\n            $vk->getAuthorizeURL('{API_SETTINGS}', '{CALLBACK_URL}');\n\n    2. Получаем токен доступа по ключу из ссылки авторизации\n\n            $vk->getAccessToken('{CODE}');\n            \n    3. Проверить авторизирован ли пользователь\n            \n            $vk->isAuth(); // return bool\n\n4. Используем API\n\n        $vk->api('{METHOD_NAME}', '{PARAMETERS}');\n        \n### Другие методы\n* Установить версию API.\n    `$vk->setApiVersion({NUBMER});`\n    \n### Переменные\n* `{APP_ID}` — ID приложения вконтакте.\n* `{API_SECRET}` — Секретный код приложения.\n* `{ACCESS_TOKEN}` — Токен доступа.\n* `{API_SETTINGS}` — Запрашиваемые [права доступа](http://vk.com/developers.php?oid=-1&p=Права_доступа_приложений) приложения (через запятую).\n* `{CALLBACK_URL}` — Адрес, на который будет передан `{CODE}`.\n* `{CODE}` — Код для получения токена доступа.\n* `{METHOD_NAME}` — Имя API метода. [Все методы](http://vk.com/developers.php?oid=-1&p=Описание_методов_API).\n* `{PARAMETERS}` — Параметры соответствующего метода API.\n\n\\* Если нужно получить бесконечный токен, используете параметр `offline` в `{API_SETTINGS}`.\n\n### Лицензия\n[MIT](https://raw.github.com/vladkens/VK/master/LICENSE)\n\n## English\n\nThe PHP class for vk.com API and to support OAuth.\nYou can ask me any questions by e-mail: <vladkens@yandex.ru>\n\n### Use\n1. Connect class\n\n        require('VK.php');\n        \n2. Create VK object\n    1. without authorization\n\n            $vk = new VK\\VK('{APP_ID}', '{API_SECRET}');\n\n    2. with authorization\n\n            $vk = new VK\\VK('{APP_ID}', '{API_SECRET}', '{ACCESS_TOKEN}');\n\n3. If need authorization\n    1. Get authoriz link\n\n            $vk->getAuthorizeURL('{API_SETTINGS}', '{CALLBACK_URL}');\n\n    2. Get the token access by code from the authoriz link\n\n            $vk->getAccessToken('{CODE}');\n            \n    3. Check the status of authorization\n            \n            $vk->isAuth(); // return bool\n            \n4. Usage API\n\n        $vk->api('{METHOD_NAME}', '{PARAMETERS}');\n\n### Other methods\n* Set version of API.\n    `$vk->setApiVersion({NUBMER});`\n    \n### Variables\n* `{APP_ID}` — Your application's identifier.\n* `{API_SECRET}` — Secret application key.\n* `{ACCESS_TOKEN}` — Access token.\n* `{API_SETTINGS}` —  Access [rights requested](http://vk.com/developers.php?oid=-17680044&p=Application_Access_Rights) by your app (through comma).\n* `{CALLBACK_URL}` —  Address to which `{CODE}` will be rendered.\n* `{CODE}` — The code to get access token.\n* `{METHOD_NAME}` — Name of the API method. [All methods.](http://vk.com/developers.php?oid=-17680044&p=API_Method_Description)\n* `{PARAMETERS}` — Parameters of the corresponding API methods.\n\n\\* If you need infinite token use key `offline` in `{API_SETTINGS}`.\n\n### License\n[MIT](https://raw.github.com/vladkens/VK/master/LICENSE)"
  },
  {
    "path": "Samples/SearchPlayAndDownload/script.js",
    "content": "// Ajax\nfunction ScriptRequest(url, callback) {\n    ScriptRequest.handler = function(data) {\n        callback(data);\n    }\n    \n    url += (url.indexOf('?') > -1 ? '&' : '?') + 'callback=ScriptRequest.handler';\n    var script = document.createElement('script');\n    script.onload = script.onerror = function() {\n        document.body.removeChild(script);\n    }\n    \n    document.body.appendChild(script);\n    script.src = url;\n}\n\nfunction play_audio(aid) {\n    if (typeof play_audio.now != 'undefined') {\n        if (play_audio.now == aid) return;\n        \n        var el = document.querySelector('[data-id=\"'+play_audio.now+'\"] audio');\n        el.pause();\n        el.currentTime = 0;\n        el.style.display = \"none\";\n        el.parentElement.style.backgroundColor = \"#fff\";\n    }\n    \n    var audio = document.querySelector('[data-id=\"'+aid+'\"] audio')\n    if (audio != null) {\n        audio.style.display = \"block\";\n        audio.play();\n    } else {\n        var url = 'https://api.vk.com//method/audio.getById.json?audios='+aid+'&access_token='+vk_access_token;\n        ScriptRequest(url, function(data) {\n            audio = document.createElement('audio');\n            audio.controls = audio.autoplay = true;\n            document.querySelector('[data-id=\"'+aid+'\"]').appendChild(audio);\n            audio.setAttribute('src', data.response[0].url);\n            \n            audio.addEventListener('ended', function() {\n                var el = document.querySelector('[data-id=\"'+aid+'\"]').nextElementSibling;\n                if (el != null) {\n                    play_audio(el.getAttribute('data-id'));\n                }\n            }, true);\n        });\n    }\n    document.querySelector('[data-id=\"'+aid+'\"]').style.backgroundColor = \"#efefef\";\n    play_audio.now = aid;\n}\n\n// Set events to play link\nwindow.onload = function() {\n    var links = document.querySelectorAll('.search-result a.play');\n    for (var i = 0, il = links.length; i < il; ++i) {\n        links[i].addEventListener('click', function(event) {\n            play_audio((this.parentElement).getAttribute('data-id'));\n            event.preventDefault();\n        }, true);\n    }\n}"
  },
  {
    "path": "Samples/example-1.php",
    "content": "<!doctype html>\n    <meta charset=\"utf-8\" />\n    <style>\n    html, body { font-family: monospace; }\n    </style>\n    \n<?php\n\n/**\n * Example 1.\n * Usage VK API without authorization.\n * Some calls are not available.\n * @link http://vk.com/developers.php VK API\n */\n\nerror_reporting(E_ALL);\nrequire_once('../src/VK/VK.php');\nrequire_once('../src/VK/VKException.php');\n\ntry {\n    $vk = new VK\\VK('{YOUR_APP_ID}', '{YOUR_API_SECRET}'); // Use your app_id and api_secret\n    \n    $users = $vk->api('users.get', array(\n        'uids'   => '1234,4321',\n        'fields' => 'first_name,last_name,sex'));\n        \n    foreach ($users['response'] as $user) {\n        echo $user['first_name'] . ' ' . $user['last_name'] . ' (' .\n            ($user['sex'] == 1 ? 'Girl' : 'Man') . ')<br />';\n    }\n    \n} catch (VK\\VKException $error) {\n    echo $error->getMessage();\n}\n"
  },
  {
    "path": "Samples/example-2.php",
    "content": "<!doctype html>\n    <meta charset=\"utf-8\" />\n    <style>\n    html, body { font-family: monospace; }\n    </style>\n\n<?php\n\n/**\n * Example 2.\n * Get access token via OAuth and usage VK API.\n * @link http://vk.com/developers.php VK API\n */\n\nerror_reporting(E_ALL);\nrequire_once('../src/VK/VK.php');\nrequire_once('../src/VK/VKException.php');\n\n$vk_config = array(\n    'app_id'        => '{YOUR_APP_ID}',\n    'api_secret'    => '{YOUR_API_SECRET}',\n    'callback_url'  => 'http://{YOUR_DOMAIN}/samples/example-2.php',\n    'api_settings'  => '{ACCESS_RIGHTS_THROUGH_COMMA}' // In this example use 'friends'.\n    // If you need infinite token use key 'offline'.\n);\n\ntry {\n    $vk = new VK\\VK($vk_config['app_id'], $vk_config['api_secret']);\n    \n    if (!isset($_REQUEST['code'])) {\n        /**\n         * If you need switch the application in test mode,\n         * add another parameter \"true\". Default value \"false\".\n         * Ex. $vk->getAuthorizeURL($api_settings, $callback_url, true);\n         */\n        $authorize_url = $vk->getAuthorizeURL(\n            $vk_config['api_settings'], $vk_config['callback_url']);\n            \n        echo '<a href=\"' . $authorize_url . '\">Sign in with VK</a>';\n    } else {\n        $access_token = $vk->getAccessToken($_REQUEST['code'], $vk_config['callback_url']);\n        \n        echo 'access token: ' . $access_token['access_token']\n            . '<br />expires: ' . $access_token['expires_in'] . ' sec.'\n            . '<br />user id: ' . $access_token['user_id'] . '<br /><br />';\n            \n        $user_friends = $vk->api('friends.get', array(\n            'uid'       => '12345',\n            'fields'    => 'uid,first_name,last_name',\n            'order'     => 'name'\n        ));\n        \n        foreach ($user_friends['response'] as $key => $value) {\n            echo $value['first_name'] . ' ' . $value['last_name'] . ' ('\n                . $value['uid'] . ')<br />';\n        }\n    }\n} catch (VK\\VKException $error) {\n    echo $error->getMessage();\n}\n"
  },
  {
    "path": "Samples/example-3.php",
    "content": "<!doctype html>\n    <meta charset=\"utf-8\" />\n    <style>\n    html, body { font-family: monospace; }\n    </style>\n\n<?php\n\n/**\n * Example 3.\n * Usage VK API having access token.\n * @link http://vk.com/developers.php VK API\n */\n\nerror_reporting(E_ALL);\nrequire_once('../src/VK/VK.php');\nrequire_once('../src/VK/VKException.php');\n\n$vk_config = array(\n    'app_id'        => '{YOUR_APP_ID}',\n    'api_secret'    => '{YOUR_API_SECRET}',\n    'access_token'  => '{YOUR_ACCESS_TOKEN}'\n);\n\ntry {\n    $vk = new VK\\VK($vk_config['app_id'], $vk_config['api_secret'], $vk_config['access_token']);\n    \n    $user_friends = $vk->api('friends.get', array(\n        'uid'       => '12345',\n        'fields'    => 'uid,first_name,last_name',\n        'order'     => 'name'\n    ));\n    \n    foreach ($user_friends['response'] as $key => $value) {\n        echo $value['first_name'] . ' ' . $value['last_name'] . ' ('\n            . $value['uid'] . ')<br />';\n    }\n    \n} catch (VK\\VKException $error) {\n    echo $error->getMessage();\n}\n\n?>"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"name\": \"vladkens/vk\",\n    \"type\": \"library\",\n    \"description\": \"The PHP class for vk.com API with support OAuth.\",\n    \"keywords\": [\"vk\", \"vk.com\", \"api\", \"oauth\"],\n    \"license\": \"MIT\",\n    \"authors\": [\n        {\n            \"name\": \"Vlad Pronsky\",\n            \"email\": \"vladkens@yandex.ru\"\n        }\n    ],\n    \"support\": {\n        \"email\": \"vladkens@yandex.ru\",\n        \"issues\": \"https://github.com/vladkens/VK/issues\",\n        \"source\": \"https://github.com/vladkens/VK\"\n    },\n    \"require\": {\n        \"php\": \">=5.3.0\"\n    },\n    \"autoload\": {\n        \"psr-0\": {\n            \"VK\": \"src\"\n        }\n    }\n}"
  },
  {
    "path": "src/VK/VK.php",
    "content": "<?php\n\n/**\n * The PHP class for vk.com API and to support OAuth.\n * @author Vlad Pronsky <vladkens@yandex.ru>\n * @license https://raw.github.com/vladkens/VK/master/LICENSE MIT\n */\n\nnamespace VK;\n\nclass VK\n{\n    /**\n     * VK application id.\n     * @var string\n     */\n    private $app_id;\n\n    /**\n     * VK application secret key.\n     * @var string\n     */\n    private $api_secret;\n\n    /**\n     * API version. If null uses latest version.\n     * @var int\n     */\n    private $api_version;\n\n    /**\n     * VK access token.\n     * @var string\n     */\n    private $access_token;\n\n    /**\n     * Authorization status.\n     * @var bool\n     */\n    private $auth = false;\n\n    /**\n     * Instance curl.\n     * @var Resource\n     */\n    private $ch;\n\n    const AUTHORIZE_URL = 'https://oauth.vk.com/authorize';\n    const ACCESS_TOKEN_URL = 'https://oauth.vk.com/access_token';\n\n    /**\n     * Constructor.\n     * @param   string $app_id\n     * @param   string $api_secret\n     * @param   string $access_token\n     * @throws  VKException\n     */\n    public function __construct($app_id, $api_secret, $access_token = null)\n    {\n        $this->app_id = $app_id;\n        $this->api_secret = $api_secret;\n        $this->setAccessToken($access_token);\n\n        $this->ch = curl_init();\n    }\n\n    /**\n     * Destructor.\n     */\n    public function __destruct()\n    {\n        curl_close($this->ch);\n    }\n\n    /**\n     * Set special API version.\n     * @param   int $version\n     * @return  void\n     */\n    public function setApiVersion($version)\n    {\n        $this->api_version = $version;\n    }\n\n    /**\n     * Set Access Token.\n     * @param   string $access_token\n     * @throws  VKException\n     * @return  void\n     */\n    public function setAccessToken($access_token)\n    {\n        $this->access_token = $access_token;\n    }\n\n    /**\n     * Returns base API url.\n     * @param   string $method\n     * @param   string $response_format\n     * @return  string\n     */\n    public function getApiUrl($method, $response_format = 'json')\n    {\n        return 'https://api.vk.com/method/' . $method . '.' . $response_format;\n    }\n\n    /**\n     * Returns authorization link with passed parameters.\n     * @param   string $api_settings\n     * @param   string $callback_url\n     * @param   bool $test_mode\n     * @return  string\n     */\n    public function getAuthorizeUrl($api_settings = '',\n                                    $callback_url = 'https://api.vk.com/blank.html', $test_mode = false)\n    {\n        $parameters = array(\n            'client_id' => $this->app_id,\n            'scope' => $api_settings,\n            'redirect_uri' => $callback_url,\n            'response_type' => 'code'\n        );\n\n        if ($test_mode)\n            $parameters['test_mode'] = 1;\n\n        return $this->createUrl(self::AUTHORIZE_URL, $parameters);\n    }\n\n    /**\n     * Returns access token by code received on authorization link.\n     * @param   string $code\n     * @param   string $callback_url\n     * @throws  VKException\n     * @return  array\n     */\n    public function getAccessToken($code, $callback_url = 'https://api.vk.com/blank.html')\n    {\n        if (!is_null($this->access_token) && $this->auth) {\n            throw new VKException('Already authorized.');\n        }\n\n        $parameters = array(\n            'client_id' => $this->app_id,\n            'client_secret' => $this->api_secret,\n            'code' => $code,\n            'redirect_uri' => $callback_url\n        );\n\n        $rs = json_decode($this->request(\n            $this->createUrl(self::ACCESS_TOKEN_URL, $parameters)), true);\n\n        if (isset($rs['error'])) {\n            throw new VKException($rs['error'] .\n                (!isset($rs['error_description']) ?: ': ' . $rs['error_description']));\n        } else {\n            $this->auth = true;\n            $this->access_token = $rs['access_token'];\n            return $rs;\n        }\n    }\n\n    /**\n     * Return user authorization status.\n     * @return  bool\n     */\n    public function isAuth()\n    {\n        return !is_null($this->access_token);\n    }\n\n    /**\n     * Check for validity access token.\n     * @param   string $access_token\n     * @return  bool\n     */\n    public function checkAccessToken($access_token = null)\n    {\n        $token = is_null($access_token) ? $this->access_token : $access_token;\n        if (is_null($token)) return false;\n\n        $rs = $this->api('getUserSettings', array('access_token' => $token));\n        return isset($rs['response']);\n    }\n\n    /**\n     * Execute API method with parameters and return result.\n     * @param   string $method\n     * @param   array $parameters\n     * @param   string $format\n     * @param   string $requestMethod\n     * @return  mixed\n     */\n    public function api($method, $parameters = array(), $format = 'array', $requestMethod = 'get')\n    {\n        $parameters['timestamp'] = time();\n        $parameters['api_id'] = $this->app_id;\n        $parameters['random'] = rand(0, 10000);\n\n        if (!array_key_exists('access_token', $parameters) && !is_null($this->access_token)) {\n            $parameters['access_token'] = $this->access_token;\n        }\n\n        if (!array_key_exists('v', $parameters) && !is_null($this->api_version)) {\n            $parameters['v'] = $this->api_version;\n        }\n\n        ksort($parameters);\n\n        $sig = '';\n        foreach ($parameters as $key => $value) {\n            $sig .= $key . '=' . $value;\n        }\n        $sig .= $this->api_secret;\n\n        $parameters['sig'] = md5($sig);\n\n        if ($method == 'execute' || $requestMethod == 'post') {\n            $rs = $this->request(\n                $this->getApiUrl($method, $format == 'array' ? 'json' : $format), \"POST\", $parameters);\n        } else {\n            $rs = $this->request($this->createUrl(\n                $this->getApiUrl($method, $format == 'array' ? 'json' : $format), $parameters));\n        }\n        return $format == 'array' ? json_decode($rs, true) : $rs;\n    }\n\n    /**\n     * Concatenate keys and values to url format and return url.\n     * @param   string $url\n     * @param   array $parameters\n     * @return  string\n     */\n    private function createUrl($url, $parameters)\n    {\n        $url .= '?' . http_build_query($parameters);\n        return $url;\n    }\n\n    /**\n     * Executes request on link.\n     * @param   string $url\n     * @param   string $method\n     * @param   array $postfields\n     * @return  string\n     */\n    private function request($url, $method = 'GET', $postfields = array())\n    {\n        curl_setopt_array($this->ch, array(\n            CURLOPT_USERAGENT => 'VK/1.0 (+https://github.com/vladkens/VK))',\n            CURLOPT_RETURNTRANSFER => true,\n            CURLOPT_SSL_VERIFYPEER => false,\n            CURLOPT_POST => ($method == 'POST'),\n            CURLOPT_POSTFIELDS => $postfields,\n            CURLOPT_URL => $url\n        ));\n\n        return curl_exec($this->ch);\n    }\n\n}\n\n;\n\n"
  },
  {
    "path": "src/VK/VKException.php",
    "content": "<?php\n\n/**\n * The exception class for VK library.\n * @author Vlad Pronsky <vladkens@yandex.ru>\n * @license https://raw.github.com/vladkens/VK/master/LICENSE MIT\n */\n\nnamespace VK;\n \nclass VKException extends \\Exception {  }\n\n"
  }
]