<?php  namespace TGA; date_default_timezone_set('Asia/Tashkent');
require(__DIR__.'/lib/Zyberspace/Telegram/Cli/RawClient.php');
require(__DIR__.'/lib/Zyberspace/Telegram/Cli/Client.php');
require(__DIR__.'/lib/Zyberspace/Telegram/Cli/ClientException.php');

class ATelegram {
    private $tgdir = __DIR__;
    private $tgcert;
    private $tgbin;
    private $tglua;
    private $tgsocks_dir;
    private $currentProfile;
    private $tg_sender_default;
    private $TGM = false;
    private $code = 'alotg';

    public function __construct() {
		//$this->tLog("__construct","ATelegram");
        $this->defaultfile = $this->tgdir.'/default';
        $this->tgcert = $this->tgdir.'/server.pub';
        $this->tgbin = $this->tgdir.'/telegram-cli';
        $this->tglua = $this->tgdir.'/incom.lua';
		$this->tgsocks_dir = $this->tgdir."/socks/";
		
		$this->set_tg_sender_default();
		
		$optFile = $this->tgdir."/tmp/opt_".$this->tg_sender_default.'.json';
		
    }
	
	public function getCode(){ 
		return $this->code;
	}
	
	public function checkTG(){ 
		if(!empty($this->TGM)){
			$status = $this->TGM->getSelf();
			//$status = $this->TGM->getTgHelp();
			$this->tLog($status,"-------------------==ATG check STATUS: ==----------------");
			
			$this->contactsUpdate();
		} 
		
		//$status = $this->get_tg_account_self();
		
		if(empty($status)){
			if(!empty($this->tg_sender_default)){
				$this->tLog($this->tg_sender_default,"-------------------==ATG Runnig after Stop... ==----------------");
				$this->run_profile_by_number(["TGNUMBER"=>$this->tg_sender_default]);
			}
		} 
		
		
		return true;
	}
	
	public function get_contact($phone){
		return false;
		$this->tLog($phone, "-- get_contact BEGIn CONTACT SEARCH:");
		if( (empty($this->TGM)) || (empty($this->tg_sender_default)) ){
			$this->tLog($phone, "-- get_contact NO Telegram Connect:");
			return [];
		}
		
		$phone = preg_replace("/[^0-9]/", '', $phone);
		
		$cntFile = $this->tgdir."/tmp/cnt_".$this->tg_sender_default.'.json';

		$jscontacts = (file_exists($cntFile)) ? file_get_contents($cntFile) : false;
		
		$arCont = [];
		if(!empty($jscontacts)){
			$arCnt = json_decode($jscontacts,true);
			
			foreach($arCnt as $peer){
				// $this->tLog($peer["phone"].' == '.$phone, "-- get_contact check Connect:");
				if(!empty($peer["phone"]) && $peer["phone"] == $phone){
					$arCont = $peer;
					break;
				}
			}
		}
		
		if(empty($arCont)){
			$resAdded = $this->TGM->addContact($phone,"Newcont_".substr($phone,-4)); //,"TestMe","TestMe"
			$this->tLog($resAdded, "-- get_contact Added RES:");
			
			if(!empty($resAdded[0])){
				$u = $resAdded[0];
				$this->tLog($u->id, "-- get_contact Added id RES:");

				// $resUinfo = $this->TGM->getUserInfo($u->id);
				// $this->tLog($resUinfo, "-- get_contact UINFO RES:");
				
				$resDelt = $this->TGM->deleteContact($u->id);
				$this->tLog($resDelt, "-- get_contact DELETE RES:");
				$resDelt = json_decode($resDelt,true);
				if($resDelt["result"]=="SUCCESS"){
					$resUinfo = $this->TGM->getUserInfo($u->id);
					$this->tLog($resUinfo, "-- get_contact resUinfo RES:");
					if(!empty($resUinfo->id)){
						$this->tLog($resUinfo->id, "-- get_contact resUinfo ID :");
						$arCnt[] = $resUinfo;
						$arCnt['time'] = time();
						file_put_contents($cntFile, json_encode($arCnt));
						
						return json_decode(json_encode($resUinfo),true);
					}
				}
			}
		}
		
		if(empty($arCont)){
			$resContactinfo = $this->TGM->getContactInfo($phone);
			$this->tLog($resContactinfo, "-- get_contact INFO RES:");
		}

		return $arCont;
	}
	
	public function contactsUpdate(){
		return true;
		if( (empty($this->TGM)) || (empty($this->tg_sender_default)) ){
			return false;
		}
		$cntFile = $this->tgdir."/tmp/cnt_".$this->tg_sender_default.'.json';
		$now = time();
		$ctimeout = 600;
		$jscontacts = (file_exists($cntFile)) ? file_get_contents($cntFile) : false;
		
		if(!empty($jscontacts)){
			$oContacts = json_decode($jscontacts,true);
			if(!empty($oContacts["time"])){
				$period = $now - $oContacts["time"];
				if( $period < $ctimeout ){
					$this->tLog($period,"--Contacts is updated!");
					return true;
				}
			}
		}
	
		$this->tLog("-- Contacts update time (".$period.")...".$now);
		
		$newContacts = $this->TGM->getContactList();
		
		if(!empty($newContacts)){
			$oContacts = $newContacts;
			$this->tLog(count($oContacts). "-- Contacts list count...");
		}
		
		$oContacts["time"] = time();
		file_put_contents($cntFile, json_encode($oContacts));
		
	}
	
	public function doTgMethod($prms){ 
		
		return true;
		
		/*if (!empty($prms['event']) && $prms['event'] == 'ONIMCONNECTORMESSAGEADD' && !empty($prms['data']['CONNECTOR']) && $prms['data']['CONNECTOR'] == $this->code && !empty($prms['data']['MESSAGES'])){
			return $this->on_imconnectormessageadd($prms);
		}*/

		if( (!empty($prms["tgmethod"])) || (!empty($prms["tgevent"])) ){
			$mtd = (!empty($prms["tgmethod"])) ? $prms["tgmethod"] : $prms["tgevent"];
			
			if( !empty($mtd) && method_exists($this, $mtd)){
				return $this->$mtd($prms);
			}
		}
		return false;
	}

	public function add_tgimol($tgPhone=false){
		if(empty($tgPhone)){ return false; }
		
		\AloVoice\AloVoiceConnector::eLog("-------------------==ATG Telegram validating Number: (".$tgPhone.")");
		$tgRes = $this->get_contact($tgPhone);
		
		$tgResId = (!empty($tgRes->id)) ? $tgRes->id : (!empty($tgRes["id"])) ? $tgRes["id"] : false;
		$tgResFirstName = (!empty($tgRes->first_name)) ? $tgRes->first_name : (!empty($tgRes["first_name"])) ? $tgRes["first_name"] : "Cl_".time();
		$tgResLastName = (!empty($tgRes->last_name)) ? $tgRes->last_name : (!empty($tgRes["last_name"])) ? $tgRes["last_name"] : "";
		$tgResPrintName = (!empty($tgRes->print_name)) ? $tgRes->print_name : (!empty($tgRes["print_name"])) ? $tgRes["print_name"] : "Cl_".time();
		$tgResPhone = (!empty($tgRes->phone)) ? $tgRes->phone : (!empty($tgRes["phone"])) ? $tgRes["phone"] : "";
		
		\AloVoice\AloVoiceConnector::eLog($tgResId,"-------------------==RES TG USER ID:");
		
		if(empty($tgResId)){
			return false;
		}
		
		$action = [	
			'restmethod' => 'alovoice_incom_message',
			'connector' => $this->code,
			'line' => $this->getLine(),
			'chat_id' => $tgResId,
			'name' => $tgResPrintName,
			'phone' => $tgResPhone,
			'chat_title' => $tgResPhone."_".$tgResLastName,
			'message' => "Новый контакт: ".$tgResPrintName." c номером: ".$tgResPhone,
			'message_id' => $tgResId."_".time()
		];
		
		
		if( !empty($action) ){
			return [
				'action' => $action,
				'result' => 'adding'
			];
		}
	}
	
	public function incom_tgmessage($p=false){
		return true;
		$this->tLog("-------------------==ATG incom_tgmessage ==----------------");
		/*
			$action = [
				'restmethod' => 'alovoice_incom_message',
				'connector' => '',
				'line' => '',
				'chat_id' => '',
				'message_id' => '',
				'message' => ''
			];

		*/
		if(!empty($_SERVER)) { 
			//$this->tLog($_SERVER,"--== TELEGRAM LUA INCOMING _SERVER:");
			if(!empty($_SERVER['argv'])) { $this->tLog($_SERVER['argv'],"--== TELEGRAM LUA INCOMING ARGV:"); }		
		}
		$this->tLog($_REQUEST,"--== TELEGRAM LUA INCOMING REQUEST:");
		$this->tLog($_FILES,"--== TELEGRAM LUA INCOMING FILES:");
		//$ifile = $this->getPostFileUrl();
		//ALVC::eLog($ifile,"--== TELEGRAM PROC ifile:");
		$arMsg = json_decode($_REQUEST["datas"],1);
		
		if( !empty($ifile) ){
			if(empty($arMsg["text"])){ $arMsg["text"] = ''; }
			if(!empty($arMsg["media"]["caption"])){
				$arMsg["text"] = $arMsg["text"]." ".$arMsg["media"]["caption"];
			}
			if(empty($arMsg["text"])){ $arMsg["text"] = 'File...'; }
		}
		
		if(empty($arMsg["to"])){
			return ['error' => 'nomsg'];
		}
		
		if(!empty($arMsg["text"])){
			$ansTo = $arMsg["from"]["id"];
			if( $arMsg["to"]["peer_type"] == "channel"){
				$ansTo = $arMsg["to"]["id"];
			}
			if( $arMsg["to"]["peer_type"] == "chat"){
				$ansTo = $arMsg["to"]["id"];
			}
			if($arMsg["text"]=="userlist"){
				$arUsers = \AloVoice\AloVoiceConnector::getUsersList();
				
				$tgMsg = '';
				$n = 1;
				if(!empty($arUsers["result"])){
					foreach($arUsers["result"] as $user){
						\AloVoice\AloVoiceConnector::eLog($user,"--== user Check Loop USER");
						$tgMsg .= $n.". ".$user["NAME"]." ".$user["LAST_NAME"];
						if(!empty($user["PERSONAL_MOBILE"])) { $tgMsg .= " ".$user["PERSONAL_MOBILE"]; }
						$tgMsg .= "\n";
						
						$n++;
					}
				}
				$resSend = self::send_telegram_msg(["toid"=>$arMsg["from"]["id"],"message"=>$tgMsg]);
				\AloVoice\AloVoiceConnector::eLog($resSend,"--== RES TG SEND USERsList");
				return ["ok"];
			}	
			
			if(preg_match("/[\s]{0,}(inn|INN|инн|ИНН)[\s]{0,}([0-9]{9})/",$arMsg["text"],$innmtchs)){
				
				\AloVoice\AloVoiceConnector::eLog($innmtchs,"--== INN Check Question:");
				if(!empty($innmtchs[2]) && strlen($innmtchs[2])==9){
					$resInn = \AloVoice\AloVoiceConnector::requesTaxInn($innmtchs[2]);
					\AloVoice\AloVoiceConnector::eLog($resInn,"--== INN Check Question:");
					if(!empty($resInn)){
						$insMsg = 'Информация по инн: '.$innmtchs[2]."\n";
						foreach($resInn as $ik=>$iv){
							$insMsg .= $ik.': '.$iv."\n";
						}
					}
					\AloVoice\AloVoiceConnector::eLog($insMsg,"--== INN Answer MSG RES:");
					
					$resSend = self::send_telegram_msg(["toid"=>$arMsg["from"]["id"],"message"=>$insMsg] );
					\AloVoice\AloVoiceConnector::eLog($resSend,"--== RES TG SEND USERsList");
				}
				
				return ["ok"];
			}
		}
		
		if( $arMsg["to"]["peer_type"] == "channel"){
			return ['error' => 'channel msg'];
		}
		
		if( $arMsg["to"]["peer_type"] == "chat"){
			return ['error' => 'Group chat msg'];
		}
		
		if( (!empty($arMsg["to"]["username"])) && ( (substr($arMsg["to"]["username"],-3) == "bot") || ($arMsg["to"]["username"]=="BotFather") ) ){
			return ['error' => 'Bot msg'];
		}
		
		
		if(!empty($arMsg["out"]) && $arMsg["to"]["peer_id"]!="124987160"){
			$this->tLog($arMsg,"--== TELEGRAM Out MSG:");
			return ['error' => 'outgoing msg'];
		}
		
		$action = [	
			'restmethod' => 'alovoice_incom_message',
			'connector' => $this->code,
			'line' => $this->getLine(),
		];
		
		if(!empty( $arMsg["to"]["id"] ) && !empty($arMsg["out"])){
			$action['chat_id'] = $arMsg["to"]["id"];
		}
		elseif(!empty( $arMsg["from"]["id"] )){
			$action['chat_id'] = $arMsg["from"]["id"];
		}
		
		if(!empty( $arMsg["to"]["print_name"] ) && !empty($arMsg["out"])){
			$action['name'] = $arMsg["to"]["print_name"];
		}
		elseif(!empty( $arMsg["from"]["print_name"] )){
			$action['name'] = $arMsg["from"]["print_name"];
			//$loadPic = $this->TGM->loadUserPhoto($arMsg["from"]["id"]);
			//$loadPic = $this->TGM->loadUserPhoto($arMsg["from"]["print_name"]);
			//$this->tLog($loadPic,"--== TELEGRAM INCOMING USER LoadPhoto:");
			//#6924234565432453120
		}
		
		if(!empty( $arMsg["from"]["phone"] ) && empty($arMsg["out"])){
			$action['phone'] = $arMsg["from"]["phone"];
		}
		elseif(!empty( $arMsg["to"]["phone"] ) && !empty($arMsg["out"])){
			$action['phone'] = $arMsg["to"]["phone"];
		}
		
		if(!empty( $arMsg["id"] )){
			$action['message_id'] = $arMsg["id"];
		}
		
		if( !empty( $arMsg["text"]) ){
			$action['message'] = $arMsg["text"];
		}
		
		if( (!empty($_FILES["ifile"])) && (!empty($arMsg["media"]))){
			
			$profileDwnFldr = (!empty($arMsg["to"]["phone"])) ? $this->tgdir."/profiles/prf_".$arMsg["to"]["phone"].'/downloads/' : $this->tgdir."/profiles/".$this->currentProfile.'/downloads/';
			
			$this->tLog("--== TELEGRAM INCOMING File Check TMP File: [".file_exists($_FILES["ifile"]["tmp_name"])."]");
			$this->tLog("--== TELEGRAM INCOMING File Check Dwn File: [".file_exists($profileDwnFldr.$_FILES["ifile"]["name"])."]");
			if(file_exists($profileDwnFldr.$_FILES["ifile"]["name"])){
				$action['filepath'] = $profileDwnFldr.$_FILES["ifile"]["name"];
			}
			
		}
		
		if( (empty($_FILES)) && (!empty($arMsg["media"]))){
			//if( $arMsg["media"]["type"]== 'photo' ){
				//$ldFile = $this->TGM->loadPhoto($arMsg["id"]);
				//$ldFile = $this->TGM->loadFile($arMsg["id"]);
				//$this->tLog($ldFile,"--== TELEGRAM INCOMING MSG LoadPhoto: [id: ".$arMsg["id"]."]");
			//}
		}
		
		/*
		$file = getPostFileUrl($arMsg["to"]["phone"]);
		if(!empty($file)){
			$action['files'] = [$file];
		}
		*/
			// photo //opt
			// files //opt
			//{"tgevent":"incom_tgmessage","datas":"{\"to\":{\"last_name\":\"Unit\",\"peer_type\":\"user\",\"id\":\"$010000008f2eca0cb4c16968733747e7\",\"flags\":720897,\"access_hash\":1,\"username\":\"technounit\",\"peer_id\":214576783,\"print_name\":\"Techno_Unit\",\"phone\":\"998974244100\",\"first_name\":\"Techno\"},\"date\":1611715531,\"unread\":false,\"flags\":256,\"out\":false,\"text\":\"Test msg\",\"service\":false,\"from\":{\"peer_type\":\"user\",\"id\":\"$01000000182773071d3a41e62f1c9b0b\",\"username\":\"kuldash\",\"access_hash\":1,\"flags\":196609,\"peer_id\":124987160,\"print_name\":\"\u041a\u0443\u043b\u044f\",\"phone\":\"998977076909\",\"first_name\":\"\u041a\u0443\u043b\u044f\"},\"id\":\"0100000018277307cc9e0000000000001d3a41e62f1c9b0b\"}"}
		
		if( !empty($action) ){
			return [
				'action' => $action,
				'result' => 'recieved'
			];
		}
		return ['res'=>'error'];
	}
	/*
	{"tgevent":"incom_tgmessage","datas":"{\"to\":{\"last_name\":\"\u041d\u0410\u0412\u0420\u0423\u0417\u041e\u0412\",\"peer_type\":\"user\",\"id\":\"$01000000182773071d3a41e62f1c9b0b\",\"flags\":196609,\"access_hash\":1,\"username\":\"kuldash\",\"peer_id\":124987160,\"print_name\":\"\u041a\u0423\u041b\u0414\u0410\u0428_\u0428\u0443\u0445\u0440\u0430\u0442\u043e\u0432\u0438\u0447_\u041d\u0410\u0412\u0420\u0423\u0417\u041e\u0412\",\"phone\":\"998977076909\",\"first_name\":\"\u041a\u0423\u041b\u0414\u0410\u0428 \u0428\u0443\u0445\u0440\u0430\u0442\u043e\u0432\u0438\u0447\"},\"date\":1612877328,\"unread\":true,\"flags\":259,\"out\":true,\"text\":\"Proverka isxodyashiy iz tgshki\",\"service\":false,\"from\":{\"last_name\":\"Unit\",\"peer_type\":\"user\",\"id\":\"$010000008f2eca0cb4c16968733747e7\",\"flags\":720899,\"access_hash\":1,\"username\":\"technounit\",\"peer_id\":214576783,\"print_name\":\"Techno_Unit\",\"phone\":\"998974244100\",\"first_name\":\"Techno\"},\"id\":\"0100000018277307c1a10000000000001d3a41e62f1c9b0b\"}"}
	
	{"tgevent":"incom_tgmessage","datas":"{\"to\":{\"last_name\":\"\u041d\u0410\u0412\u0420\u0423\u0417\u041e\u0412\",\"peer_type\":\"user\",\"id\":\"$01000000182773071d3a41e62f1c9b0b\",\"flags\":196609,\"access_hash\":1,\"username\":\"kuldash\",\"peer_id\":124987160,\"print_name\":\"\u041a\u0423\u041b\u0414\u0410\u0428_\u0428\u0443\u0445\u0440\u0430\u0442\u043e\u0432\u0438\u0447_\u041d\u0410\u0412\u0420\u0423\u0417\u041e\u0412\",\"phone\":\"998977076909\",\"first_name\":\"\u041a\u0423\u041b\u0414\u0410\u0428 \u0428\u0443\u0445\u0440\u0430\u0442\u043e\u0432\u0438\u0447\"},\"date\":1612877410,\"unread\":true,\"flags\":16643,\"out\":true,\"text\":\"Proverka is Bitrix sotrudnika...........\",\"service\":false,\"from\":{\"last_name\":\"Unit\",\"peer_type\":\"user\",\"id\":\"$010000008f2eca0cb4c16968733747e7\",\"flags\":720899,\"access_hash\":1,\"username\":\"technounit\",\"peer_id\":214576783,\"print_name\":\"Techno_Unit\",\"phone\":\"998974244100\",\"first_name\":\"Techno\"},\"id\":\"0100000018277307c2a10000000000001d3a41e62f1c9b0b\"}"}
	
	
	*/
	public function getYandexTTSVoice($t){
		//https://tts.api.cloud.yandex.net/speech/v1/tts:synthesize
	}
	
	
	public function get_loaduserphoto($r){
		$ldFile = $this->TGM->loadUserPhoto($r["dt"]);
		$this->tLog($ldFile,"--== TELEGRAM INCOMING MSG LoadUserPhoto: [id: ".$r["dt"]."]");
		return $ldFile;
	}
	
	public function get_loadcontactslist($r){
		$jsContacts = $this->TGM->getContactList();
		
		$arContacts = [];
		if(!empty($jsContacts)){
			$contCnt = count($jsContacts);
			if(!empty($contCnt)){
				foreach($jsContacts as $cnt){
					if( (!empty($r["number"])) && (substr($r["number"],-9) == substr($cnt->phone,-9)) ){
						return json_decode(json_encode($cnt),1);
					}
					$arContacts[$cnt->phone] = $cnt->print_name;
				}
				$this->tLog($arContacts,"--== TELEGRAM CONTACTS: [All_cnt: ".$contCnt."]");
			}
		}
		return $arContacts;
	}
	
	public function get_testfunc($r){
		$ldFile = $this->TGM->loadFile($r["dt"]);
		$this->tLog($ldFile,"--== TELEGRAM INCOMING MSG LoadPhoto: [id: ".$r["dt"]."]");
		return $ldFile;
	}
	
	public function getPathByLink($link,$fname){
		if( empty($link) || empty($fname) ){
			return '';
		}
		
		$fname = str_replace(" ","_",$fname);
		
		$dwnDir = $this->tgdir."/profiles/".$this->currentProfile.'/downloads/';
		file_put_contents($dwnDir.$fname, fopen($link, 'r'));
		return $dwnDir.$fname;
	}
	
	public function getPostFileUrl($phone=false){
		if(empty($_FILES)){ return false; }
		$profile = ( !empty($phone) ) ? 'prf_'.$phone : $this->currentProfile;
		$dwnDir = $this->tgdir."/profiles/".$profile.'/downloads/';
		
		$dfilename = $_FILES["ifile"]["name"];
		$fPathName = $_FILES["ifile"]["tmp_name"];
		$saveTo = $this->tgdir."/profiles/".$profile.'/downloads/'.$dfilename;
		$urlFile = "/profiles/".$profile.'/downloads/'.$dfilename;
		
		$this->tLog($fPathName,"--== TELEGRAM POSTUpl fPathName:");
		$this->tLog($saveTo,"--== TELEGRAM POSTUpl saveTo:");
		$this->tLog($urlFile,"--== TELEGRAM POSTUpl urlFile:");
		
		if (file_exists($fPathName)){
			if (move_uploaded_file($fPathName, $saveTo)) {
				$retArFile = array("name"=>$dfilename,"path"=>$urlFile);
				$this->tLog($retArFile,"--== TELEGRAM retArFile:");
				
				return $retArFile;
			} else {
				return false;
			}
		}
	}


	public function get_contact_bynumber($r){
		return true;
		return $this->get_contact_info($r["number"]);
	}
	
	public function get_contact_info($number){
		return true;
		$this->tLog($number,"--== TGM Begin GEtting Contact Info Contact: ");
		if(empty($this->TGM)){ return ''; }
		$jsContacts = $this->TGM->getContactList();
		$this->tLog(count($jsContacts),"--== TGM Contact Info ContactsList count");
		$this->tLog($jsContacts,"--== TGM Contact Info ContactsList:");
		$Info = [];
		
		if(!empty($jsContacts)){
			$contCnt = count($jsContacts);
			if(!empty($contCnt)){
				foreach($jsContacts as $cnt){
					$fNum = substr($number,-9);
					$chNum = (!empty($cnt->phone)) ? substr($cnt->phone,-9) : '';
					//$this->tLog("--== TGM CheckNum: [".$fNum." == ".$chNum."]"," ");
					
					if( $fNum == $chNum ){
						$this->tLog($cnt,"--== TGM Found Contact: ");
						$Info = $cnt;
					}
				}
			}
		}
		
		if(empty($Info)) {
			$this->tLog($number,"--== TGM Contact not found");
			return  "Неизвестный контакт ".$number; 
		} else {
			$this->tLog($Info,"--== TGM Contact Founded");
			//json_decode(json_encode($Info),true); ;
			$retHTML = '<h3>'.$Info->print_name.'</h3>';
			if(!empty($Info->username)){
				$retHTML .= '<a href="https://t.me/'.$Info->username.'" target="_blank">@'.$Info->username.'</a>';
			}
			
			$this->tLog($cnt,"--== TGM Before Get User Photo for....[".$Info->id."]");
			$resPhoto = $this->TGM->loadUserPhoto($Info->id); //false; //
			$this->tLog($resPhoto,"--== TGM After Get User Photo....");
			if(!empty($resPhoto)){
				$retHTML .= '<div>'.json_encode($resPhoto).'</div>'; 
				//  {"result":"\/var\/www\/html\/bx24\/vendor\/tg\/src\/profiles\/prf_998974244100\/downloads\/download_264415650_399886.jpg","event":"download"}
				// todo: save for cache
			}
			
			return $retHTML;
		}
	}
	
	/*public function getPostFileUrl(){
		if(empty($_FILES)){ return false; }
		$dfilename = $_FILES["ifile"]["name"];
		$fPathName = $_FILES["ifile"]["tmp_name"];
		$saveTo = dirname(dirname(dirname(__DIR__))).'/tgfiles/'.$dfilename;
		$urlFile = $this->config["asterisk_host"].'/tgfiles/'.$dfilename;
		
		$this->tLog($fPathName,"--== TELEGRAM POSTUpl fPathName:");
		$this->tLog($fPathName,"--== TELEGRAM POSTUpl saveTo:");
		
		if (file_exists($fPathName)){
			if (move_uploaded_file($fPathName, $saveTo)) {
				$retArFile = array("name"=>$dfilename,"path"=>$urlFile);
				$this->tLog($retArFile,"--== TELEGRAM retArFile:");
				
				return $retArFile;
			} else {
				return false;
			}
		}
	}*/
	
	public function set_tg_sender_default($sender=false){
		return true;
		$sender = (!empty($sender)) ? preg_replace("/[^0-9]/", '', $sender) : false;
		
		if(is_numeric($sender)){
			file_put_contents($this->defaultfile,$sender);
			$this->tg_sender_default = $sender;
		}
		else {
			$defProf = file_get_contents($this->defaultfile);
			if( !empty($defProf) && is_numeric($defProf)){
				$this->tg_sender_default = $defProf;
			} else {
				$arTgAccountsList = $this->get_telegram_accounts();
				if(!empty($arTgAccountsList)){
					$this->tg_sender_default = $arTgAccountsList[0]["phone"];
				}
			}
		}
		
		if(!empty($this->tg_sender_default)){
			$this->currentProfile = 'prf_'.$this->tg_sender_default;
			if(file_exists($this->tgsocks_dir.$this->currentProfile.'.sck')){
				$this->TGM = new \Zyberspace\Telegram\Cli\Client('unix://'.$this->tgsocks_dir.$this->currentProfile.'.sck');
			}
			
			return $this->tg_sender_default;
		}
	}
	
	public function get_tg_sender_default(){
		return $this->tg_sender_default;
	}
	
	public function send_telegram_file($p){
		return true;
		
		if(!empty($p["from_number"])){ $this->set_tg_sender_default($p["from_number"]); }
		$telegram = $this->TGM; 
		$this->tLog("aTG: --=== Begin Sending TG Files... : [".json_encode($p)."]");
		if( !empty($p["toid"]) && !empty($p["link"]) ){
			$sfilename = (!empty($p["name"])) ? $p["name"] : 'down_'.time();
			$fPath = $this->getPathByLink($p["link"],$sfilename);
			
			$this->tLog("aTG: Sending TG File... : [".json_encode($fPath)."]");
			
			if(!empty($fPath)){
				if(file_exists($fPath)){
					$fs_res = $telegram->sendFile($p["toid"],$fPath);
					$this->tLog("aTG: Sent TGFile RES... : [".json_encode($fs_res)."]");
				}
			}
		}
	}
	
	public function send_telegram_photo($p){
		return true;
		/* PARAMS
			- tonumber
			- path
			- message
			- from_number //no required
			- name //no required
		*/
		
		if(!empty($p["from_number"])){ $this->set_tg_sender_default($p["from_number"]); }
		$telegram = $this->TGM; 
			
		if( !empty($p["toid"]) && !empty($p["link"]) ){
			$this->tLog("aTG: Sending TG Photo : [".json_encode($p)."]");
			$arResTg = $telegram->msg($p["toid"],$p["link"]);
			
			$this->tLog("aTG: Sending TG Photo : [".json_encode($p)."]");
			return true;
		}
		
		if( !empty($p["tonumber"]) && !empty($p["path"]) ){
			if(!file_exists($p["path"])){ return array();} else { $file_path = $p["path"];}
			
			$toNumber = preg_replace("/[^0-9]/", '', $p["tonumber"]);

			$toMessage = (!empty($p["message"])) ? $p["message"] : "";
			if(!empty($p["name"])){ 
				$toMessage = preg_replace("/#NAME#/",$p["name"],$toMessage);
				return $telegram->sendPictureCaptionToNumber($toNumber,$file_path,$toMessage,$p["name"]);
			}
			return $telegram->sendPictureCaptionToNumber($toNumber,$file_path,$toMessage);
		}
	}	
	
	public function send_telegram_msg($p){
		return true;
		/* PARAMS
			- tonumber (or toid)
			- message
			- from_number //no required
			- name //no required
		*/
		$this->tLog("aTG: Sending TG message : [".json_encode($p)."]");
		$arResTg = false;
		if(!empty($p["from_number"])){ $this->set_tg_sender_default($p["from_number"]); }
		$telegram = $this->TGM;
		
		if(!empty($p["message"])){
			$toMessage = $p["message"];
			if((!empty($p["name"]))&&(preg_match("/#NAME#/",$toMessage))){ 
				$chName = $p["name"];
				$toMessage = preg_replace("/#NAME#/",$p["name"],$toMessage);
			}
		} else {
			return false;
		}
		
		if( !empty($p["tonumber"]) ){
			$toNumber = preg_replace("/[^0-9]/", '', $p["tonumber"]);
			
			
			//$profile = (!empty($p["from_number"])) ? 'prf_'.$p["from_number"] : $this->currentProfile;
			//$telegram = new \Zyberspace\Telegram\Cli\Client('unix://'.$this->tgsocks_dir.$profile.'.sck');

			if(!empty($chName)){ 
				$arResTg = $telegram->msgToNumber($toNumber,$toMessage,$chName);
			}
			$arResTg = $telegram->msgToNumber($toNumber,$toMessage);
		}
		
		elseif( !empty($p["toid"]) ){
			$arResTg = $telegram->msg($p["toid"],$toMessage);
		}
		
		return $arResTg;
	}		
		
	
	public function delete_telegram_account($params){
		return true;
		if(!empty($params["TGNUMBER"])){ $tgNumber = preg_replace("/[^0-9]/", '', $params["TGNUMBER"]); }
		if(!empty($tgNumber)){
			$this->stop_profile_by_number($tgNumber);
			
			$tgprofile = "prf_".$tgNumber;
			$tg_profile_dir = $this->tgdir."/profiles/".$tgprofile;
			$tg_config = $this->tgdir."/confs/".$tgprofile;
			$tg_socket = $this->tgdir."/socks/".$tgprofile.".sck";
			
			if(is_dir($tg_profile_dir)){
				$this->delTree($tg_profile_dir);
			}
			if(file_exists($tg_config)){
				unlink($tg_config);
			}
			if(file_exists($tg_socket)){
				unlink($tg_socket);
			}
			
			return array("answer"=>"deleted ".$tgNumber);
		}
	}
	
	public function get_telegram_account_status($params){
		return true;
		if(!empty($params["TGNUMBER"])){ $tgNumber = preg_replace("/[^0-9]/", '', $params["TGNUMBER"]); } else { return 'Not set Profile'; }
		$profd = "prf_".$tgNumber;
		$arProfile = $this->get_tg_account_self($profd);
		$oneTgProfile = array("phone"=>$tgNumber);
		$oneTgProfile["active"] = is_object($arProfile) ? '<span class="active_tg_status badge badge-success">Активный</span>' : '<span class="off_tg_status badge badge-secondary">Выключен</span>';
		$oneTgProfile["status"] = is_object($arProfile) ? 'on' : 'off';
		$oneTgProfile["profile"] = $profd;
		$oneTgProfile["name"] = (!empty($arProfile->print_name)) ? $arProfile->print_name : ''; //oneTgProfile["phone"];
		$oneTgProfile["username"] = (!empty($arProfile->username)) ? $arProfile->username : '';
		return $oneTgProfile;
	}
	
	public function get_telegram_accounts(){
		return true;
		$tg_profiles_dir = $this->tgdir."/profiles/";
		$tg_socks_dir = $this->tgdir."/socks/";
		
		$flProfiles = scandir($tg_profiles_dir);
		$this->tLog("aTG: scan Profiles DIR:  [".json_encode($flProfiles)."] ");
		$arTgAccounts = array();
		foreach($flProfiles as $profd){
			
			if(is_dir($tg_profiles_dir.$profd) && substr($profd,0,4)=="prf_"){
				$optsFile = $this->tgdir."/tmp/opt_".substr($profd,4).'.json';
				
				if(file_exists($tg_profiles_dir.$profd."/auth")) {
					$authSize = filesize($tg_profiles_dir.$profd."/auth");
					
					$this->tLog("aTG: scan Profiles AuthSIZE:  [".$tg_profiles_dir.$profd."/auth"."] =(".$authSize.")");
					if($authSize>0) {
						$arProfile = $this->get_tg_account_self($profd);
						
						$this->tgdir."/tmp/opt_".$this->tg_sender_default.'.json';
						
						$this->tLog($arProfile, "aTG: scan Profiles STS:(".$profd.")");
						//$this->tLog($arProfile,"aTG: scan Profiles AuthSIZE:  [".$tg_profiles_dir.$profd."/auth"."] =(".$profd.")");
						//if($arProfile==false){
						//	return false;
						//}
						// ["profile"]=> object(stdClass)#1363 (10) { ["id"]=> string(33) "$010000007e53ac3d557f36881c3521f6" ["peer_type"]=> string(4) "user" ["peer_id"]=> int(1034703742) ["print_name"]=> string(11) "Texnomart_*" ["flags"]=> int(524291) ["first_name"]=> string(9) "Texnomart" ["when"]=> string(19) "2019-12-18 15:49:02" ["last_name"]=> string(1) "*" ["phone"]=> string(12) "998946712860" ["username"]=> string(13) "texnomartstar" } 
						$oneTgProfile = array("phone"=>substr($profd,4));
						$oneTgProfile["active"] = is_object($arProfile) ? '<span class="active_tg_status badge badge-success">Активный</span>' : '<span class="off_tg_status badge badge-secondary">Выключен</span>'; //(file_exists($tg_socks_dir.$profd.".sck")) ? "Y" : "N";
						$oneTgProfile["status"] = is_object($arProfile) ? 'on' : 'off';
						$oneTgProfile["profile"] = $profd;
						$oneTgProfile["name"] = (!empty($arProfile->print_name)) ? $arProfile->print_name : ''; //oneTgProfile["phone"];
						$oneTgProfile["username"] = (!empty($arProfile->username)) ? $arProfile->username : '';
						$oneTgProfile["optsfile"] = $optsFile;
						$oneTgProfile["options"] = (file_exists($optsFile)) ? json_decode(file_get_contents($optsFile),true) : [];
						$arProfile = null;
						unset($arProfile);
						$arTgAccounts[] = $oneTgProfile;
					}
				}
			}
		}
		return $arTgAccounts;
	}

	public function register_account_confcode($params){
		return true;
		if(!empty($params["TGNUMBER"])){ $tgNumber = preg_replace("/[^0-9]/", '', $params["TGNUMBER"]); }
		if(!empty($params["TGCONFCODE"])){ $tgNumberConfCode = preg_replace("/[^0-9]/", '', $params["TGCONFCODE"]); }
		if(!empty($tgNumber)){

			$tgprofile = "prf_".$tgNumber; 
			$confirm_num_file = $this->tgdir."/tmp/".$tgprofile;
			$this->tLog("aTG: register_account_confcode: Writing: [".$tgNumberConfCode."] ".$confirm_num_file);
			file_put_contents($confirm_num_file, $tgNumberConfCode);
		}
		return array("answer"=>"sent");
	}
	
	public function stop_profile_by_number($params){
		return true;
		if(!empty($params["TGNUMBER"])){ $tgNumber = preg_replace("/[^0-9]/", '', $params["TGNUMBER"]); }
		if(empty($tgNumber)){
			return array("error"=>'No or bad Number');
		}
		$this->tLog("aTG: stop_profile_by_number: STOPPING: [".$tgNumber."]");
		//$telegram = new \Zyberspace\Telegram\Cli\Client('unix://'.$this->tgsocks_dir.'prf_'.$tgNumber.'.sck');
		
		$shRes = shell_exec("ps aux | grep prf_".$tgNumber.".sck | grep -v grep  | awk {'print $2'}");
		preg_match_all("/[0-9]{2,}/",$shRes, $arPids);
		if(!empty($arPids)){ 
			$tgPID = implode(" ",$arPids[0]);
		}
		//$tgPID = preg_replace("/[^0-9]/", '', $shRes);
		$this->tLog("aTG: stop_profile_by_number: SHELL PID: [".$tgPID."]");
		
		if(!empty($tgPID)){
			$killRes = shell_exec("kill -9 ".$tgPID);
			$delSock = unlink("/var/www/html/bx24/vendor/tg/src/socks/prf_".$tgNumber.".sck");
			return [ "result" => $killRes, 'delres'=>$delSock ];
		} else {
			return [ "result" => "Already stopped" ];
		}
		/*
		if(!empty($tgNumber)){ $this->set_tg_sender_default($tgNumber); }
		$telegram = $this->TGM; 
		
		$qRes = $telegram->exec('quit');
		return ["result"=>$qRes];
		*/
	}

	public function get_tg_account_self($profile=false){
		
		if( empty($profile)  && empty($this->currentProfile) ){ return false; }
		
		if(!empty($profile)){
			$prfSock = $this->tgsocks_dir.$profile.'.sck';
			$this->tLog("aTG: get_tg_account_self: SOCKET: [".$prfSock."]");
			if(file_exists($prfSock)){
				$this->TGM = new \Zyberspace\Telegram\Cli\Client('unix://'.$prfSock);
			}
		} 
		
		if(!empty($this->TGM)){
			//return $this->TGM->exec('help');
			return $this->TGM->exec('get_self');
		} 

		return false;
	}
	
	public function get_contacts_list_old($params){
		return true;
		if( empty($this->currentProfile)){ $this->currentProfile ="998946712860"; }
		$telegram = new \Zyberspace\Telegram\Cli\Client('unix://'.$this->tgsocks_dir.'prf_'.$this->currentProfile.'.sck');
		
		$contactList = $telegram->getContactList();
		////var_dump($contactList);
		$res["contacts"] = json_decode(json_encode($contactList),1);
		//$res["contact_photos"] = array();
		foreach($res["contacts"] as $cKey => $cnt){
			//view_user_photo
			$telegram->msg($cnt->print_name,"Проверка: ".time());
			$res["contacts"][$cKey]["user_photo"] = $telegram->exec('view_user_photo '.$cnt->print_name);
		}
		$jsContacts = json_encode($res["contacts"]);
		$this->tLog("Contacts: ".$jsContacts);
		return $res;
	}
	
	public function run_profile_by_number($params){
		if(!empty($params["TGNUMBER"])){ $tgNumber = preg_replace("/[^0-9]/", '', $params["TGNUMBER"]); }
		
		if(!empty($tgNumber)){
			$phpCmd = ' $tgl = new \TGA\ATelegram(); $tgl->tLog("Begin Async FUNC.......");  $tgl->async_run_profile_by_number("'.$tgNumber.'");';
			$phpRes = $this->execInBackground($phpCmd);
			return array("answer"=>$phpRes);
		}
		return array("error"=>"No or bad Number");
		
	}
	
	public function async_run_profile_by_number($tgNumber){
		return true;
		if(empty($tgNumber)){
			return array("error"=>'No or bad Numbers');
		}
		
		$this->stop_profile_by_number( [ "TGNUMBER" => $tgNumber ] );
		
		$tgprofile = "prf_".$tgNumber;
		$tg_profile_dir = $this->tgdir."/profiles/".$tgprofile;
		$tg_config = $this->tgdir."/confs/".$tgprofile;
		$tg_ulog = $this->tgdir."/tmp/".$tgprofile.".log";
		$tg_socket = $this->tgdir."/socks/".$tgprofile.".sck";
		$tg_bin = $this->tgbin;
		chmod($tg_bin, 0775);
		$this->tLog("Starting Telegram (".$tgNumber.")");
		//$tgSocket = 'unix:///tmp/tg.sck';
		///usr/bin/telegram-cli -vvv -R -C -k /etc/telegram-cli/server.pub -W -N -d -L /var/log/telegram-officetg.log -P 51235 --json --accept-any-tcp -s /var/www/html/tg/tg.lua &
		//$cmd = $tg_bin." -k ".$this->tgcert." -c ".$tg_config." -vvv -p ".$tgprofile; //--accept-any-tcp
		$cmd = $tg_bin." -U asterisk -vvvvvvvvvv -d -R -C -W -N --json -k ".$this->tgcert." -S ".$tg_socket." -s ".$this->tglua." -c ".$tg_config." -L ".$tg_ulog." -p ".$tgprofile." &"; // -d because quit n ot working with key "-d"
		$this->tLog("Telegram CMD: ".$cmd);
		
		//shell_exec("pkill -9 telegram-cli");
		
		if(file_exists($tg_socket)){
			
			unlink($tg_socket);
		}
		
		$ansTelRun = exec($cmd,$cmdOut);
		$this->tLog("Telegram RUN[".$tgprofile."]: ".$ansTelRun);
		$this->tLog("Telegram RUN OUTPUT: ".json_encode($cmdOut));
		// Start the process.
		//$process = proc_open('exec ' . $cmd, $descriptors, $pipes);
		return true;
	}	
	
		
	public function register_account($params){
		return true;
		$this->tLog("aTG: register_account: ".json_encode($params));
		if(!empty($params["TGNUMBER"])){ $tgNumber = preg_replace("/[^0-9]/", '', $params["TGNUMBER"]); }
		$this->delete_telegram_account(["TGNUMBER"=>$tgNumber]);
		if(!empty($tgNumber)){
			$phpCmd = ' $tgl = new \TGA\ATelegram(); $tgl->tLog("Begin Async FUNC.......");  $tgl->check_and_register_tg("'.$tgNumber.'");';
			$phpRes = $this->execInBackground($phpCmd);
			return array("answer"=>$phpRes);
			//return $this->check_and_register_tg($tgNumber);
		}
		return array("error"=>"Some Tg Error");
	}
	public function registerNewTgNumber(){
		///home/bitrix/www/bitrix/modules/alovoice/tg/incom.lua
		$this->tgdir.'/incom.lua';
	}
	
	public function getTelegramSmsSettingsPage() {
		return true;
		global $APPLICATION;
		$arAccountsList = $this->get_telegram_accounts();
		//var_dump($arAccountsList);
		$tgProfile = $this->tg_sender_default(); 
		$arResult["BUTTON"] = array("title"=>'Добавить Телеграм аккоунт','click'=>'openTgAddProfileWin();');
		$arResult["COLUMNS"] = array(
			['id' => 'PHONE', 'name' => 'Номер', 'sort' => 'PHONE', 'default' => true],
			['id' => 'NAME', 'name' => 'Имя', 'default' => true],
			['id' => 'USERNAME', 'name' => 'Юзернейм', 'default' => true], 
			['id' => 'ACTIVE', 'name' => 'Статус', 'default' => true]
		);
		$arTgProfiles = $arAccountsList;
		$arTgProfilesssss = array(
			array(
				'id' => '1',
				'phone' => '998935312860',
				'name' => 'Texnomart',
				'username' => 'Texnomart',
				'active' => 'Y',
			)
		); 
		foreach($arTgProfiles as $tpf){
			$newLineActions = array(
				[
					'text'    => 'Контакты',
					'onclick' => 'alvTgGetProfileContactsByNumber("'.$tpf['phone'].'");'
				]
			);
			
			if( !empty($tpf['username']) ){
				$newLineActions[] = array('text' => 'Остановить', 'onclick' => 'alvTgStopProfileByNumber("'.$tpf['phone'].'");');
			} else {
				$newLineActions[] = array('text' => 'Запустить', 'onclick' => 'alvTgRunProfileByNumber("'.$tpf['phone'].'");');
			}
			
			$newLineActions[] = array('text' => 'Удалить', 'onclick' => 'alvTgDeleteProfileByNumber("'.$tpf['phone'].'");');
			
			$newLine = array( 
				'data' => array(
					"ID" => $tpf['id'],
					"PHONE" => $tpf['phone'],
					"NAME" => $tpf['name'],
					"USERNAME" => $tpf['username'], 
					"ACTIVE" => $tpf['active'],
				),
				'actions' => $newLineActions
			);
				
			$arResult["DATAS"][] = $newLine ;
		}
		$arResult["SCRIPTS"] = '
			//function openTgAddProfileWin(){
				
			//}
		';
		return $arResult;
	}
	
	/*----------------------------INCOM----------------------------------------------*/
	
	public function handleIncomingMessages($params){
		return true;
		$this->tLog("aTG: handleIncomingMessages: |".$params."|");
		//{"to":{"last_name":"*","peer_type":"user","id":"$010000007e53ac3d557f36881c3521f6","flags":524291,"access_hash":1,"username":"texnomartstar","peer_id":1034703742,"print_name":"Texnomart_*","phone":"998946712860","first_name":"Texnomart"},"date":1576750169,"unread":true,"flags":257,"out":false,"text":"123123","service":false,"from":{"last_name":"Nava","peer_type":"user","id":"$010000001827730723b8ffcdc773a34c","flags":196609,"access_hash":1,"username":"kuldash","peer_id":124987160,"print_name":"kulya_Nava","phone":"998977076909","first_name":"kulya"},"id":"0100000018277307080000000000000023b8ffcdc773a34c"}
		$arDefIncomUsersIds = array(1,9);
		$arUsersPhoneFields = array(
			"PERSONAL_MOBILE",
			"PERSONAL_PHONE",
			"WORK_PHONE",
		);
		$arCrmEntTypes = array(
			"LEAD" => 1,
			"DEAL" => 2,
			"CONTACT" => 3,
			"COMPANY" => 4,
		);
		
		$arMsg = json_decode($params,1);
		
		if(!empty($arMsg["from"]["phone"])){
			
			$fromNumber = $arMsg["from"]["phone"];
			
			$this->tLog("-------------------== [".$fromNumber."]==[".$arMsg["text"]."]----------------");
			
			/* TODO
			$crmEntitySearchResult = ALVC::searchCrmEntities($fromNumber);
			
			$this->tLog($crmEntitySearchResult,"-------------------== CRM Search RES: ----------------");
			
			// [{"CRM_ENTITY_TYPE":"CONTACT","CRM_ENTITY_ID":8,"ASSIGNED_BY_ID":1}]
			
			if(!empty($crmEntitySearchResult)){
				$curEntity = $crmEntitySearchResult[0];
				$addActivityResult = $this->telegram_activity_add(array(
					"ENTITY_ID" => $curEntity["CRM_ENTITY_ID"],
					"ENTITY_TYPE" => $curEntity["CRM_ENTITY_TYPE"],
					"MESSAGE_TO" => $fromNumber,
					"MESSAGE_BODY" => $arMsg["text"],
				),\CCrmActivityDirection::Incoming);
				
				$this->tLog("-----== CRM Search RES: ".json_encode($addActivityResult));

			}
			*/
		}
		
	}
	
	/*----------------------------INCOM--END--------------------------------------------*/
	
	
	/*----------------------------  CONTACT  -- INFO  --------------------------------------------*/
	public function getcontactinfo($params){
		return true;
		$telegram = new \Zyberspace\Telegram\Cli\Client($tgSocket);
		$resAns = '';
		$number = preg_replace("/[^0-9]/", '', $_REQUEST["getcontactinfo"]) ;
		tLog("Func getcontactinfo number:".$number);
		
		$contactList = $telegram->getContactList();
		
		$arUinfo = false;
		
		foreach($contactList as $tcnt){
			if(!empty($tcnt->phone)){
				if(substr($tcnt->phone,-9) == substr($number,-9)){
					$arUinfo = $tcnt;
				}
			}
		}
		
		tLog("Res getcontactinfo clst: ".json_encode($arUinfo));
		
		if(!empty($arUinfo)){
			if(substr($arUinfo->first_name,0,7)!=="addLast"){
				
				$resAns .= $arUinfo->first_name.' '.$arUinfo->last_name. ' ('.$arUinfo->username.')';
				tLog("Res getcontactinfo Founded: ".$arUinfo->first_name.' '.$arUinfo->last_name. ' ('.$arUinfo->username.')');
				
				//$resAdding = $telegram->addContact($number,$arUinfo->first_name,$arUinfo->last_name);

				if(file_exists(__DIR__."/photos/".$number.'.jpg')){
					$phFileName = "photos/".$number.'.jpg';
				}
				elseif(file_exists(__DIR__."/photos/".$number.'.png')){
					$phFileName = "photos/".$number.'.png';
				}
				else{
					tLog("Check Loading photo...\n");
					$getPhoto = $telegram->loadUserPhoto($arUinfo->print_name);
					
					tLog("Res getcontactinfo getPhoto: ".json_encode($getPhoto));
					
					if(!empty($getPhoto->result)){
						tLog("Res getcontactinfo getPhoto: ".json_encode($getPhoto->result));

						$phFileName = "photos/".$number.substr($getPhoto->result,-4);
						//$phFileName = "/photos/".$number.substr($getPhoto->result,-4);
						if(file_exists($getPhoto->result)){
							rename($getPhoto->result, __DIR__.'/'.$phFileName);
							chmod(__DIR__.$phFileName, 0755);
							
								
							/*if(!empty($_REQUEST["getphotobase"])){
								$imagePhotoContent = file_get_contents($getPhoto->result);
								echo base64_encode($imagePhotoContent);
								die();
							} else {
								
							}*/

						} else {
							tLog('Cannot load photo:'.$getPhoto->result);
						}
					} else {
						tLog("Res getcontactinfo getPhoto: NO PHOTO of Not loading");
					}
				}
				
				if(file_exists(__DIR__.'/'.$phFileName)){
					if(!empty($_REQUEST["getphotobase"])){
						$fullPictureFilePath = __DIR__.'/'.$phFileName;
						$imagePhotoContent = file_get_contents($getPhoto->result);
						echo base64_encode($imagePhotoContent);
						die();
					} else {
						echo json_encode( array("result"=>$resAns,"photo"=>'/tg/'.$phFileName) );
						die();
					}
				}
				
				
			} else {
				$resAdding = $telegram->addContact($number,$arUinfo->first_name,$arUinfo->last_name);
				$addLast = 1;
			}
		}
		
		tLog("Res getcontactinfo CHECK addLast: ".$addLast);
		
		if(empty($addLast)){
			$resAdding = $telegram->addContact($number);
			$pId = false;
			tLog("Res getcontactinfo ADDING to contacts: ".json_encode($resAdding));
			
			if(!empty($resAdding["peer"])){
				$pId = $resAdding["peer"]->id;
			}
			if((empty($pId))&&(!empty($resAdding[0]))){
				$pId = $resAdding[0]->id;
			}
			
			tLog("Res getcontactinfo Got UserID: ".$pId);
			//echo json_encode( array("query"=>"getcontactinfo_adding", "param"=>$number, "result"=>$resAdding) );
		}
		
		$resDel = $telegram->deleteContactNumber($number);
		
		tLog("Res getcontactinfo deleting: ".json_encode($resDel));
		//var_dump($pId);
		//var_dump($resDel);
		
		
		if(!empty($resDel) && !empty($pId)){
			//echo 'Getting userInfo:'.$pId;
			$arUinfo = $telegram->getUserInfo($pId);
			//echo json_encode( array("query"=>"getcontactinfo_newinfo", "param"=>$number, "result"=>$arUinfo) );
			
			tLog("Res getcontactinfo getUserInfo: ".json_encode($arUinfo));
			
			if(!empty($arUinfo)){
				$resAns = $arUinfo->first_name.' '.$arUinfo->last_name. ' ('.$arUinfo->username.')';
				$resAdding = $telegram->addContact($number,$arUinfo->first_name,$arUinfo->last_name);
				tLog("Res2 getcontactinfo addContact: ".json_encode($resAdding));
			
				$getPhoto = $telegram->loadUserPhoto($arUinfo->print_name);
				
				tLog("Res2 getcontactinfo getPhoto: ".json_encode($getPhoto));
					
				if(!empty($getPhoto->result)){
					tLog("Res2 getcontactinfo getPhoto: ".json_encode($getPhoto->result));

					$phFileName = "/photos/".$number.substr($getPhoto->result,-4);
					if(file_exists($getPhoto->result)){
						rename($getPhoto->result, __DIR__.$phFileName);
						chmod(__DIR__.$phFileName, 0755);
						//$resAns .=  '<img src="'.$phFileName.'">';
					} else {
						tLog('Cannot2 load photo:'.$getPhoto->result);
					}
				} else {
					tLog("Res2 getcontactinfo getPhoto: NO PHOTO of Not loading");
				}
				
				
				echo json_encode( array("result"=>$resAns,"photo"=>'/tg/'.$phFileName) );
				die();
			}
		}
		//getUserInfo
		
		
		
		//echo json_encode( "query"=>"addcontact", "param"=>$number, "result"=>$resAdding );
		//echo '<br>After ADD<br>';
		//$contactList = $telegram->getContactList();
		//echo json_encode( $contactList );
		die();
	}
	
	/*----------------------------INCOM--END--------------------------------------------*/
	
	
	
	
	public function telegram_activity_add($params,$dir=\CCrmActivityDirection::Outgoing) {
		return true;
		$this->tLog("aTG: PRED Add Activity IN PARAMS: [".json_encode($params)."]");
		\Bitrix\Main\Loader::includeModule('crm');
		$arCrmEntTypes = array(
			"LEAD" => 1,
			"DEAL" => 2,
			"CONTACT" => 3,
			"COMPANY" => 4,
		);
		if( !empty($params["ENTITY_TYPE"]) && !empty($params["ENTITY_ID"]) ){
			$now = ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', 's1');
			$entType = strtoupper($params["ENTITY_TYPE"]);
			$fields = array( 
				'TYPE_ID' => \CCrmActivityType::Provider, //\CCrmActivityType::Email, //0, //CCrmActivityType::Call, //тип самого дела, может быть: Meeting, Call, Task, Email (константы класса)
				'PROVIDER_ID' => 'Telegram', //\CCrmActivityType::Email, //0, //CCrmActivityType::Call, //тип самого дела, может быть: Meeting, Call, Task, Email (константы класса)
				'OWNER_TYPE_ID' =>$arCrmEntTypes[$entType], //CCrmOwnerType::Deal, //тип основной сущности, к которой привязывается дело, //может быть Deal, Lead, Contact, Company (константы класса)
				'OWNER_ID' => $params["ENTITY_ID"], //ID основной сущности
				'SUBJECT' => 'Телеграм', 
				'START_TIME' => $now, 
				'END_TIME' => $now, 
				'COMPLETED' => 'Y', //флаг завершенности дела
				'RESPONSIBLE_ID' => 1, //ответственный
				'PRIORITY' => \CCrmActivityPriority::None, //приоритет, может быть None, Low, Medium, High (константы класса)
				'DESCRIPTION' => $params["MESSAGE_TO"]." <br> ".$params["MESSAGE_BODY"], 
				'DESCRIPTION_TYPE' => CCrmContentType::Html,
				'DIRECTION' => $dir, //\CCrmActivityDirection::Outgoing, //актуально для типов дел, где может быть направление  //(входящий или исходящий - телефон или email), //может быть Outgoing, Incoming (константы класса)
				//'LOCATION' => '',
				'BINDINGS' => array( 
					array( 
						'OWNER_TYPE_ID' => $arCrmEntTypes[$entType], //\CCrmOwnerType::Deal, 
						'OWNER_ID' => $params["ENTITY_ID"] 
					) 
				), 
				'ORIGIN_ID' => 'TLG_'.$params["MESSAGE_TO"].'_'.time() //некий внешний идентификатор, опционально
			); 
			$this->tLog("aTG: PRED Add Activity PARAMS: [".json_encode($fields)."]");
			
			//$sendResult = array( "answer" => self::asterSendTgMessage( array("MESSAGE_TO" => $params["MESSAGE_TO"], "MESSAGE_BODY"=> $params["MESSAGE_BODY"] ) ) ) ;
			
			//$addActivityResult = \CCrmActivity::Add($fields, true); 
			
			$addActivityResult = Bitrix\Crm\Activity\Provider\Alotelegram::addActivity($fields,false);
			
			$this->tLog("aTG: Add Activity: [".json_encode($addActivityResult)."]");
			
			return $addActivityResult;
		}
	}
	public function echo_sleep($sec, $msg = false, $newline = false) {
		return true;
		global $echo_sleep_prev_msg_gb; // Preeventing to show the same msg.
		if ($echo_sleep_prev_msg_gb !== $msg) { 
			if ($msg) $this->tLog( $msg );
			for ($i=0;$i<$sec;$i++) { $this->tLog( "." ); sleep (1); }
			if ($newline) $this->tLog( "\n" );
			$echo_sleep_prev_msg_gb = $msg;
		} else 
			$this->tLog(".");
	}

	public function check_and_register_tg($tgnumber) {
		return true;
		$this->tLog("Alo TG Reginster begin number: ".$tgnumber);
		
		$this->echo_sleep(1, "Loading config", true);
		
		$confirmation_num_timeout_sec=3*60;
		$timeout = 60;
		$tgprofile = "prf_".$tgnumber;
		$tg_profile_dir = $this->tgdir."/profiles/".$tgprofile;
		$tg_config = $this->tgdir."/confs/".$tgprofile;
		$tg_socket = $this->tgdir."/socks/".$tgprofile.".sck";
		$tg_bin = $this->tgbin;
		$confirm_num_file = $this->tgdir."/tmp/".$tgprofile;
		
		$this->tLog("aTG: ".$tgprofile.", ".$tg_socket.", ".$tg_config.", ".$tg_bin);

		if(file_exists($tg_profile_dir."/auth")) {
			if(filesize($tg_profile_dir."/auth")>0) {
				return array('error' => "Profile [$tgnumber] already activated! \n");
			}
		}
		
		$conf_profile_record = $tgprofile." = {\n"
			."config_directory = \"".$tg_profile_dir ."\";\n"
			."test = false;\n"
			."msg_num = true;\n"
			."binlog_enabled = true;\n"
			."log_level = 2;\n"
			."};\n";
		
		if(!is_dir($tg_profile_dir)) {
			if(!mkdir($tg_profile_dir, 0777)){
				return  array('error' => "Profile [$tgnumber] Directory creating error! \n");
			}
		}
		
		/*if(!file_exists($tg_bin)) {
			copy($tgdir."/telegram-cli", $tg_bin);
		}
		
		*/
		if(file_exists($tg_bin)) {
			chmod($tg_bin, 0777);
		}
		if(!file_exists($tg_config)) {
			file_put_contents($tg_config, "\n".$conf_profile_record."\n");
		}
		if(!file_exists($confirm_num_file)) {
			file_put_contents($confirm_num_file, "");
		}
		$this->tLog(json_encode(stat($tg_bin) ));
		$this->echo_sleep(1, "Starting telegram");
		$cmd = $tg_bin." -k ".$this->tgcert." -c ".$tg_config." -vvv -p ".$tgprofile;
		$this->tLog($cmd);
		// File descriptors passed to the process.
		$descriptors = array(
			0 => array('pipe', 'r'),  // stdin
			1 => array('pipe', 'w'),  // stdout
			2 => array('pipe', 'w')   // stderr
		);

		// Start the process.
		$process = proc_open('exec ' . $cmd, $descriptors, $pipes);

		if (!is_resource($process)) {
			return  array('error' => "Error on run Telegram cli [$tgnumber]! \n");
		}

		// Set the stdout stream to non-blocking.
		stream_set_blocking($pipes[1], 0);

		// Set the stderr stream to non-blocking.
		stream_set_blocking($pipes[2], 0);

		// Turn the timeout into microseconds.
		$timeout = $timeout * 1000000;

		// Output buffer.
		$buffer = '';

		// While we have time to wait.
		$phone_num_prompt = false;
		$phone_num_sent = false;
		$confirm_num_prompt = false;
		$confirm_num_sent = false;
		$confirm_num = "";

		$this->echo_sleep(1, "Saving tg output into buffer timeout[$timeout]", true);

		while ($timeout > 0) {

			$start = microtime(true);
			$this->tLog("aTG: start WHILE timeout: ".$start);	
			// Wait until we have output or the timer expired.
			$read  = array($pipes[1]);
			$other = array();
			stream_select($read, $other, $other, 0, $timeout);

			// Get the status of the process.
			// Do this before we read from the stream,
			// this way we can't lose the last bit of output if the process dies between these functions.
			$status = proc_get_status($process);

			// Read the contents from the buffer.
			// This function will always return immediately as the stream is non-blocking.
			$oneBuff = stream_get_contents($pipes[1]);

			//TODO: debug on/off
			/*if(!empty($oneBuff)) {
				echo "\nLine:[".trim($oneBuff)."]\n";
			} else {
				echo "Line:[Empty]\n";
			}*/

			$buffer .= $oneBuff;
			$this->tLog( "Buffer: ".$oneBuff."; Status:".json_encode($status));
			if($phone_num_prompt == false) {
				$this->echo_sleep(1, "Waiting phone number prompt", false);
				if(strpos($buffer, "phone number:") !== false) {
					$phone_num_prompt = true;
					$this->tLog( " OK \n");
				}
			} 
			if ($phone_num_prompt == true and $phone_num_sent == false) {
				$this->echo_sleep(1, "Sending phone number [$tgnumber]", false);
				fwrite($pipes[0], $tgnumber."\n");
				$phone_num_sent = true;
				$this->tLog( " OK (confirmation number has been sent) \n");
				sleep(1);
			}
			if($phone_num_sent == true and $confirm_num_prompt == false) {
				$this->echo_sleep(1, "Waiting confirmation number prompt", false);
				if(strpos($buffer, "CALL") !== false) {
					$confirm_num_prompt = true;
					$this->tLog(" OK \n");
				}
			}
			if($confirm_num_prompt == true and $confirm_num_sent == false) {
				for ($ii = 0; $ii < $confirmation_num_timeout_sec; $ii++) { //TODO: do NOT allow endless loop here... 
					$this->echo_sleep(1, "Reading confirmation number from file [$confirm_num_file]", false);
					$confirm_num = trim(file_get_contents($confirm_num_file));
					$this->tLog("Check confirmation code: ".$confirm_num);
					if (!empty($confirm_num)){ break; }
					sleep(1);
				}
				if(empty($confirm_num)){ $error_msg = 'No confirm number'; break; }
				
				file_put_contents($confirm_num_file, ""); // Clean the conf number 
				$this->tLog(" OK \n");

				$this->echo_sleep(1, "Sending confirmation number [$confirm_num]", false);
				fwrite($pipes[0], $confirm_num."\n");
				$confirm_num_sent = true;
				$this->tLog("Sent Conf CODE OK \n");
				sleep(1);
				break;
			}

			if (!$status['running']) {
				// Break from this loop if the process exited before the timeout.
				$this->echo_sleep(1, "Process is dead, break the loop", true);
				break;
			}

			//echo " \n ";
			// Subtract the number of microseconds that we waited.
			$timeout -= (microtime(true) - $start) * 1000000;
		}

		// Check if there were any errors.
		//$errors = stream_get_contents($pipes[2]);

		//if (!empty($errors)) {
		//  throw new \Exception($errors);
		//}

		// Kill the process in case the timeout expired and it's still running.
		// If the process already exited this won't do anything.
		proc_terminate($process, 9);

		// Close all streams.
		fclose($pipes[0]);
		fclose($pipes[1]);
		fclose($pipes[2]);

		proc_close($process);

		if($confirm_num_sent === false){
			$this->echo_sleep(1, "Sorry, something wierd going on here..", true);
			return array("error"=>$error_msg);
		}
		return true;
	}
	
	public function execInBackground($cmd) {
		$tgClass = __FILE__;
		$command = 'require "'.$tgClass.'"; '.$cmd;
		$command = base64_encode($command);
		$cmd = "php -r 'eval(base64_decode(\"$command\"));'";
		if (substr(php_uname(), 0, 7) == "Windows"){
			//die('windows');
			pclose(popen("start /B ". $cmd, "r"));
		}
		else {
			//die('not windows');
			exec($cmd . " > /dev/null &");
		}
		return "sent";
	}
	
	public function setLine($lid){
		file_put_contents( __DIR__."/lineid", intVal($lid));
	}
	
	public function getLine(){
		if(file_exists(__DIR__."/lineid")){
			return file_get_contents( __DIR__."/lineid");
		}
		return false;
	}

	public function tLog($data,$title=''){
		if(is_object($data)){
			$data = (array)$data;
		}
		
		$log = "\n------------------------\n";
		$log .= date("Y.m.d G:i:s")." - ";
		$log .= (strlen($title) > 0 ? $title."\n" : '');
		$log .= (is_array($data)) ?  "arr: ".json_encode($data) : "str:".$data; //, JSON_PRETTY_PRINT

		file_put_contents( __DIR__."/tgm.log", $log, FILE_APPEND);
	}
	public function delTree($dir) {
	   $files = array_diff(scandir($dir), array('.','..'));
		foreach ($files as $file) {
			if($file=="downloads"){
				continue;
			}
			(is_dir("$dir/$file") && !is_link($dir)) ? $this->delTree("$dir/$file") : unlink("$dir/$file");
		}
		return rmdir($dir);
	}
}	


//AlovoiceTelegram
//2254937
//a99f8a3ce02dbaa987cfb3c644a16a26
//AloTG
//149.154.167.40:443 //test
//149.154.167.50:443 //prod
/*
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
-----END RSA PUBLIC KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAruw2yP/BCcsJliRoW5eB
VBVle9dtjJw+OYED160Wybum9SXtBBLXriwt4rROd9csv0t0OHCaTmRqBcQ0J8fx
hN6/cpR1GWgOZRUAiQxoMnlt0R93LCX/j1dnVa/gVbCjdSxpbrfY2g2L4frzjJvd
l84Kd9ORYjDEAyFnEA7dD556OptgLQQ2e2iVNq8NZLYTzLp5YpOdO1doK+ttrltg
gTCy5SrKeLoCPPbOgGsdxJxyz5KKcZnSLj16yE5HvJQn0CNpRdENvRUXe6tBP78O
39oJ8BTHp9oIjd6XWXAsp2CvK45Ol8wFXGF710w9lwCGNbmNxNYhtIkdqfsEcwR5
JwIDAQAB
-----END PUBLIC KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvfLHfYH2r9R70w8prHbl
Wt/nDkh+XkgpflqQVcnAfSuTtO05lNPspQmL8Y2XjVT4t8cT6xAkdgfmmvnvRPOO
KPi0OfJXoRVylFzAQG/j83u5K3kRLbae7fLccVhKZhY46lvsueI1hQdLgNV9n1cQ
3TDS2pQOCtovG4eDl9wacrXOJTG2990VjgnIKNA0UMoP+KF03qzryqIt3oTvZq03
DyWdGK+AZjgBLaDKSnC6qD2cFY81UryRWOab8zKkWAnhw2kFpcqhI0jdV5QaSCEx
vnsjVaX0Y1N0870931/5Jb9ICe4nweZ9kSDF/gip3kWLG0o8XQpChDfyvsqB9OLV
/wIDAQAB
-----END PUBLIC KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs/ditzm+mPND6xkhzwFI
z6J/968CtkcSE/7Z2qAJiXbmZ3UDJPGrzqTDHkO30R8VeRM/Kz2f4nR05GIFiITl
4bEjvpy7xqRDspJcCFIOcyXm8abVDhF+th6knSU0yLtNKuQVP6voMrnt9MV1X92L
GZQLgdHZbPQz0Z5qIpaKhdyA8DEvWWvSUwwc+yi1/gGaybwlzZwqXYoPOhwMebzK
Uk0xW14htcJrRrq+PXXQbRzTMynseCoPIoke0dtCodbA3qQxQovE16q9zz4Otv2k
4j63cz53J+mhkVWAeWxVGI0lltJmWtEYK6er8VqqWot3nqmWMXogrgRLggv/Nbbo
oQIDAQAB
-----END PUBLIC KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvmpxVY7ld/8DAjz6F6q0
5shjg8/4p6047bn6/m8yPy1RBsvIyvuDuGnP/RzPEhzXQ9UJ5Ynmh2XJZgHoE9xb
nfxL5BXHplJhMtADXKM9bWB11PU1Eioc3+AXBB8QiNFBn2XI5UkO5hPhbb9mJpjA
9Uhw8EdfqJP8QetVsI/xrCEbwEXe0xvifRLJbY08/Gp66KpQvy7g8w7VB8wlgePe
xW3pT13Ap6vuC+mQuJPyiHvSxjEKHgqePji9NP3tJUFQjcECqcm0yV7/2d0t/pbC
m+ZH1sadZspQCEPPrtbkQBlvHb4OLiIWPGHKSMeRFvp3IWcmdJqXahxLCUS1Eh6M
AQIDAQAB
-----END PUBLIC KEY-----

*/

?>