<?php

function mappingInfo($channelInfoKey, $channelInfoNew) {
 $mappingInfo=array();

 $chanid=explode("-", $channelInfoKey)[0];
 foreach(array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["chanid"] == $chanid) {
   $mappingInfo[]=$channelInfoNew[$k]["typemapping"];
  } // if ($channelInfoNew["chanid"] == $chanid) 
 } // foreach(array_keys($channelInfoNew) as $k)
 if (count($mappingInfo) != 0) { return $mappingInfo; } else return false;
} // function end

function forwardInfo($channelInfoKey, $channelInfoNew) { 
 $forwardInfo=array();

 $chanid=explode("-", $channelInfoKey)[0];
 foreach(array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["chanid"] == $chanid) {
   if (!array_key_exists("-1", $channelInfoNew[$k]["to"])) {
    foreach (array_keys($channelInfoNew[$k]["to"]) as $t) {
     if (array_key_exists($channelInfoNew[$k]["to"][$t]["chanid"], $channelInfoNew)) {
 	  if ($channelInfoNew[$channelInfoNew[$k]["to"][$t]["chanid"]]["disabled"] == -1) {
       $forwardInfo[$chanid]["from_topic_id"][$channelInfoNew[$k]["from_topic_id"]][$channelInfoNew[$k]["to"][$t]["chanid"]]=$channelInfoNew[$k]["to"][$t]["to_topic"];
	  } // if ($channelInfoNew[$t["chanid"]]["disabled"] == -1)
	 } else $forwardInfo[$chanid]["from_topic_id"][$channelInfoNew[$k]["from_topic_id"]][$channelInfoNew[$k]["to"][$t]["chanid"]]=$channelInfoNew[$k]["to"][$t]["to_topic"]; // if (array_key_exists($t["chanid"], $channelInfoNew)
    } // foreach ($channelInfoNew[$k]["to"] as $t)
   } // if (!array_key_exists("-1",$channelInfoNew[$k]["to"]) 
  } // if ($channelInfoNew["chanid"] == $chanid) 
 } // foreach(array_keys($channelInfoNew) as $k)
 if (count($forwardInfo) != 0) { return $forwardInfo; } else return false;
} // function end

function getChannelKeyFromChanid($chanid, $channelInfoNew) { // get all channelkeys? 
 foreach(array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["chanid"] == $chanid ) return $k;
 }
 return false;
} // function end

function loadPandabotConfig($conf=false) {
 global $askcommand, $recoverqueue, $globalsettings; 
 
 $channelsConf="conf/pandabot.conf";
 
 if ($conf) $channelsConf=$conf; 
  
 if (!$conf) logger("loadPandabotConfig: using: ".$channelsConf);
 
 checkChannelsConf($channelsConf);
 $data=yaml_parse_file($channelsConf); 
 
 $globalsettings["bot"]["botname"]=$data["botcommand"];
 $askcommand="!".$globalsettings["bot"]["botname"]." ";
 
 $globalsettings["request"]["requestcommand"]="#".$data["requestcommand"]." ";
 $globalsettings["bot"]["downloaddirectory"]=$data["downloaddirectory"];
 $requestcommand="#".$data["requestcommand"]." ";
 $globalsettings["db"]["dbhost"]=$data["dbhost"];
 $globalsettings["db"]["dbport"]=$data["dbport"];
 $globalsettings["db"]["dbuser"]=$data["dbuser"];
 $globalsettings["db"]["dbpass"]=$data["dbpass"];
 $globalsettings["db"]["dbname"]=$data["dbname"];

 $recoverqueue=$data["recover forward queue"]; 
 $globalsettings["forward"]["recoverqueue"]=$data["recover forward queue"]; 
} // function end

function CheckMyChannels($myChans, $chanid) {
 unset($channelOnPeerDatabase);
 foreach ($myChans as $mychan) {
  if (substr($mychan, 0, 4) == "-100") if (substr($mychan,4,null)==$chanid) $channelOnPeerDatabase=true;
 } // foreach ($myChans as $mychan) {
 if (!isset($channelOnPeerDatabase)) return false;
 return true;
}

function CheckDialog($dialog, $chanid, $dialogarray, $dialogkey) {
 foreach ($dialog[$dialogarray] as $d) if ($d['id']==$chanid) if (array_key_exists($dialogkey, $d)) return $d[$dialogkey];
 return false;
} // function end


function getConfTopicName($channelInfoNew, $chanid, $topic_id) {
 foreach(array_keys($channelInfoNew) as $k) {
  if (array_key_exists("to", $channelInfoNew[$k]) && !array_key_exists("-1", $channelInfoNew[$k]["to"])) {
   foreach (array_keys($channelInfoNew[$k]["to"]) as $t) if ($channelInfoNew[$k]["to"][$t]["chanid"]==$chanid) if ($channelInfoNew[$k]["to"][$t]["to_topic"] == $topic_id ) if ($channelInfoNew[$k]["to"][$t]["topic_name"] != "-1") return $channelInfoNew[$k]["to"][$t]["topic_name"];
  } // if (!array_key_exists("-1", $channelInfoNew[$k]["to"]))
 } // foreach(array_keys($data) as $c)
 return false;
} // function end

function checkChannelsConf($file) {
 if (!file_exists($file)) {
  echo "ERR: config file: ".$file." missing!\n";
  exit;
 }
} // function end

function checkPandabotPID() {
 global $donotaskPID;

 if (!isset($donotaskPID)) $donotaskPID=false;

 $tmpdir="log/tmp/";
 $pandabot="pandabot.pid";
 $mypid=getmypid();
 $lockfile=$tmpdir.$pandabot;
  
 if (file_exists($lockfile)) {
  $lockingPID = trim(file_get_contents($lockfile));
  $pidsshellout=shell_exec("ps -ef | awk -v pid=".$lockingPID." '{if ($2 == pid) {print $2}}'");
  
  $pids = explode("\n", $pidsshellout);
  if (in_array($lockingPID, $pids) && $donotaskPID==false) {
   logger("checkPandabotPID: ERR: pandabot is running @ pid: ".$lockingPID);
   exit;
  } // if (in_array($lockingPID, $pids)) 
 } // if (file_exists($tmpdir.$pandabot) 

  if (file_exists($lockfile)) unlink($lockfile);
  file_put_contents($lockfile, $mypid."\n"); 
} // function end

function copyChannelConfig($channelInfoNew) {
 $tmpdir="log/tmp/";
 $confdir="conf/";

 $channelsConfFile="channels.conf";
 $channelsConfOrig=$confdir.$channelsConfFile;
 $channelsConfTmp=$tmpdir.$channelsConfFile;

 if (file_exists($channelsConfTmp)) unlink($channelsConfTmp);

 writeChannelConfig($channelInfoNew);
 
 copy($channelsConfOrig, $channelsConfTmp);
} // function end


function loadChannelConfig($startup=false, $cfgfile=false) {
 global $shm, $globalsettings;
 if ($startup) { $channelsConf="conf/channels.conf"; } else $channelsConf="log/tmp/channels.conf";
 if ($cfgfile) $channelsConf=$cfgfile;
 
 $channelInfoNew=array();
 
 $globalsettings["channels"]["channeldb"]=made("", "getDialogIds()", -1);

// inject admin channel - predefine $channelInfoNew array
 $getSelf=made("","getSelf()",-1);
 $channelInfoNew["pandabot owner"]["chanid"]=$getSelf['id'];
 $channelInfoNew["pandabot owner"]["peerid"]=$channelInfoNew["pandabot owner"]["chanid"];
 $channelInfoNew["pandabot owner"]["typemapping"]="video";
 $channelInfoNew["pandabot owner"]["status"]="ok";
 $channelInfoNew["pandabot owner"]["info"]="pandabot admin channel - saved messages";
 $channelInfoNew["pandabot owner"]["from_topic_id"]=-1;
 $channelInfoNew["pandabot owner"]["from_topic_name"]=-1;
 $channelInfoNew["pandabot owner"]["autosync"]=-1;
 $channelInfoNew["pandabot owner"]["disabled"]=-1;
 $channelInfoNew["pandabot owner"]["mode"]="a";
 $channelInfoNew["pandabot owner"]["to"]["-1"]=array("chanid" => -1, "peerid" => -1, "status" => "nook", "info" => "no to settings @ admin channel", "to_topic" => -1, "topic_name" => -1, "name" => -1);
 $channelInfoNew["pandabot owner"]["name"]="@".$getSelf["username"];
 $channelInfoNew["pandabot owner"]["forward"]="nook";
 $channelInfoNew["pandabot owner"]["topicchannel"]=-1;
 $channelInfoNew["pandabot owner"]["redirectout"]=-1;
 $channelInfoNew["pandabot owner"]["redirectout_name"]=-1;
 $channelInfoNew["pandabot owner"]["redirectout_mode"]="link";
 $channelInfoNew["pandabot owner"]["redirectout_tochannel"]=-1;
 $channelInfoNew["pandabot owner"]["redirectout_tochannel_name"]=-1;
 $channelInfoNew["pandabot owner"]["channelbotname"]=$globalsettings["bot"]["botname"];
 $channelInfoNew["pandabot owner"]["repostinfomsg_msgid"]=-1;
 $channelInfoNew["pandabot owner"]["repostinfomsg_time"]=-1;
 $channelInfoNew["pandabot owner"]["repostinfomsg_timemode"]=-1;
 $channelInfoNew["pandabot owner"]["repostinfomsg_topicid"]=-1;
 $channelInfoNew["pandabot owner"]["channeluser"]=-1;
 
 
 logger("loadChannelConfig: using: ".$channelsConf);

 checkChannelsConf($channelsConf);
 
 $myChans=made("", "getDialogIds()", -1);

 $data=yaml_parse_file($channelsConf); 

 $countsections=1;

 foreach(array_keys($data) as $k) {
  $info="ready"; // channelstatus info
  
  if (array_key_exists("from", $data[$k])) { 
   $from=$data[$k]['from']; 
   
   $t=explode(":", $from); // topic on from channel
   if (array_key_exists(2,$t)) { $from=$t[0]."-".$t[2]; } else $from=$t[0]; // topic hack...

   if (!CheckMyChannels($myChans, $t[0])) { 
    $from_status="nook"; 
	$from_info="not on channel"; 
	$channelInfoNew[$from]["name"]=$k; 
	$channelInfoNew[$from]["forward"]="nook"; 
	$channelInfoNew[$from]["disabled"]=1; 
   } else { 
    $from_status="ok"; 
	$from_info="ready"; 
   }
   
   $channelInfoNew[$from]["chanid"]=$t[0];
   $channelInfoNew[$from]["peerid"]="-100".$t[0];

   $typemapping=$t;
   if (array_key_exists(1, $typemapping)) {
    if ($typemapping[1]=="topic") {
     $channelInfoNew[$from]["typemapping"]="video";
    } else {
     $channelInfoNew[$from]["typemapping"]=$typemapping[1];
    } // if ($typemapping=="topic") 
   } else {
    $channelInfoNew[$from]["typemapping"]="video";
   } // if (array_key_exists(1, $typemapping) - else
 

   $channelInfoNew[$from]["status"]=$from_status;
   $channelInfoNew[$from]["info"]=$from_info;

   $from_topic_id=-1; 
   $from_topic_name="-1"; 
   
   if ($channelInfoNew[$from]["status"] != "nook" ) if (array_key_exists(2,$t)) { 
    $from_topic_id=$t[2]; 
    $from_topic_name=getTopicName($channelInfoNew[$from]["chanid"], $t[2]);
   } // if (array_key_exists(2,$t))

   $channelInfoNew[$from]["from_topic_id"]=$from_topic_id;
   $channelInfoNew[$from]["from_topic_name"]=$from_topic_name;

  } else {
   $from_status="nook";
   $from_info="no from settings @ channel.conf, section: [".$k."]";
   $from=$k; // take human input section name, when from not set @ conf 
   $channelInfoNew[$from]["chanid"]=-1;
   $channelInfoNew[$from]["peerid"]=-1;
   $channelInfoNew[$from]["status"]=$from_status;
   $channelInfoNew[$from]["info"]=$from_info;
   $channelInfoNew[$from]["from_topic_id"]=-1;
   $channelInfoNew[$from]["from_topic_name"]=-1;
  } // if (array_key_exists("from", $data[$k])) - else
  
  if (array_key_exists("mode", $data[$k])) { $mode=$data[$k]['mode']; } else $mode=-1;
  $channelInfoNew[$from]["mode"]=$mode;

  if (array_key_exists("redirectout", $data[$k])) {
   $channelInfoNew[$from]["redirectout"]=explode(":",$data[$k]['redirectout'])[0]; 
   if (array_key_exists("1",explode(":",$data[$k]['redirectout']))) {
    $channelInfoNew[$from]["redirectout_mode"]=explode(":",$data[$k]['redirectout'])[1]; 
   } else $channelInfoNew[$from]["redirectout_mode"]="link";
   
   if (array_key_exists("2",explode(":",$data[$k]['redirectout']))) {
    $channelInfoNew[$from]["redirectout_tochannel"]=explode(":",$data[$k]['redirectout'])[2]; 
   } else $channelInfoNew[$from]["redirectout_tochannel"]=-1; 
	   
  } else $channelInfoNew[$from]["redirectout"]=-1;

  if (array_key_exists("channelbotname", $data[$k])) {
   $channelInfoNew[$from]["channelbotname"]=$data[$k]["channelbotname"];  
  } else {
   $channelInfoNew[$from]["channelbotname"]=$globalsettings["bot"]["botname"];  	  
  } // if (array_key_exists("channelbotname", $data[$k])) 

  if (array_key_exists("repostinfomsg", $data[$k])) {
   $channelInfoNew[$from]["repostinfomsg_msgid"]=explode(":", $data[$k]["repostinfomsg"])[0];  
   $channelInfoNew[$from]["repostinfomsg_time"]=explode(":", $data[$k]["repostinfomsg"])[1];  
   $channelInfoNew[$from]["repostinfomsg_timemode"]=explode(":", $data[$k]["repostinfomsg"])[2];  
   $channelInfoNew[$from]["repostinfomsg_topicid"]=explode(":", $data[$k]["repostinfomsg"])[3]; 

   // avoid spam 
   $minseconds=$globalsettings["channels"]["repostinfomintimer"] * 60;
   $minminutes=$globalsettings["channels"]["repostinfomintimer"];
   
   if ($channelInfoNew[$from]["repostinfomsg_timemode"]=="seconds" && ($channelInfoNew[$from]["repostinfomsg_time"] < $minseconds)) {
    $channelInfoNew[$from]["repostinfomsg_time"]=$minseconds;
   } //	if ($channelInfoNew[$from]["repostinfomsg_timemode"]=="seconds" && ($channelInfoNew[$from]["repostinfomsg_time"] < 600))
   if ($channelInfoNew[$from]["repostinfomsg_timemode"]=="minutes" && ($channelInfoNew[$from]["repostinfomsg_time"] < $minminutes)) {
    $channelInfoNew[$from]["repostinfomsg_time"]=$minminutes;
   } //	if ($channelInfoNew[$from]["repostinfomsg_timemode"]=="minutes" && ($channelInfoNew[$from]["repostinfomsg_time"] < 10))
	   
  } else {
   $channelInfoNew[$from]["repostinfomsg_msgid"]=-1;
   $channelInfoNew[$from]["repostinfomsg_time"]=-1;
   $channelInfoNew[$from]["repostinfomsg_timemode"]=-1;
   $channelInfoNew[$from]["repostinfomsg_topicid"]=-1;
  } // if (array_key_exists("repost", $data[$k]))   
  

  if (array_key_exists("autosync", $data[$k])) { 
   switch($data[$k]["autosync"]) {
    case "true":    
                  $autosync=1;
    break;
    case "force":
                  $autosync=2;
    break;
    default:
                  $autosync=-1;
   } // switch($data[$k]["autosync"])
  } else $autosync=-1; // if (array_key_exists("autosync", $data[$k])) 

  $channelInfoNew[$from]["autosync"]=$autosync; 

  if (array_key_exists("disabled", $data[$k]) && $channelInfoNew[$from]["status"] != "nook" ) { 
   switch($data[$k]["disabled"]) {
    case "true":    
                  $disabled=1;
				  $channelInfoNew[$from]["disabled"]=1;
				  $channelInfoNew[$from]["status"]="nook";
				  $channelInfoNew[$from]["info"]="disabled by user";
    break;
    case "updatedb":
                  $disabled=2;
				  $channelInfoNew[$from]["disabled"]=2;
				  $channelInfoNew[$from]["status"]="ok";
				  $channelInfoNew[$from]["info"]="no forward into channel by user(updatedb)";
    break;
    default:
                  $disabled=-1;
				  $channelInfoNew[$from]["disabled"]=-1;
				  $channelInfoNew[$from]["status"]="ok";
				  $channelInfoNew[$from]["info"]="ready";
   } // switch($data[$k]["disabled"])
  } else {
   $disabled=-1; 
   if ($channelInfoNew[$from]["status"] != "nook") {
	$channelInfoNew[$from]["disabled"]=-1;
    $channelInfoNew[$from]["status"]="ok";
    $channelInfoNew[$from]["info"]="ready";
   } // if ($channelInfoNew[$from]["status"] != "nook") 
  } // if (array_key_exists("disabled", $data[$k]) && $channelInfoNew[$from]["status"] != "nook" ) {  - else 

//  $channelInfoNew[$from]["disabled"]=$disabled; 

  if (array_key_exists("to", $data[$k])) { $to=$data[$k]['to']; } else $to=-1;
  if (is_array($to)) {
   if ($mode == -1) { $mode="r"; $channelInfoNew[$from]["mode"]=$mode; } // if mode not set, then change it to r
   $countto=1;
   foreach ($to as $t) {
    $t=explode(":", $t);
    if (array_key_exists(2,$t) && CheckMyChannels($myChans, $t[0])) { 
     $to_topic=$t[2]; 
     
     $tn=getConfTopicName($channelInfoNew, $t[0], $t[2]);
     if ($tn==false) {$topic_name=getTopicName($t[0], $t[2]);} else $topic_name=$tn;
    } else { 
     $to_topic=-1; $topic_name="-1"; 
    }
	
    if (!CheckMyChannels($myChans, $t[0])) { $to_status="nook"; $to_info="not on channel"; $name="no name"; } else { $to_status="ok"; $to_info="ready"; $name="-1"; }

    $channelInfoNew[$from]["to"][$t[0]]=array("chanid" => $t[0], "peerid" => "-100".$t[0], "status" => $to_status, "info" => $to_info, "to_topic" => $to_topic, "topic_name" => $topic_name, "name" => $name);

    if (array_key_exists($channelInfoNew[$from]["to"][$t[0]]["chanid"], $channelInfoNew)) {
     if ($channelInfoNew[$channelInfoNew[$from]["to"][$t[0]]["chanid"]]["disabled"] != -1) $channelInfoNew[$from]["to"][$t[0]]["info"]=$channelInfoNew[$channelInfoNew[$from]["to"][$t[0]]["chanid"]]["info"];
//	 if ($channelInfoNew[$channelInfoNew[$from]["to"][$t[0]]["chanid"]]["disabled"] == 1) $channelInfoNew[$from]["to"][$t[0]]["status"]=$channelInfoNew[$channelInfoNew[$from]["to"][$t[0]]["chanid"]]["status"];
	} // if (array_key_exists($channelInfoNew[$from]["to"][$t[0]]["chanid"], $channelInfoNew))
	
    $countto++;
   } // foreach ($to as $t)
  } else { 
   $name="-1";
   $topic_name="-1";
   $to_status="nook";
   $to_info="no to settings @ channel.conf, section: [".$k."]";
   $to_topic=-1;
   $channelInfoNew[$from]["to"]["-1"]=array("chanid" => -1, "peerid" => -1, "status" => $to_status, "info" => $to_info, "to_topic" => $to_topic, "topic_name" => $topic_name, "name" => $name);
  } // if (is_array($to)) - else

 $countsections++;
 } // foreach($keys as $k)

// info section
 $allchannels=array();
 foreach ($channelInfoNew as $chan) {
  if ($chan["mode"] != "a" ) { // do not insert admin channel
   if ($chan["peerid"]!="-1") if ($chan["status"]=="ok" || ($chan["status"]=="nook" && $chan["disabled"]==1 && $chan["info"] != "not on channel")) if (!asearch($chan["peerid"], $allchannels)) $allchannels[]=$chan["peerid"]; 
   foreach($chan["to"] as $t) if ($t["status"]=="ok") if (!asearch($t["peerid"], $allchannels)) $allchannels[]=$t["peerid"]; 
  } // if ($chan["mode"] != "a" ) 
 }

 $dialog=made("messages", "getPeerDialogs", array("peers" => $allchannels));

 foreach (array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["mode"] != "a" ) { // do not change admin user
   if ($channelInfoNew[$k]["peerid"]!="-1") {


    if ($channelInfoNew[$k]["status"]=="ok" || ($channelInfoNew[$k]["status"] == "nook" && $channelInfoNew[$k]["disabled"] == 1 && $channelInfoNew[$k]["info"] != "not on channel")) {

/*    
     if ($channelInfoNew[$k]["from_topic_id"] !=-1 ) {
      $channelInfoNew[$k]["name"]=removeChannelAds(cleanupString(CheckDialog($dialog, $channelInfoNew[$k]["peerid"], "chats", "title")))."-".$channelInfoNew[$k]["from_topic_name"];
     } else $channelInfoNew[$k]["name"]=removeChannelAds(cleanupString(CheckDialog($dialog, $channelInfoNew[$k]["peerid"], "chats", "title"))); 
*/
    if ($channelInfoNew[$k]["from_topic_id"] !=-1 ) {
      $channelInfoNew[$k]["name"]=CheckDialog($dialog, $channelInfoNew[$k]["peerid"], "chats", "title")."-".$channelInfoNew[$k]["from_topic_name"];
     } else $channelInfoNew[$k]["name"]=CheckDialog($dialog, $channelInfoNew[$k]["peerid"], "chats", "title"); 

     if (CheckDialog($dialog, $channelInfoNew[$k]["peerid"], "chats", "forum") == 1) { $channelInfoNew[$k]["topicchannel"]=1; } else $channelInfoNew[$k]["topicchannel"]=-1;

     if (CheckDialog($dialog, $channelInfoNew[$k]["peerid"], "chats", "noforwards") == 1) {
      $channelInfoNew[$k]["forward"]="nook";
      $channelInfoNew[$k]["status"]="nook";
      $channelInfoNew[$k]["info"]="forward disabled";
     } else { $channelInfoNew[$k]["forward"]="ok"; } // if (CheckDialog($dialog, $channelInfoNew[$k]["chanid"], "chats", "noforwards") == 1) - else

     if (is_array(CheckDialog($dialog,$channelInfoNew[$k]["peerid"], "chats", "restriction_reason"))) {
      $restriction_reason=CheckDialog($dialog,$channelInfoNew[$k]["peerid"], "chats", "restriction_reason");
      switch ($restriction_reason["0"]["reason"]) {
        case "copyright":
         $channelInfoNew[$k]["status"]="nook";
         $channelInfoNew[$k]["info"]=$restriction_reason["0"]["text"];
        break;
        case "porn":
         $channelInfoNew[$k]["status"]="ok";
         $channelInfoNew[$k]["info"]="ready, but: ".$restriction_reason["0"]["text"];
        break;
        default:
          $channelInfoNew[$k]["status"]="ok";
          $channelInfoNew[$k]["info"]="ready, but: ".$restriction_reason["0"]["text"];
      } // switch ($dialog["chats"]["0"]["restriction_reason"]["0"]["reason"]) 
     } // if (is_array(CheckDialog($dialog,$channelInfoNew[$k]["chanid"], "chats", "restriction_reason")) 
    }  // if ($channelInfoNew[$k]["chanid"]!="-1") if ($channelInfoNew[$k]["status"]=="ok") 
   } else {
    $channelInfoNew[$k]["name"]=$k;
   } // if ($channelInfoNew[$k]["chanid"]!="-1") - else
   
   foreach(array_keys($channelInfoNew[$k]["to"]) as $tk) if ($channelInfoNew[$k]["to"][$tk]["status"]=="ok") {
/*
    $channelInfoNew[$k]["to"][$tk]["name"]=removeChannelAds(cleanupString(CheckDialog($dialog, $channelInfoNew[$k]["to"][$tk]["peerid"], "chats", "title")));
*/
    $channelInfoNew[$k]["to"][$tk]["name"]=CheckDialog($dialog, $channelInfoNew[$k]["to"][$tk]["peerid"], "chats", "title");

   } // foreach(array_keys($channelInfoNew[$k]["to"]) as $tk) if ($channelInfoNew[$k]["to"][$tk]["status"]=="ok")
  } // if ($channelInfoNew[$k]["mode"] != "a" )
 } // foreach (array_keys($channelInfoNew) as $k) 

// redirectout - extra round
 foreach (array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["redirectout"]!="-1") {
   if (array_key_exists($channelInfoNew[$k]["redirectout"],$channelInfoNew)) { 
    $channelInfoNew[$k]["redirectout_name"]=$channelInfoNew[$channelInfoNew[$k]["redirectout"]]["name"]; 
   } else $channelInfoNew[$k]["redirectout"]=-1;
  } // if ($channelInfoNew[$k]["redirectout"]!="-1") 
 } // foreach (array_keys($channelInfoNew) as $k) 

// redirectout_tochannel - extra round && predefine admins element
 foreach (array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["redirectout"]!="-1") {
   if (array_key_exists($channelInfoNew[$k]["redirectout_tochannel"],$channelInfoNew)) { 
    $channelInfoNew[$k]["redirectout_tochannel_name"]=$channelInfoNew[$channelInfoNew[$k]["redirectout_tochannel"]]["name"]; 
   } else $channelInfoNew[$k]["redirectout_tochannel"]=-1;
  } // if ($channelInfoNew[$k]["redirectout"]!="-1") 
 } // foreach (array_keys($channelInfoNew) as $k) 

 $globalsettings["channels"]["channelinfo"]=$channelInfoNew;
 shm_put_var($shm, 4, $globalsettings["channels"]["channelinfo"]);

// print_r($globalsettings);
// exit();
 
 return $globalsettings["channels"]["channelinfo"];
} // function end
 
function writeChannelConfig($channelInfoNew) {
 global $globalsettings;
//print_r($channelInfoNew);

 $channelsConf="conf/channels.conf";
 if (file_exists($channelsConf)) unlink($channelsConf); // remove channels.conf

$header="# attention: bot rewrite hes own conf file in human readable form
# all \"to:\" channels automatical r mode and will be readed
# all channels without \"to:\" will be still readed and saved in database
# from and section names must be unique, otherwise, the last find will be used
# example section config:
# -----------------------
#
# '<unique name>': 
#  mode: r                      # modus i for interactiv (botcommands) or r for readonly - ir = interactiv + request mode
#  channelbotname: name         # overwrites pandabot.conf:botcommand eg. eva, adam or ... default is pandabot.conf:botcommand 
#  autosync: true 				# or false - is false by default - ATTENTION! TARGET CHANNEL SHOULD BE FULL READ @ DATABASE!                                                 
#  disabled: true 				# or updatedb or false - is false by default
#  from: <channelid>            # from:type:topicid - forward only files from specificated topic
#  to:
#   - <channelid1>
#   - <channelid2>:topic:<topicid>                   # send forwards in topic
#   - <channelid3>
#   - <channelid4>
#   - ...
#
# redirectout: <channelid>:<link|id>:<targetchannelid> # means print search/ last results from another channel(<channelid>) to current channel
# is <targetchannelid> configured, he will search in channelid and forward to targetchannelid
# eg. channel1: search in channelid and will forward to targetchannelid
# use !<botname> last<x> channel:current to list last<x> entrys in current channel
# use !<botname> search <term> channel:current to search in current channel
#
# repostinfomsg: <msgid>:<time>:<timemode>:<topic> # eg. repostinfomsg: 1234:5:minutes:-1 (-1 no topic, otherwise topicid)
# <timemode>: seconds, minutes, hours, days - min. reposttime: 30 minutes
#
# types can only be setup @ from: 
# from: <channelid>                # set default video
# from: <channelid>:mp3            # set type to mp3
# from: <channelid>:movie:topicid  # set type to movie only from topicid 
#
# valid types are: mp3, flac, audio, audiobooks, ebooks, movie, moviefhd, movie4gb, archive, video - default video (means video files with an minimum duration from 15 minutes)
# all audio types: have no min. duration, movie: min. duration 75 minutes
# moviefhd: movie fhd(+) and min size 1.7gb, movie4gb min size 2.5 gb  
# archive: zip, rar, zZ and so on...
#
# simple section conf:
# --------------------
# <unique name>:
#  from: <channelid>
#  to:
#   - <channelid>
#
# -------------------";

 file_put_contents($channelsConf, sprintf("%s\n\n", $header),  FILE_APPEND | LOCK_EX);

 foreach (array_keys($channelInfoNew) as $k) {
  if ($channelInfoNew[$k]["mode"] != "a" ) { // do not write admin channel
//   print_r($channelInfoNew[$k]);
   file_put_contents($channelsConf, sprintf("'%s': \n", $channelInfoNew[$k]["name"]), FILE_APPEND | LOCK_EX);
   if ($channelInfoNew[$k]["mode"] != -1 ) file_put_contents($channelsConf, sprintf(" mode: %s \n", $channelInfoNew[$k]["mode"]), FILE_APPEND | LOCK_EX);

   if ($channelInfoNew[$k]["autosync"] != -1) file_put_contents($channelsConf, sprintf(" autosync: %s \n", "true"), FILE_APPEND | LOCK_EX);
   
   if ($channelInfoNew[$k]["channelbotname"] != $globalsettings["bot"]["botname"]) file_put_contents($channelsConf, sprintf(" channelbotname: %s \n", $channelInfoNew[$k]["channelbotname"]), FILE_APPEND | LOCK_EX);

   if ($channelInfoNew[$k]["repostinfomsg_msgid"] != -1) file_put_contents($channelsConf, sprintf(" repostinfomsg: %s:%s:%s:%s \n", $channelInfoNew[$k]["repostinfomsg_msgid"], $channelInfoNew[$k]["repostinfomsg_time"], $channelInfoNew[$k]["repostinfomsg_timemode"] ,$channelInfoNew[$k]["repostinfomsg_topicid"]), FILE_APPEND | LOCK_EX);

   if ($channelInfoNew[$k]["redirectout"] != -1) file_put_contents($channelsConf, sprintf(" redirectout: %s:%s:%-19s # [%s] \n", $channelInfoNew[$k]["redirectout"], $channelInfoNew[$k]["redirectout_mode"], $channelInfoNew[$k]["redirectout_tochannel"], $channelInfoNew[$k]["redirectout_name"] ), FILE_APPEND | LOCK_EX);
   
   switch($channelInfoNew[$k]["disabled"]) {
    case "1":    
             file_put_contents($channelsConf, sprintf(" disabled: %s \n", "true"), FILE_APPEND | LOCK_EX);
    break;
    case "2":
             file_put_contents($channelsConf, sprintf(" disabled: %s \n", "updatedb"), FILE_APPEND | LOCK_EX); 
    break;
    } // switch($channelInfoNew[$k]["disabled"]) 
   
   if ($channelInfoNew[$k]["status"]=="nook" ) { $status="ERR:"; } else $status=$channelInfoNew[$k]["status"];

   if ($channelInfoNew[$k]["chanid"] != -1) {
    if ($channelInfoNew[$k]["from_topic_id"] != -1) {
     file_put_contents($channelsConf, sprintf(" from: %s:%s:%-12s # %-4s [%s] - %s\n", $channelInfoNew[$k]["chanid"], $channelInfoNew[$k]["typemapping"], $channelInfoNew[$k]["from_topic_id"], $status, $channelInfoNew[$k]["name"], $channelInfoNew[$k]["info"]), FILE_APPEND | LOCK_EX);
     } else file_put_contents($channelsConf, sprintf(" from: %s:%-15s # %-4s [%s] - %s\n", $channelInfoNew[$k]["chanid"], $channelInfoNew[$k]["typemapping"], $status, $channelInfoNew[$k]["name"], $channelInfoNew[$k]["info"]), FILE_APPEND | LOCK_EX);
   } // if ($channelInfoNew[$k]["chanid"] != -1) 

   if (!array_key_exists("-1", $channelInfoNew[$k]["to"])) { 
    file_put_contents($channelsConf, sprintf(" to: \n"), FILE_APPEND | LOCK_EX);
    foreach (array_keys($channelInfoNew[$k]["to"]) as $t) {
     if ($channelInfoNew[$k]["to"][$t]["to_topic"] !=-1 ) { 
      if ($channelInfoNew[$k]["to"][$t]["status"]=="nook") { $status="ERR:"; } else $status=$channelInfoNew[$k]["to"][$t]["status"];
      file_put_contents($channelsConf, sprintf("  - %s:topic:%-12s # %-4s [%s:%s] - %s \n", $channelInfoNew[$k]["to"][$t]["chanid"], $channelInfoNew[$k]["to"][$t]["to_topic"], $status, $channelInfoNew[$k]["to"][$t]["name"], $channelInfoNew[$k]["to"][$t]["topic_name"], $channelInfoNew[$k]["to"][$t]["info"]), FILE_APPEND | LOCK_EX);
     } else { 
      if ($channelInfoNew[$k]["to"][$t]["status"]=="nook") { $status="ERR:"; } else $status=$channelInfoNew[$k]["to"][$t]["status"];
      file_put_contents($channelsConf, sprintf("  - %-29s # %-4s [%s] - %s \n", $channelInfoNew[$k]["to"][$t]["chanid"], $status, $channelInfoNew[$k]["to"][$t]["name"], $channelInfoNew[$k]["to"][$t]["info"]), FILE_APPEND | LOCK_EX);
     } // if ($channelInfoNew[$k]["to"][$t]["to_topic"]
    } // foreach (array_keys($channelInfoNew[$k]["to"] as $t)
   } // if (!array_key_exists("-1", $channelInfoNew[$k]["to"]))

  file_put_contents($channelsConf, sprintf("\n# -------------------\n\n"), FILE_APPEND | LOCK_EX);

  } // if ($channelInfoNew[$k]["mode"] != "a" ) 
 } // foreach (array_keys($channelInfoNew) as $k) 

 chmod($channelsConf, 0666); // makes channels.conf writeable for samba user, when user uses vm, like me, with samba shares.. :-)
} // funcion end


// these inc contains:
//
// loadChannelConfig()
// loadPandabotConfig()
// writeChannelConfig()
// copyChannelConfig()
// checkPandabotPID()
// buildautoSyncChannels()
// getChannelKeyFromChanid()
// forwardInfo()
// mappingInfo()
