<?php
/**
* PHP клас за сваляне на видео файлове от vbox7
* @author GNNMobile.eu
*/
class VboxDownload
{
	private $maxMediaServers = 30;

	public function getUrl($videoID)
	{
		$return = array(
			'success' => false,
			'url' => null,
			'errors' => null
		);
		if (!preg_match('/^[a-z0-9]+$/u', $videoID)) {
			$return['errors'][] = 'Невалидно video-id';
		}
		if ($return['errors'] == null) {
			for ($id = 1; $id < $this->maxMediaServers; $id++) {
				$mediaServer = str_pad($id, 2, "0", STR_PAD_LEFT);
				$dir = substr($videoID, 0, 2);
				$url = sprintf("http://media%s.vbox7.com/s/%s/%s.flv", $mediaServer, $dir, $videoID);
				if ($this->remoteFileExists($url) === true) {
					$return['success'] = true;
					$return['url'] = $url;
					break;
				}
			}
			if ($return['success'] === false) {
				$return['errors'][] = 'Няма намерен файл';
			}
		}
		return $return;
	}

	private function remoteFileExists($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 0.1);
		if (curl_exec($ch)) {
			$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if ($statusCode == 200) {
				return true;
			}
		}
		curl_close($ch);
		return false;
	}
}