<?

include_once 'sys/inc/start.php';
include_once 'sys/inc/compress.php';
include_once 'sys/inc/sess.php';
include_once 'sys/inc/home.php';
include_once 'sys/inc/settings.php';
include_once 'sys/inc/db_connect.php';
include_once 'sys/inc/ipua.php';
include_once 'sys/inc/fnc.php';
include_once 'sys/inc/user.php';
include_once 'sys/inc/shif.php';

/**
*
* выполнить sql запрос
* ALTER TABLE `user` ADD COLUMN `vk_id` INT(11) NULL DEFAULT NULL
*
* создать приложение вконтакте и заполнить поля нижу
*
* В нужое место разместить
include_once H.'vklogin.php';
returnLink();
*
*
*/

//print_r($_GET);
$app_id = '3077769'; //в настройках приложения
$secret_key = 'U8tz19FJVm1GJD7diVas'; //в настройках приложения

$redirect_url = urlencode($_SERVER['SERVER_NAME'] . '/vklogin.php');

if (isset($_REQUEST['code'])) {
$url = "https://api.vkontakte.ru/oauth/access_token?client_id={$app_id}&client_secret={$secret_key}&code=" . $_REQUEST['code'];
$response = json_decode(@file_get_contents($url));
$arrR = json_decode(@file_get_contents("https://api.vkontakte.ru/method/users.get?uid={$response->user_id}&access_token={$response->access_token}&fields=uid,first_name,last_name,nickname,screen_name,sex,bdate,city,country,photo_big"))->
response;
$num = mysql_query("SELECT * FROM `user` WHERE `vk_id`='{$response->user_id}'");

if (isset($arrR) && !empty($arrR) && mysql_num_rows($num) == 0) {
$arr = array();

$pass = passgen(8);

$arr['ank_name'] = $arrR[0]->first_name;
$arr['nick'] = $arrR[0]->screen_name;
$nickq = mysql_query('SELECT `id` FROM `user` WHERE LOWER(`nick`) = LOWER(\'' . $arr['nick'] . '\')');
while (mysql_num_rows($nickq) > 0) {
$arr['nick'] = $arrR[0]->screen_name . mt_rand(1, 100);
$nickq = mysql_query('SELECT `id` FROM `user` WHERE LOWER(`nick`) = LOWER(\'' . $arr['nick'] . '\')');
}
$arr['pass'] = shif($pass);
$arr['vk_id'] = $response->user_id;

$sex = $arrR[0]->sex;
if ($sex == 1)
$arr['pol'] = 0;
else
$arr['pol'] = 1;

$bdate = isset($arrR[0]->bdate) ? explode('.', $arrR[0]->bdate) : array();
$arr['ank_d_r'] = isset($bdate[0]) ? $bdate[0] : null;
$arr['ank_m_r'] = isset($bdate[1]) ? $bdate[1] : null;
$arr['ank_g_r'] = isset($bdate[2]) ? $bdate[2] : null;

$city = $arrR[0]->city;
//$country = $arr[0]->country;
$photo = $arrR[0]->photo_big;

$arrR = json_decode(@file_get_contents("https://api.vkontakte.ru/method/places.getCityById?cids={$city}&access_token={$response->access_token}"))->
response;
$arr['ank_city'] = $arrR[0]->name;
$arr['date_reg'] = time();

$key = $val = array();
foreach ($arr as $k => $v) {
$key[] = "`$k`";
$val[] = "'$v'";
}
$keys = implode(', ', $key);
$vals = implode(', ', $val);

$q = mysql_query("INSERT INTO `user`($keys) VALUES($vals)");
$q = mysql_query("SELECT LAST_INSERT_ID() as `last_id` FROM `user` LIMIT 1");
$id = mysql_fetch_assoc($q);
$photop = pathinfo($photo);
$photo = file_get_contents($photo);
$photo_path = H . 'sys/avatar/' . $id['last_id'] . '.' . $photop['extension'];
if (file_exists($photo_path))
unlink($photo_path);
file_put_contents($photo_path, $photo);

$num = mysql_query("SELECT * FROM `user` WHERE `vk_id`='{$response->user_id}'");
auth_vk();
header('Location: /info.php');
} elseif (mysql_num_rows($num) > 0) {
auth_vk();
header('Location: /info.php');
}
}

function auth_vk() {
global $num;
$user = mysql_fetch_assoc($num);
$_SESSION['id_user'] = $user['id'];

if (isset($_POST['aut_save']) && $_POST['aut_save'] == 1) {
setcookie('id_user', $user['id'], time() + 60 * 60 * 24 * 365);
setcookie('pass', cookie_encrypt($_POST['pass'], $user['id']), time() + 60 * 60 * 24 * 365);
}
mysql_query("UPDATE `user` SET `date_aut` = " . time() . " WHERE `id` = '$user[id]' LIMIT 1");
mysql_query("UPDATE `user` SET `date_last` = " . time() . " WHERE `id` = '$user[id]' LIMIT 1");
}

function returnLink() {
global $app_id, $redirect_url;
echo '<a href="http://api.vkontakte.ru/oauth/authorize?client_id=' . $app_id . '&scope=offline&redirect_uri=' . $redirect_url .
'&response_type=code&display=touch" class="vk_auth">Авторизация вконтакте</a>';
}