<?php
///////////////////////////////////////////////////////////////////////////

class HD
{
	public static function is_map($a)
	{
		return is_array($a) &&
			array_diff_key($a, array_keys(array_keys($a)));
	}

	///////////////////////////////////////////////////////////////////////

	public static function has_attribute($obj, $n)
	{
		$arr = (array) $obj;
		return isset($arr[$n]);
	}
	///////////////////////////////////////////////////////////////////////

	public static function get_map_element($map, $key)
	{
		return isset($map[$key]) ? $map[$key] : null;
	}

	///////////////////////////////////////////////////////////////////////

	public static function starts_with($str, $pattern)
	{
		return strpos($str, $pattern) === 0;
	}

	///////////////////////////////////////////////////////////////////////
	public static function get_playlist()
	{
	$A = file_get_contents("/tmp/sysinfo.txt");
	preg_match("|serial_number: (.*?)\n|ms", $A, $matches);
	$serial = $matches[1];
	$opts = array(
	"http"=>array(
	"method"=>"GET",
	"header"=>"SERIAL: $serial"));
	$context = stream_context_create($opts);
	return file_get_contents("http://plugins.mydune.ru/ddaaff/free_tv/playlist.php", true, $context);
	}

	public static function format_timestamp($ts, $fmt = null)
	{
		// NOTE: for some reason, explicit timezone is required for PHP
		// on Dune (no builtin timezone info?).

		if (is_null($fmt))
			$fmt = 'Y:m:d H:i:s';

		$dt = new DateTime('@' . $ts);
		return $dt->format($fmt);
	}

	///////////////////////////////////////////////////////////////////////

	public static function format_duration($msecs)
	{
		$n = intval($msecs);

		if (strlen($msecs) <= 0 || $n <= 0)
			return "--:--";

		$n = $n / 1000;
		$hours = $n / 3600;
		$remainder = $n % 3600;
		$minutes = $remainder / 60;
		$seconds = $remainder % 60;

		if (intval($hours) > 0)
		{
			return sprintf("%d:%02d:%02d", $hours, $minutes, $seconds);
		}
		else
		{
			return sprintf("%02d:%02d", $minutes, $seconds);
		}
	}

	///////////////////////////////////////////////////////////////////////

	public static function encode_user_data($a, $b = null)
	{
		$media_url = null;
		$user_data = null;

		if (is_array($a) && is_null($b))
		{
			$media_url = '';
			$user_data = $a;
		}
		else
		{
			$media_url = $a;
			$user_data = $b;
		}

		if (!is_null($user_data))
			$media_url .= '||' . json_encode($user_data);

		return $media_url;
	}
  ///////////////////////////////////////////////////////////////////////////////////
	public static function sec_format_duration($secs)
	{
		$n = intval($secs);
		if (strlen($secs) <= 0 || $n <= 0)
			return "--:--";
		$hours = $n / 3600;
		$remainder = $n % 3600;
		$minutes = $remainder / 60;
		$seconds = $remainder % 60;
		if (intval($hours) > 0)
			return sprintf("%d:%02d:%02d", $hours, $minutes, $seconds);
		else
			return sprintf("%02d:%02d", $minutes, $seconds);
	}
	///////////////////////////////////////////////////////////////////////

	public static function decode_user_data($media_url_str, &$media_url, &$user_data)
	{
		$idx = strpos($media_url_str, '||');

		if ($idx === false)
		{
			$media_url = $media_url_str;
			$user_data = null;
			return;
		}

		$media_url = substr($media_url_str, 0, $idx);
		$user_data = json_decode(substr($media_url_str, $idx + 2));
	}

	///////////////////////////////////////////////////////////////////////

	public static function create_regular_folder_range($items,
		$from_ndx = 0, $total = -1, $more_items_available = false)
	{
		if ($total === -1)
			$total = $from_ndx + count($items);

		if ($from_ndx >= $total)
		{
			$from_ndx = $total;
			$items = array();
		}
		else if ($from_ndx + count($items) > $total)
		{
			array_splice($items, $total - $from_ndx);
		}

		return array
		(
			PluginRegularFolderRange::total => intval($total),
			PluginRegularFolderRange::more_items_available => $more_items_available,
			PluginRegularFolderRange::from_ndx => intval($from_ndx),
			PluginRegularFolderRange::count => count($items),
			PluginRegularFolderRange::items => $items
		);
	}

	///////////////////////////////////////////////////////////////////////

	public static function http_get_document($url, $opts = null)
	{
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,    30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,    true);
		curl_setopt($ch, CURLOPT_TIMEOUT,           30);
		curl_setopt($ch, CURLOPT_USERAGENT,         'DuneHD/1.0');
		curl_setopt($ch, CURLOPT_URL,               $url);

		if (isset($opts))
		{
			foreach ($opts as $k => $v)
				curl_setopt($ch, $k, $v);
		}

		hd_print("HTTP fetching '$url'...");

		$content = curl_exec($ch);
		$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		if($content === false)
		{
			$err_msg = "HTTP error: $http_code (" . curl_error($ch) . ')';
			hd_print($err_msg);
			//throw new Exception($err_msg);
		}

		if ($http_code != 200)
		{
			$err_msg = "HTTP request failed ($http_code)";
			hd_print($err_msg);
			//throw new Exception($err_msg);
		}

		hd_print("HTTP OK ($http_code)");

		curl_close($ch);

		return $content;
	}

	///////////////////////////////////////////////////////////////////////

	public static function http_post_document($url, $post_data)
	{
		return self::http_get_document($url,
			array
			(
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => $post_data
			));
	}

	///////////////////////////////////////////////////////////////////////

	public static function parse_xml_document($doc)
	{
		$xml = simplexml_load_string($doc);

		if ($xml === false)
		{
			hd_print("Error: can not parse XML document.");
			hd_print("XML-text: $doc.");
			throw new Exception('Illegal XML document');
		}

		return $xml;
	}

	///////////////////////////////////////////////////////////////////////

	public static function make_json_rpc_request($op_name, $params)
	{
		static $request_id = 0;

		$request = array
		(
			'jsonrpc' => '2.0',
			'id' => ++$request_id,
			'method' => $op_name,
			'params' => $params
		);

		return $request;
	}

	///////////////////////////////////////////////////////////////////////////





	public static function get_mac_addr()
	{
		static $mac_addr = null;

		if (is_null($mac_addr))
		{
			$mac_addr = shell_exec(
				'ifconfig  eth0 | head -1 | sed "s/^.*HWaddr //"');

			$mac_addr = trim($mac_addr);

			hd_print("MAC Address: '$mac_addr'");
		}

		return $mac_addr;
	}

	///////////////////////////////////////////////////////////////////////////

	// TODO: localization
	private static $MONTHS = array(
		'January',
		'February',
		'March',
		'April',
		'May',
		'June',
		'July',
		'August',
		'September',
		'October',
		'November',
		'December',
	);

	public static function format_date_time_date($tm)
	{
		$lt = localtime($tm);
		$mon = self::$MONTHS[$lt[4]];
		return sprintf("%02d %s %04d", $lt[3], $mon, $lt[5] + 1900);
	}

	public static function format_date_time_time($tm, $with_sec = false)
	{
		$format = '%H:%M';
		if ($with_sec)
			$format .= ':%S';
		return strftime($format, $tm);
	}

	public static function print_backtrace()
	{
		hd_print('Back trace:');
		foreach (debug_backtrace() as $f)
		{
			hd_print(
				'  - ' . $f['function'] .
				' at ' . $f['file'] . ':' . $f['line']);
		}
	}


	///////////////////////////////////////////////////////////////////////
	public static function http_post_document2($url, $post_data, $opts=null)
	{
		$arr [CURLOPT_POST] = true;
		$arr [CURLOPT_POSTFIELDS] = $post_data;
		if (isset($opts))
		{
			foreach ($opts as $k => $v)
			   $arr[$k] = $v;
		}
		return self::http_get_document($url, $arr);
	}

	///////////////////////////////////////////////////////////////////////////////////
	public static function http_get_document2($url, $opts = null)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 	0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 	0);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,    10);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,    true);
		curl_setopt($ch, CURLOPT_TIMEOUT,           10);
		curl_setopt($ch, CURLOPT_USERAGENT,         "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
		curl_setopt($ch, CURLOPT_ENCODING,          1);
		curl_setopt($ch, CURLOPT_URL,               $url);

		if (isset($opts))
		{
			foreach ($opts as $k => $v)
				curl_setopt($ch, $k, $v);
		}
		hd_print("HTTP fetching '$url'...");
		$content = curl_exec($ch);
		$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if($content === false)
		{
			$err_msg = "HTTP error: $http_code (" . curl_error($ch) . ')';
			hd_print($err_msg);
		}
		if ($http_code != 200)
		{
			$err_msg = "HTTP request failed ($http_code)";
			hd_print($err_msg);
		}

		hd_print("HTTP OK ($http_code)");
		curl_close($ch);
		return $content;
	}


///////////////////////////////////////////
	public static function get_yandex_epg($yandex_tv, $day_start_ts)
	{
	$pre=explode("/", $yandex_tv);

		if (file_exists(DuneSystem::$properties['tmp_dir_path']."/channel_yandex_tv_"  . $pre[2] . "_" . $pre[4] . "_" . $day_start_ts))
			$epg = unserialize(file_get_contents(DuneSystem::$properties['tmp_dir_path']."/channel_yandex_tv_"  . $pre[2] . "_" . $pre[4] . "_" . $day_start_ts));
		else {

		$url = "https://tv.yandex.ru";
		$opts = array (CURLOPT_SSL_VERIFYPEER => false);
		$html = HD::http_get_document($url, $opts);
		preg_match('|window.__INITIAL_STATE__ = (.*?);\n        window.__INITIAL_SK__ = (.*?);\n|ms', $html, $matches);
		$user = json_decode($matches[1]);
		$initial_sk = json_decode($matches[2]);
		$yandexuid = $user->user->yandexuid;
		$x_tv_sk = $initial_sk->key;
		$epg_date = date("Y-m-d", $day_start_ts);
		$url = "https://" . $yandex_tv ."/schedule?selectedDay=" . $epg_date;
		$opts = array (CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_COOKIE => "yandexuid=$yandexuid");
		$opts[CURLOPT_HTTPHEADER] = array(
					'content-type: application/json',
					'x-requested-with: XMLHttpRequest',
					'x-tv-sk: ' . $x_tv_sk);
		$doc = json_decode(HD::http_get_document($url, $opts));
		$epg = array();
		$last_time = 0;
		foreach($doc->schedule->events as $epg_item)
			{
			//$u_time = strtotime($epg_item->start);
			$u_time = strtotime($epg_item->start  . "GMT+3");
			$last_time = $u_time;
			$epg[$last_time]["name"] = $epg_item->title;

//$epg_item->program->type->name |сериалы|
			$epg[$last_time]["desc"] = empty($epg_item->program->description)?  "" : $epg_item->program->description;
			}
			file_put_contents(DuneSystem::$properties['tmp_dir_path']."/channel_yandex_tv_"  . $pre[2] . "_" . $pre[4] . "_" . $day_start_ts, serialize($epg));
			}
			//ksort($epg, SORT_NUMERIC);
		return $epg;
	}
///////////////////////////////////////////
	public static function get_peers_epg($doc)
	{
	$epg = array();
	$doc = HD::http_get_document2($doc);
	$doc = json_decode($doc);
	$last_time = 0;

		foreach ($doc->telecastsList as $key) {
		$time = $key->date->year ."/" . $key->date->month . "/" . $key->date->day . " " . $key->date->hour . ":" . $key->date->minute . ":" . $key->date->second;
		if(!$time)
		return NULL;
	   $last_time = strtotime($time  . "GMT+3");
		$epg[$last_time]["name"] = $key->title;
		if (!isset($key->title))
		$epg[$last_time]["name"] = 'ERROR';
		if (!$key->title)
		$epg[$last_time]["name"] = 'ERROR';
		$epg[$last_time]["desc"] = $key->description;
		$epg[$last_time]["nachalo"] = $last_time;
		$epg[$last_time]["konez"] = $time;
		}
return $epg;
	}

/////////////////////////////////////////////////////////GET LOCAL TMEZONE
public static function get_local_time_zone_offset() {
	exec((file_exists('/etc/TZ')? 'TZ=`cat /etc/TZ` ' : '') . 'date +%z', $tz, $rc);
	$local_tz = (($rc != 0) || (count($tz) != 1) || !is_numeric($tz[0]))? '' : $tz[0];
	if ($local_tz <> '') {
		$sign = 1;
		$sign_ch = substr($local_tz, 0, 1);
		if ($sign_ch == '-') {
			$sign = -1;
		} else if ($sign_ch == '+') {
			$sign = +1;
		} else return '';
		$tz_hh = intval(substr($local_tz, 1, 2));
		$tz_mm = intval(substr($local_tz, 3, 2));
		return $sign * ($tz_hh * 60 + $tz_mm) * 60;
	}
	return 0;
}

//////////////////////////////////////////////////////
	public static function get_items($path) {
		$items = array();
			$link = DuneSystem::$properties['data_dir_path'] . '/'. $path;
		if (file_exists($link))
			$items = unserialize(file_get_contents($link));
		return $items;
	}

//////////////////////////////////////////////////////
	public static function save_items($path, $items) {
			$link = DuneSystem::$properties['data_dir_path'] . '/'. $path;
		file_put_contents ($link, serialize($items));
	}

//////////////////////////////////////////////////////
	public static function get_item($path) {
		$item = '';
			$link = DuneSystem::$properties['data_dir_path'] . '/'. $path;
		if (file_exists($link))
			$item = file_get_contents($link);
		return $item;
	}

//////////////////////////////////////////////////////
	public static function save_item($path, $item) {
			$link = DuneSystem::$properties['data_dir_path'] . '/'. $path;
		file_put_contents ($link, $item);
	}


////////////////////////////////////////////////////////////////



}
/////////////////////////////////////////////////////////////////
/*
if (!file_exists("/etc/TZ"))
define('LOCAL_TZ_OFFSET', shell_exec('let B=$(date +"%b %d %T %Y" | (read a; date -d "$a" "+%s"))-$(date -u +"%b %d %T %Y" | (read a; date -d "$a" "+%s")); echo $B'));
else
define('LOCAL_TZ_OFFSET',			get_local_time_zone_offset());

function get_local_time_zone() {
	exec('TZ=`cat /etc/TZ` date +%z', $out, $rc);
	return (($rc != 0) || (count($out) != 1))? '' : $out[0];
}

function get_local_time_zone_offset() {
	$local_tz = get_local_time_zone();
	if ($local_tz <> '') {
		$sign = 1;
		$sign_ch = substr($local_tz, 0, 1);
		if ($sign_ch == '-') {
			$sign = -1;
		} else if ($sign_ch == '+') {
			$sign = +1;
		} else return '';
		$tz_hh = intval(substr($local_tz, 1, 2));
		$tz_mm = intval(substr($local_tz, 3, 2));
		return $sign * ($tz_hh * 60 + $tz_mm) * 60;
	} else return 0;
}
*/

/////////////////////////////////////////////////////////////////