<?php
///////////////////////////////////////////////////////////////////////////
const NEWIPTV_ARCHIVE_ID = 'main';
/////////////////////////////////////////////
    const VERSION_MAJOR                     = '1';
    const VERSION_MINOR                     = '0';
    const VERSION_SUBMINOR                  = '6';
    const VERSION_DATE                      = '25.01.21';
    const VERSION_TIME                      = '00:00';
    ///////////////////////////////////////////////////////////////////////

class MyPlugIN_Api
{ 
	#const API_URL = '';
	private $cookie = null;
	public $settings = null;
	public $account = null;
	private $is_logged = null;
	private $disk_space = 0;


	public function is_logged_in()
	{ return $this->is_logged; }

	public function get_account($plugin_cookies)
	{ return $this->account; }

	public function get_settings()
	{ return $this->settings; }
	
///////////////////////////////////////////////////////////////////////////

    	public function api_exception($e, $def_caption, $is_playback)
	{
		$is_mylogin_error = ($e instanceof MyPlugIN_Exception);
        	if (!$is_mylogin_error)
        	{
			if ($e->getMessage() == 0)
			{
				hd_print('General exception:------------------');
				$text='Неправильный логин или пароль';
				$text2='Обновитесь по POP UP MENU->Обновить';
				$cookies_file = "/config/" . DuneSystem::$properties['plugin_name'] . "_plugin_cookies.properties";
				shell_exec("sed -i '/is_login_correct\|login\|pass/d' $cookies_file");
			}
			else
			{
				$text=$e->getMessage();
				$text2='';
			}
            		hd_print('General exception: ' . $e->getMessage());
            		$title = !$is_playback ? 'Оповещение' : 'Не удалось подключиться к Интернету.';
            		$text_lines = $is_playback ? array() : array($text, $text2);
            		return new DuneException(	$def_caption, -1, ActionFactory::show_error(false, $title, $text_lines));
        	}
        	hd_print('MyPlugIN API exception: ' .
            		'code=' . $e->getCode() . ', message=' . $e->getMessage());

        	$ecode = $e->getCode();
		$emessage = $e->getMessage();
        	#$fatal = $ecode == 5 || $ecode == 6 ||
            		#$ecode == 11 || $ecode == 12 || $ecode == 13;

		$fatal = $ecode == 12 && $emessage == 'Authentification error' || $ecode == 17 || $ecode == 5;
        	if ($fatal)
            		$this->unset_login();
        	$title = !$is_playback ? 'Error' : $emessage;
        	$text_lines = $is_playback ? array() :
            	array('Описание: ' . $emessage,
                	'Код ошибки: ' . $ecode);
        	return new DuneException(
            		$def_caption, $ecode,
            		ActionFactory::show_error($fatal, $title, $text_lines));
		
	}
///////////////////////////////////////////////////////////////////////////
	public function unset_login()
	{
		hd_print("unset_login");
		$this->cookie = null;
		$this->is_logged = false;
		$this->account = null;
		$this->settings = null;
		
	}
///////////////////////////////////////////////////////////////////////////
	public function ping()
	{		
	#$ping = MyPlugIN_Config::API_URL . '/stalker_portal/api/v2/users/1/ping';
	$doc = HD::get_daten("users/".$this->account."/ping", $this->cookie);
	#$doc = HD::http_get_document($ping);
	hd_print("DOC_PING -------> $doc");
	}
///////////////////////////////////////////////////////////////////////////
	public function check_login($plugin_cookies)
	{
		$this->ping();
		hd_print("check_login");
		echo ("cookie: " . $this->cookie);
		$is_login_correct = isset($plugin_cookies->is_login_correct) ? $plugin_cookies->is_login_correct : false;
		echo ("is_login_corect: " . $is_login_correct);
		$is_logged = $this->is_logged_in();
		echo ("is_logged: "); var_dump($is_logged);
		if($this->cookie == '')
		{
			hd_print("ooopppppps");
			if(isset($plugin_cookies->token))
				$this->cookie = $plugin_cookies->token;
		}
		$is_log = isset($is_logged) ? $is_logged : false;
		if ($is_login_correct == 1 && $is_logged != 1)
		{
			hd_print("Авторизация...................");
			$this->login_mylogin($plugin_cookies);
			echo ("cookie1: " . $this->cookie);
		}	
	}
	
	public function get_smart_token($plugin_cookies)
	{
		$duid= trim(shell_exec("cat /tmp/sysinfo.txt | grep -E '^serial_number' | awk -F' ' '{print $2}'"));
		$login = $plugin_cookies->login;
		$pass = $plugin_cookies->pass;	
		$post_data = "platform=sandroid&duid=$duid&lid=ru";
		$url = "http://smart.prostotv.com/smartup/auth";
		$A = json_decode(HD::http_post_document($url, $post_data));
		$aid=$A->aid;
		$post_data = "platform=sandroid&duid=$duid&lid=ru&signin[login]=$login&signin[password]=$pass&aid=$aid";
		$url = "http://smart.prostotv.com/smartup/auth";
		$A = json_decode(HD::http_post_document($url, $post_data));
		$smart_token=$A->token;
		$plugin_cookies->smart_token = $smart_token;
		$plugin_cookies->duid = $duid;
	}
	
///////////////////////////////////////////////////////////////////////////
	public function logout()
	{
		$this->unset_login();
	}
///////////////////////////////////////////////////////////////////////////
	public function get_sett()
	{
			$set = HD::get_daten("users/" . $this->account . "/settings", $this->cookie);
			hd_print("get-setting-- $set");
			$set = json_decode($set);
		return $set;
	}
	
	public function login_mylogin($plugin_cookies)
	{
		$token = isset($plugin_cookies->token) ? $plugin_cookies->token : 0;
		hd_print("login_mylogin");
		if (!isset($plugin_cookies->login))
			throw new Exception('Логин не введен');
		if (!isset($plugin_cookies->pass))
			throw new Exception('Пароль не введен');
		$doc = HD::get_token($plugin_cookies->login, $plugin_cookies->pass);
		hd_print("--->>> get_login: $doc");
		$data = json_decode($doc);
		/////////////////////////////////////////////////////
		if(isset($data->access_token))
		{
			hd_print("login is ok");
			$this->is_logged = true;
			$plugin_cookies->is_login_correct = true;
			$this->cookie = $data->access_token;
			$plugin_cookies->token = $data->access_token;
			$this->settings = $data->expires_in;
			$this->account = $data->user_id;
		}
		else
		{
			try
			{
				hd_print("login is not ok->$doc");
				//$data = json_decode($doc);
			}		
			catch (Exception $e)
			{
				$this->is_logged = false;
				hd_print("loged falled");
				$plugin_cookies->is_login_correct = false;
				throw $this->api_exception($e,'Ошибка авторизации', false);
			}
		}		
		if (isset($data->error))
		{
			try
			{
				$error = 'Error';		
				throw new Exception($error);		
				// Code following an exception is not executed.
				//echo 'Never executed';		
			}
			catch (Exception $e)
			{
				throw $this->api_exception($e,'General', false);
			}
		}
	}
	
	public function get_new_login($login, $pass, &$plugin_cookies)
	{
		$doc = HD::get_token($login, $pass);
		hd_print("--->>> get_login2: $doc");
		$data = json_decode($doc);
		/////////////////////////////////////////////////////
		if(isset($data->access_token))
		{
			hd_print("login is ok");
			$this->is_logged = true;
			$plugin_cookies->is_login_correct = true;
			$this->cookie = $data->access_token;
			$this->settings = $data->expires_in;
			$this->account = $data->user_id;
		}
		else
		{
			try
			{
				$this->is_logged = false;
				$plugin_cookies->is_login_correct = false;
				hd_print("login is not ok");
				$error = 'Ошибка авторизации';		
				throw new Exception($error);
			}		
			catch (Exception $e)
			{
				$this->is_logged = false;
				hd_print("loged falled");
				$plugin_cookies->is_login_correct = false;
				throw $this->api_exception($e,'Ошибка авторизации', false);
			}
		}	
	}
	
	public function get_account_settings()
	{
		$doc = HD::get_daten("users/".$this->account."/settings",$this->cookie);
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,"get_account_settings failed.", true);
		}
		return $data;
	}
	public function api_set_setting($streamer, $value){
		hd_print("value in api----->$value");
		$doc = HD::put_sett($this->account, $streamer, $value, $this->cookie);
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,"api_set_setting failed.", true);
		}
		return $data;
	}
///////////////////////////////////////////////////////////////////////////
	
	public function load_radio_list()
		{
			$doc = HD::get_daten("users/".$this->account."/radio-channels" ,$this->cookie);
			//hd_print("--->>> get_list_radio: $doc");
			file_put_contents('/tmp/radio_list.txt', $doc);
			$xml = json_decode($doc);

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

        		if ($xml->status !== 'OK')
        		{
        		    hd_print("Error: unexpected node '" . $xml->getName() . "'. Expected: 'response'");
        		    throw new Exception('Invalid document');
        		}
			return $xml;
		}
///////////////////////////////////////////////////////////////////////////
	public function get_channel_list($plugin_cookies)
		{
		$this->check_login($plugin_cookies);
		$this->ping();
			$doc = HD::get_daten("users/".$this->account."/tv-channels" ,$this->cookie);
            hd_print("get_list_tv--->>>$doc");
            try
            {
                $data = json_decode($doc);
            }
            catch (Exception $e)
            {
                throw $this->api_exception($e,'get_group_list failed.', true);
            }
            return $data;
        }
	//////////////////////////////////////////
	public function get_real_url($url, $id, &$plugin_cookies)
		{
		#hd_print("url_real--->>>$url");	
		if($url == '')
		{
			return $url;
		}
		else
		{
		$url = $this->get_channel_url($id, $plugin_cookies);
		return $url;
		}
        }
	public function get_channel_url($id, $plugin_cookies)
		{
		$this->check_login($plugin_cookies);
		$this->ping();
			$doc = HD::get_daten("users/".$this->account."/tv-channels/$id/link" ,$this->cookie);
            hd_print("get_channel_url--->>>$doc");
            try
            {
                $data = json_decode($doc);
            }
            catch (Exception $e)
            {
                throw $this->api_exception($e,'get_group_list failed.', true);
            }
            return $data;
        }
	//////////////////////////////////////////
	public function get_group_tv_channel($group)
	{
		$doc = HD::get_daten("users/".$this->account."/tv-genres/".$group."/tv-channels" ,$this->cookie);
		#hd_print("get_group_list--->>>$doc");
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_group_list failed.', true);
		}
		return $data;	
	}
	public function get_group_tv()
    {
		$doc = HD::get_daten("users/".$this->account."/tv-genres" ,$this->cookie);
		#hd_print("get_group_list--->>>$doc");
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_group_list failed.', true);
		}
		$data = HD::sort_tv_groups($data);
		
		return $data;	
	}
///////////////////////////////////////////////////////////////////////////
	public function get_stalker_epg($day_start,$channel_id,$sid, &$plugin_cookies)
	{
		//date_default_timezone_set(UTC);
		$end_time = mktime(23,59,59,date('m', $day_start), date('d', $day_start), date('Y', $day_start));
		$doc = HD::get_daten('users/'.$this->account.'/tv-channels/'.$channel_id.'/epg&from='.$day_start.'&to='.$end_time.'', $this->cookie);
		if (is_null($doc))
			throw new Exception('Can not fetch epg');
		$json = json_decode($doc);
		return $json;
	}
///////////////////////////////////////////////////////////////////////////
	public function get_url($cid,$gmt,$protect_code,&$plugin_cookies)
	{
		$epg_shift = isset($plugin_cookies->epg_shift) ? $plugin_cookies->epg_shift : 0;
		$time_shift = isset($plugin_cookies->time_shift) ? $plugin_cookies->time_shift : 0;		
		if ($time_shift != 0)
		{
			$time_shift = '&time_shift='.$plugin_cookies->time_shift;
		}
		else
			$time_shift = '';		
		if($gmt >= 0) //архив
		{
			$start_time = mktime(0,0,0,date('m', $gmt), date('d', $gmt), date('Y', $gmt));
			$end_time = mktime(23,59,59,date('m', $gmt), date('d', $gmt), date('Y', $gmt));
			$doc = HD::get_daten('users/'.$this->account.'/tv-channels/'.$cid.'/epg&from='.$start_time.'&to='.$end_time, $this->cookie);		
			$doc = json_decode($doc);		
			foreach ($doc->results as $check)
			{
				if ($check->start == $gmt)
				{
					$id = $check->id;
					$spuelen = 'ok';
					break;
				}
				else
				{
					if (($gmt > $check->start) && ($gmt < $check->end)) 
					{
						$id = $check->id;
						$start = $check->start;
						$end = $check->end;
						$spuelen = 'not';
					}
				}
			}		
			$doc = HD::get_daten('users/'.$this->account.'/epg/'.$id.'/link', $this->cookie);
			$doc = json_decode($doc);
			if ($spuelen == 'ok') 
			{
				//hd_print("okkkkkkkkkkk".$gmt."---".$start);
				$url = str_replace('http://', 'http://ts://',  $doc->results);
			}
			if ($spuelen == 'not') 
			{
				hd_print("noooooooooot".$gmt."------".$start);
				$url = $doc->results;
				/*$pere = $gmt - $start;
				$kor = explode('&start=', $url);
				$rest = explode('&duration', $url);
				$kore = $pere + strstr($kor[1], '&', true);
				$url = $kor[0].'&start='.$kore.'&duration'.$rest[1];*/
				$url = str_replace($start, $gmt, $url);
				$url = str_replace('http://', 'http://ts://', $url);
			}
		} 
		else 
		{
			$doc=HD::get_daten("users/".$this->account."/tv-channels/".$cid."/link" ,$this->cookie);
			$doc = json_decode($doc);
			if ($doc->status == "ERROR")
			{
				$url = "";
			} 
			else 
			{
				//$url = /* str_replace('http://', 'http://ts://',  */$doc->results/* )*/;
				$url = str_replace('http://', 'http://ts://', $doc->results);
				//hd_print("прямой эфир-----> $url");
				$url = str_replace('ffrt2 ', '', $url);
			}
		}
		hd_print("END_URL----->$url");
		return $url;
	}

//////////////////////////////////////////////////////////////////////////
	public function get_vod_cat($plugin_cookies)
	{
	$this->check_login($plugin_cookies);
		$doc = HD::get_daten('users/'.$this->account.'/video-categories', $this->cookie);
		try
		{
			$data = json_decode($doc);
			//echo ("--->>> get_vod_categories: " . print_r($data, true));
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_genres failed.', false);
		}				
		return $data;
	}


	public function get_vod_genres()
	{	
		$doc = HD::get_daten('users/'.$this->account.'/video-genres', $this->cookie);
		try
		{
			$data = json_decode($doc);
			//echo ("--->>> get_vod_genres: " . print_r($data, true));
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_genres failed.', false);
		}				
		return $data;
	}

	public function smart_get_vod_genres($title, $plugin_cookies)
	{	
		$url = "http://smart.prostotv.com/smartup/vod/catalog";
		if ($title == "Все категории")
		$post_data="platform=sandroid&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token . "&module=vod&get=genres";
		else
		$post_data="platform=sandroid&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token . "&module=vod&get=genres&category=" . urlencode($title);
		$doc = HD::http_post_document($url, $post_data);
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_genres failed.', false);
		}				
		return $data;
	}

///////////////////////////////////////////////////////////////////////////
//TODO 2
	public function get_vod_list($aid,$bid,$add,&$plugin_cookies)
	{
	//$this->check_login($plugin_cookies);
	echo("--$aid-----$bid---$add");

		if($aid == 'search')
		{
			$bid = urlencode($bid);
			$url = "http://smart.prostotv.com/smartup/vod/search";
			$post_data="platform=sandroid&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token . "&module=vod&phrase=$bid&sort=added&page=$add";
			$doc=HD::http_post_document($url, $post_data);
		}
		elseif($aid == 'all')
		{		
			$url = "http://smart.prostotv.com/smartup/vod/catalog";
			$post_data="platform=sandroid&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token . "&module=vod&get=videos&category=&genre=&year=&sort=added&page=$add";
			$doc=HD::http_post_document($url, $post_data);
		}
		else
		{
			$pre=explode("/", $bid);
			$cat=$pre[0];
			$cat=($cat == "all_categories") ? "" : $cat=urlencode($cat);
			$genre=$pre[1];
			$genre=($genre == "Все жанры") ? "" : urlencode($genre);
			
			$url = "http://smart.prostotv.com/smartup/vod/catalog";
			$post_data="platform=sandroid&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token . "&module=vod&get=videos&category=$cat&genre=$genre&year=&sort=added&page=$add";
			
			$doc=HD::http_post_document($url, $post_data);
		}
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}				
		return $data;	
	}
	
///////////////////////////////////////////////////////////////////////////
	public function get_vod_info($id)
	{
		if (preg_match('/karaoke/i', $id)) {
		$id = str_replace("karaoke", "", $id);
		$doc = HD::get_daten('users/'.$this->account.'/karaoke/'.$id, $this->cookie);
		hd_print("--->>> get_vod_info: $doc");
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}
		}
		else {
		$doc = HD::get_daten('users/'.$this->account.'/video/'.$id, $this->cookie);
		hd_print("--->>> get_vod_info: $doc");
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}
		}
		return $data;	
			}

///////////////////////////////////////////////////////////////////////////
	public function get_vod_serie_url($id, $serie)
	{
		$doc = HD::get_daten('users/'.$this->account.'/video/'.$id.'/episodes/'.$serie.'/link', $this->cookie); 
		hd_print("--->>> get_vod_url: $doc");
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}				
		return $data;	
	}
	
	public function get_vod_url($id)
	{
		if (preg_match('/karaoke/i', $id))
		{
		$id = explode('karaoke', $id);
		$doc = HD::get_daten('users/'.$this->account.'/karaoke/'.$id[1].'/link', $this->cookie);
		}
		else
		$doc = HD::get_daten('users/'.$this->account.'/video/'.$id.'/link', $this->cookie); 
		hd_print("id---$id--->>> get_vod_url: $doc");
		try
		{
			$data = json_decode($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}				
		return $data;	
	}

///////////////////////////////////////////////////////////////////////////
//TODO 3
	public function set_settings($control_id, $new_value)
	{
		if($control_id == 'pcode')
		{
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.$new_value);
		}
		else if($control_id == 'timeshift')
		{
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.$new_value);
		}
		else
		{
			$doc = self::API_URL.'settings_set.php?var='.$control_id.'&val='.$new_value;
		}
		hd_print("--->>> set_settings: $doc");
		try
		{
			$data = simplexml_load_string($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,"get settings $control_id failed.", false);
		}
		

		if (!isset($data->error))
		{	if($control_id != 'pcode')
			hd_print("sapis");
			 $this->settings->{$control_id}->value = $new_value;
		}
		else
		{
			throw new MyPlugIN_Exception($data->error->message, $code,false);
		}
	
	}
	public function get_set_pro()
	{
	if(isset($this->cookie)) {
	$paket = HD::get_daten('users/'.$this->account, $this->cookie);
	#hd_print("paket---------->$paket");
	$paket = json_decode($paket);
	#$paket = $paket->results->tariff_plan;
	}
	else
	$paket = 0;
	return $paket;
	}

///////////////////////////////////////////////////////////////////////////
//TODO 4
	public function set_channels_order($id,$act)
	{
		if($id == -1)
		{
			$doc = MyPlugIN_Config::API_URL.'/set_channels_order.php?act='.$act;
		}
		else
		{
			$doc = MyPlugIN_Config::API_URL.'/set_channels_order.php?id='.$id.'&act='.$act;
		}
		hd_print("--->>> set_channels_order: $doc");
		$data = $this->json_fetch($doc,0);
		if (intval($data->message->code) == 4)
		{	
			return $data;
		}
		else
		{
			throw new MyPlugIN_Exception($data->error->message, $code);
		}

	}

///////////////////////////////////////////////////////////////////////////
	public function get_channels_order()
	{
		$doc = MyPlugIN_Config::API_URL.'/get_channels_oder.php';
		hd_print("--->>> get_channels_order: $doc");
		$data = $this->json_fetch($doc,0);
		return $data;	
	}

///////////////////////////////////////////////////////////////////////////
	public function json_fetch($url,$islogin)
	{
		if($islogin == 0)
		{
			if (strpos($url,"?") === false )
			{
		    		$url .= "?$this->cookie";
			}
			else
			{
		    		$url .= "&$this->cookie";
			}
		}
		$doc = HD::http_get_document($url);
		#hd_print("--->>> get_json: $doc");
		$data = simplexml_load_string($doc);
		#hd_print("--->>> get_xml: $doc");
		if ($data === null)
                throw new Exception('Invalid data received from server');
		if (isset($data->error))
            	{
			$code = intval($data->error->code);
			hd_print("API error: URL '$url' " .
                    	"returned error with code=$code, msg=" .
                    	$data->error->message . '.');
			throw new MyPlugIN_Exception($data->error->message, $code);
		}
		return $data;
	}
	///////////////////////////////////////////////////////////////////////////
	private function do_get_edit_subscription_defs(&$plugin_cookies, $handler, $add_params)
    {
        $defs = array();
        $login = isset($plugin_cookies->login) ? $plugin_cookies->login : '';
        $pass = isset($plugin_cookies->pass) ? $plugin_cookies->pass : '';

        ControlFactory::add_text_field($defs,
            $handler, $add_params,
            'login', 'Логин на prostotele.vision:',
            $login, false, false, false, false, 750);

        ControlFactory::add_text_field($defs,
            $handler, $add_params,
            'pass', 'Пароль на prostotele.vision:',
            $pass, false, true, false, false, 750);

        ControlFactory::add_vgap($defs, 50);

        ControlFactory::add_button($defs,
            $handler, $add_params,
            'apply_sub', null, 'Ввести', 300);

        ControlFactory::add_vgap($defs, -3);

        ControlFactory::add_close_dialog_button($defs,
            'Отмена', 300);
			
		#ControlFactory::add_label($defs, '', '');
		ControlFactory::add_img_label($defs, '', '<text dy="7" size="small"> Нажмите </text><icon>gui_skin://special_icons/controls_button_blue.aai</icon><text dy="7" size="small"> для вызова экранной клавиатуры</text>', 0, 0, 0);
        return $defs;
    }
	/////////////////////////////////////////////////////////////////////////// 
   public function do_get_edit_subscription_action(&$plugin_cookies, $handler, $add_params = null) 
	{
        	return ActionFactory::show_dialog(
            		'Введите данные логин и пароль',
            		$this->do_get_edit_subscription_defs(
                	$plugin_cookies, $handler, $add_params),
            		true);

	} 
///////////////////////////////////////////////////////////////////////////
    public function apply_sub(&$plugin_cookies, &$user_input)
    {
        if (!isset($user_input->control_id) || $user_input->control_id != 'apply_sub')
        {
	    #hd_print("dalshe: $user_input->control_id");
            return false;
	}
	if ($user_input->control_id == 'close')
        {
		hd_print("close");
		return array(
               'need_close_dialog' => true,
                'action' =>ActionFactory::close_dialog());
        }


        if ($user_input->login === '' || $user_input->pass === '')
        {
		return array(
                'need_close_dialog' => false,
                'action' =>ActionFactory::show_error(false,'Error',array('Поле Логин не может быть пустым.')));
        }

	$plugin_cookies->login = $user_input->login;
	$plugin_cookies->pass = $user_input->pass;
	$islogged = $this->is_logged_in();
	if ($islogged == true)
	{
        	$this->logout();
	}
        $post_action = null;
        try
        {
            $this->login_mylogin($plugin_cookies);
        }
        catch (DuneException $e)
        {
            $post_action = $e->get_error_action();
        }
		
	if ($this->is_logged == false)
	{
	hd_print("--------------------");
		return array('need_close_dialog' => false, 'action' =>ActionFactory::show_error(false,'Error',array('Неправильный логин или пароль')));
	}
        return array(
            'need_close_dialog' => true,
            'action' => $post_action);
    }
	///////////////////////////////////////////////////////////////////////////
  /*  public function get_icon($id)
    {
        $archive = DefaultArchive::get_archive(
            NEWIPTV_ARCHIVE_ID,
            NEWIPTV_ARCHIVE_URL_PREFIX);

        return $archive->get_archive_url($id);
    }*/

    public function get_group_icon($group_id)
    {
        return $this->get_icon("group_$group_id.png");
    }

    public function get_channel_icon($channel_id)
    {
        return $this->get_icon("channel_$channel_id.png");
    }

	public function get_icon_genre($name)
    {
        return 'plugin_file://icons/vod/' . $name;
    }

    
    	public function get_archive()
	{
		if ($this->disk_space == 100)
		{
			return DefaultArchive::get_archive('ico', MyPlugIN_Config::ARCHIVE_URL);
		}
		else
		{
			return null;
		}
	}

	public function get_icon($icon)
	{
		if ($this->disk_space == 1)
		{
			$archive = DefaultArchive::get_archive('ico',MyPlugIN_Config::ARCHIVE_URL); 
			return $archive->get_archive_url($icon);
		}
		else
		{
			$icon_url = $icon;
			return $icon_url;
		} 
	}
}
