<?php
class VKClient {
	const FORMAT_XML = 'XML';
	const FORMAT_JSON = 'JSON';
	const API_VERSION = '2.0';

	var $id_user;
	var $id_app;
	var $secret;
	var $format;
	var $test_mode;

	function VKClient($id_user, $id_app, $secret) {
		$this->id_user = $id_user;
		$this->id_app = $id_app;
		$this->secret = $secret;
		$this->format = self::FORMAT_JSON;
	}

	function request($method, array $data) {
		if(!isset($data['api_id'])) $data['api_id'] = $this->id_app;
		if(!isset($data['v'])) $data['v'] = self::API_VERSION;
		if(!isset($data['method'])) $data['method'] = $method;
		if(!isset($data['format'])) $data['format'] = $this->format;

		if($this->test_mode) $data['test_mode'] = 1;

		ksort($data);

		$sig = $this->sig($data);

		$url = 'http://api.vkontakte.ru/api.php?';
		foreach($data as $key => $value) $url .= $key.'='.urlencode($value).'&';
		$url .= 'sig='.$sig;

		$content = @file_get_contents($url);
		return (!$content ? false : $content);
	}

	function setFormat($f) {
		if($f != self::FORMAT_JSON && $f != self::FORMAT_XML) throw new Exception('Wrong format');
		$this->format = $f;
	}

	function sig($arr) {
		$data = '';
		foreach($arr as $key => $value) $data .= $key.'='.$value;
		return md5($this->id_user.$data.$this->secret);
	}
}
?>