<?php

function getlastexceptions($infoarray) {
 global $globalsettings;
 $exceptionkey=$infoarray["exceptiontimestamp"]."-".$infoarray["exceptionmessage"];
} // function end 

function getlastbotcommands($infoarray) {
 global $globalsettings;
 
 $commandskey=$infoarray['channelid']."-".$infoarray['msgid'];
 
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["msgid"]=$infoarray['msgid'];
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["message"]=htmlspecialchars($infoarray['message']);
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["channelname"]=htmlspecialchars($infoarray['channelname']);
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["channelid"]=$infoarray['channelid'];
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["username"]=htmlspecialchars($infoarray['username']);
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["userid"]=$infoarray['userid'];
 $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]["msgdate"]=$infoarray['msgdate'];

 // move to array element 1
 $globalsettings["bot"]["lastbotcommands"]["commands"]=array($commandskey => $globalsettings["bot"]["lastbotcommands"]["commands"][$commandskey]) + $globalsettings["bot"]["lastbotcommands"]["commands"];

 // restrict array length 
 $globalsettings["bot"]["lastbotcommands"]["commands"]=array_slice($globalsettings["bot"]["lastbotcommands"]["commands"], 0, $globalsettings["bot"]["lastbotcommands"]["count"]);
} // function end

function showlastbotcommands($arguments) {
 global $globalsettings;

 $outputcounter=0;
 $output="list last <b>".$globalsettings["bot"]["lastbotcommands"]["count"]."</b> botcommands:<br>";

 if (array_key_exists(1,$arguments)) { 
  switch ($arguments[1]) {
   case "help": $output.="<code>lastbotcommands</code>(list over all channels><br><code>lastbotcommands</code> ".htmlspecialchars("<channelid>")." (show only channel 123, use <code>channelstatus</code>)<br>";
    $help=1;
   break;
   default:
    if (!array_key_exists($arguments[1], $globalsettings["bot"]["channelinfo"])) {
	 $output.="channelid: <b>".$arguments[1]."</b> does not exists!<br>try: <code>channelstatus</code><br><br><code>lastbotcommands</code><br>";
     $help=1;
   } else {
	 $setchannel=$arguments[1];
   } // if (!array_key_exists($arguments[1], $globalsettings["bot"]["channelinfo"])) {
  } // switch ($arguments) 
 } // if (array_key_exists(1,$arguments)) 

 if (array_key_exists("commands", $globalsettings["bot"]["lastbotcommands"]) && is_array($globalsettings["bot"]["lastbotcommands"]["commands"]) && count($globalsettings["bot"]["lastbotcommands"]["commands"])!=0 && !isset($help)) {
  foreach ($globalsettings["bot"]["lastbotcommands"]["commands"] as $command) {
   if (!isset($setchannel)) { 
    $outputcounter++;
    $output.="channel: <b><a href='https://t.me/c/".$command["channelid"]."'>".$command["channelname"]."</a></b>, user: <b>@".$command["username"]."</b><br>"; 
    $output.="<b>command</b>(".date('m/d/Y H:i:s', $command["msgdate"])."): <b><code>".$command["message"]."</code></b><br>--<br>"; 
   } else {
	if ($setchannel==$command["channelid"]) {
	 $outputcounter++;
     $output.="channel: <b><a href='https://t.me/c/".$command["channelid"]."'>".$command["channelname"]."</a></b>, user: <b>@".$command["username"]."</b><br>"; 
     $output.="<b>command</b>(".date('m/d/Y H:i:s', $command["msgdate"])."): <b><code>".$command["message"]."</code></b><br>--<br>"; 
	} // if ($setchannel==$command["channelid"]) 
   } // if (!isset($setchannel)) 	   
  } // foreach ($globalsettings["bot"]["lastbotcommands"]["commands"] as $commands) 
 } else {
  if (!isset($help) || $outputcounter!=0) $output.="no botcommands used<br>";
 } // if (array_key_exists("commands",$globalsettings["bot"]["lastbotcommands"]) && count($globalsettings["bot"]["lastbotcommands"]["commands"])!=0) 

 $topicid=-1;
 sendmessageintochannel("pandabot owner", $output, $topicid);		
} // function end

function channel_detail($channel){
 global $globalsettings, $channelInfoNew;
  
 $channelInfoKey=$channel[1];
 $topicid=-1;
 
 if (!array_key_exists($channelInfoKey, $channelInfoNew)) {
  $output="channelid: <b>".$channelInfoKey."</b> does not exists!<br>";
  sendmessageintochannel("pandabot owner", $output, $topicid);		 
  return;
 } // if (!array_key_exists($channelInfoKey, $channelInfoNew))
 
 $output="";
 $output.="<b>name:</b> ".htmlspecialchars($channelInfoNew[$channelInfoKey]["name"])."<br><br>";

 $output.="<b>channelbotname:</b> ".htmlspecialchars($channelInfoNew[$channelInfoKey]["channelbotname"])."<br>";
 
 switch ($channelInfoNew[$channelInfoKey]["mode"]) {
  case "a": $output.="<b>mode:</b> admin<br>";
  break;
  case "i": $output.="<b>mode:</b> interactiv<br>";
  break;
  case "ir": $output.="<b>mode:</b> interactiv+request<br>";
  break;
  case "r": $output.="<b>mode:</b> read only<br>";
  break;
 } // switch ($channelInfoNew[$channelInfoKey]["mode"]) 

 $output.="<b>typemapping:</b> ".$channelInfoNew[$channelInfoKey]["typemapping"]."<br>";

 switch ($channelInfoNew[$channelInfoKey]["autosync"]) {
  case -1: $output.="<b>autosync:</b> false<br>";
  break;
  case 1: $output.="<b>autosync:</b> true<br>";
  break;
  case 2: $output.="<b>autosync:</b> force<br>";
  break;
 } // switch ($channelInfoNew[$channelInfoKey]["autosync"]) 

 switch ($channelInfoNew[$channelInfoKey]["disabled"]) {
  case -1: $output.="<b>disabled:</b> false<br>";
  break;
  case 1: $output.="<b>disabled:</b> true<br>";
  break;
  case 2: $output.="<b>disabled:</b> updatedb<br>";
  break;
 } // switch ($channelInfoNew[$channelInfoKey]["disabled"]) 
 
 if (array_key_exists("-1", $channelInfoNew[$channelInfoKey]["to"])) {
  $output.="<b>to</b>: no target channels configured<br>";
 } else {
  $output.="<b>to</b>:<br>";
  foreach (array_keys($channelInfoNew[$channelInfoKey]["to"]) as $t) {
   $output.=" - ".$channelInfoNew[$channelInfoKey]["to"][$t]["name"]."<br>";	  
  } // foreach (array_keys($channelInfoNew[$channelInfoKey]["to"]) as $t) 	  
 } // if (array_key_exists("-1", $channelInfoNew[$channelInfoKey]["to"])) 

 $output.="<br>"; 
 if ($channelInfoNew[$channelInfoKey]["redirectout"]==-1) {
  $output.="<b>redirect</b>: not configured<br>";
 } else {
  $output.="<b>redirect from</b>: ".htmlspecialchars($channelInfoNew[$channelInfoKey]["redirectout_name"])."<br>";
  $output.="<b>redirect mode</b>: ".htmlspecialchars($channelInfoNew[$channelInfoKey]["redirectout_mode"])."<br>";
  if ($channelInfoNew[$channelInfoKey]["redirectout_tochannel"]!=-1) {
   $output.="<b>redirect to</b>: ".htmlspecialchars($channelInfoNew[$channelInfoKey]["redirectout_tochannel_name"])."<br>";  	  
  } else {
   $output.="<b>redirect to</b>: ".htmlspecialchars($channelInfoNew[$channelInfoKey]["name"])."<br>";
  } // if ($channelInfoNew[$channelInfoKey]["redirectout_tochannel"]==-1) 
 } // if ($channelInfoNew[$channelInfoKey]["redirectout"]==-1)) 

 if (array_key_exists(2,$channel) && $channel[2]=="dump") {$output=htmlspecialchars(print_r($channelInfoNew[$channelInfoKey], true));}
 
 sendmessageintochannel("pandabot owner", $output, $topicid);	
} // function end

function ifconfigkeyvaluevalid($key, $value) {
 global $globalsettings;
 switch ($key) {
	 case "mode":
	  foreach($globalsettings["bot"]["channelmode"] as $mode) {
	   if ($value == $mode) {
		return $value;
	   } // if ($value == $mode) 
	  } // foreach($globalsettings["bot"]["channelmode"] as $mode) 
      return false;
	 break;
	 case "autosync":
	 // echo "autosync here ".$value."\n";
	  foreach($globalsettings["bot"]["autosyncmode"] as $mode) {
	   switch ($value) {
                      case "true": if ($mode==$value) return 1;
					  break;
                      case "force": if ($mode==$value) return 2;
					  break;
                      case "false": if ($mode==$value) return -1;
					  break;
       } // switch ($mode) 
	  } // foreach($globalsettings["bot"]["autosyncmode"] as $mode) 
	  return false;
	 break; 
	 case "disabled":
	 // echo "disabled here ".$value."\n";
	  foreach($globalsettings["bot"]["disabledmode"] as $mode) {
	   switch ($value) {
                      case "true": if ($mode==$value) return 1;
					  break;
                      case "updatedb": if ($mode==$value) return 2;
					  break;
                      case "false": if ($mode==$value) return -1;
					  break;
       } // switch ($mode) 
	  } // foreach($globalsettings["bot"]["autosyncmode"] as $mode) 
	  return false;
	 break; 	 
	 case "channelbotname":
	 // echo "channelbotname here ".$value."\n";
	  if (preg_match("/^[a-zA-Z]+$/", $value) && strlen($value)<7) {
	   return $value;
	  } else {
	   return false;
	  } // if (preg_match("/^[a-zA-Z]+$/", $value) 
	 break; 	 
 } // switch ($key) 
} // function end


function setchannel($arguments) {
 global $globalsettings, $channelInfoNew;	
 
 $usage="<b>usage</b>: setchannel ".htmlspecialchars("<channelid> <option> <value>")."<br>";
 
 if (count($arguments) == 1) {
  $output=$usage;	 
  $output.="<br>";
  $output.="possible options to set: <br>";
  foreach ($globalsettings["admin"]["setchannel"] as $validkey) $output.=" - <code>".$validkey."</code><br>";
  sendmessageintochannel("pandabot owner", $output, -1);
  return;
 } // if (count($arguments) == 1) 
	 
	 
 if (array_key_exists(1,$arguments) && array_key_exists($arguments[1], $channelInfoNew)) { 
  $channelInfoKey=$arguments[1];
  $usage="<b>usage</b>: setchannel ".htmlspecialchars("<channelid> <option> <value>")."<br>use <code>channelstatus ".$channelInfoKey."</code>";
 } else {
  $channelInfoKey=$arguments[1];
  sendmessageintochannel("pandabot owner", "<b>channelid</b>(".$channelInfoKey.") not valid<br>use <code>channelstatus</code><br>".$usage, -1);
  return;
 }// if (array_key_exists(1,$arguments)) 

 if (array_key_exists(2,$arguments)){ 
  $setkey=$arguments[2];
  if (!asearch($setkey, $globalsettings["admin"]["setchannel"])) {
   $output="option(".$setkey.") is invalid<br><b>avaible options's:</b><br>";
   foreach ($globalsettings["admin"]["setchannel"] as $validkey) {
	$output.=" - ".$validkey."<br>";
   } // foreach ($globalsettings["admin"]["setchannel"] as $validkey) 
   $output.=$usage;
   sendmessageintochannel("pandabot owner", $output, -1);
   return;
  } // if (!asearch($setkey, $globalsettings["admin"]["setchannel"])) 
 } else {
//  sendmessageintochannel("pandabot owner", "<b>key</b> not valid<br>".$usage, -1);
//  return;
 } // if (array_key_exists(2,$arguments))
	 
 if (array_key_exists(3,$arguments)) {
  $setvalue=$arguments[3];
  switch($setkey) {
   case "mode":
             if (ifconfigkeyvaluevalid($setkey, $setvalue)) {
              sendmessageintochannel("pandabot owner", "setup channel(".$channelInfoNew["$channelInfoKey"]["name"].") mode from ".$channelInfoNew["$channelInfoKey"]["mode"]." to: ".$setvalue."<br>", -1);
			  $channelInfoNew[$channelInfoKey]["mode"]=$setvalue;
			 } else {
			  $output="<b>value(".$setvalue.") invalid</b>, valid values are:<br>";
			  foreach ($globalsettings["bot"]["channelmode"] as $mode) $output.=" - ".$mode."<br>";
			  
              sendmessageintochannel("pandabot owner", $output, -1);
			 } // if (ifconfigkeyvaluevalid($setkey, $setvalue) 
   break;
   case "autosync": 
             if (ifconfigkeyvaluevalid($setkey, $setvalue)) {
              sendmessageintochannel("pandabot owner", "setup channel(".$channelInfoNew["$channelInfoKey"]["name"].") autosync from ".$channelInfoNew["$channelInfoKey"]["autosync"]." to: ".ifconfigkeyvaluevalid($setkey, $setvalue)."<br>", -1);
			  $channelInfoNew[$channelInfoKey]["autosync"]=ifconfigkeyvaluevalid($setkey, $setvalue);
			 } else {
			  $output="autosync <b>value(".$setvalue.") invalid</b>, valid values are:<br>";
			  foreach ($globalsettings["bot"]["autosyncmode"] as $mode) $output.=" - ".$mode."<br>";
              sendmessageintochannel("pandabot owner", $output, -1);
			 } // if (ifconfigkeyvaluevalid($setkey, $setvalue)) 
   break;
   case "disabled": 
             if (ifconfigkeyvaluevalid($setkey, $setvalue)) {
              sendmessageintochannel("pandabot owner", "setup channel(".$channelInfoNew["$channelInfoKey"]["name"].") disabled from ".$channelInfoNew["$channelInfoKey"]["disabled"]." to: ".ifconfigkeyvaluevalid($setkey, $setvalue)."<br>", -1);
			  $channelInfoNew[$channelInfoKey]["disabled"]=ifconfigkeyvaluevalid($setkey, $setvalue);
			 } else {
			  $output="disabled <b>value(".$setvalue.") invalid</b>, valid values are:<br>";
			  foreach ($globalsettings["bot"]["disabledmode"] as $mode) $output.=" - ".$mode."<br>";
              sendmessageintochannel("pandabot owner", $output, -1);
			 } // if (ifconfigkeyvaluevalid($setkey, $setvalue)) 
   break;
   case "channelbotname":
             if (ifconfigkeyvaluevalid($setkey, $setvalue)) {
              sendmessageintochannel("pandabot owner", "setup channel(<b>".$channelInfoNew["$channelInfoKey"]["name"]."</b>) channelbotname from: <b>".$channelInfoNew["$channelInfoKey"]["channelbotname"]."</b> to: <b>".$setvalue."</b><br>", -1);
			  
              sendmessageintochannel($channelInfoKey, "setup channel(<b>".$channelInfoNew["$channelInfoKey"]["name"]."</b>) channelbotname from: <b>".$channelInfoNew["$channelInfoKey"]["channelbotname"]."</b> to: <b>".$setvalue."</b><br>".generatebotmarker(), -1);

			  $channelInfoNew[$channelInfoKey]["channelbotname"]=$setvalue;
			 } else {
			  $output="<b>value(".$setvalue.") invalid</b>, only (max. 6) letters allow<br>";
			  
              sendmessageintochannel("pandabot owner", $output, -1);
			 } // if (ifconfigkeyvaluevalid($setkey, $setvalue) 
   break;
  } // switch($setkey) 	 
	 
 } else {
  sendmessageintochannel("pandabot owner", "<b>value</b> not valid<br>".$usage, -1);
 } // if (array_key_exists(3,$arguments))  
} // function end

function clearqueue($arguments) {
 global $globalsettings;	
 
 $sql="select id from forwardqueue";
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
  
 if (array_key_exists(1,$arguments) && $arguments[1]=="yes") {
  $sql="delete from forwardqueue";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
  sendmessageintochannel("pandabot owner", "db queue(".$numrows.") is cleared<br>", -1);
 } else {
  sendmessageintochannel("pandabot owner", "use: clearqueue yes<br>".$numrows." entrys on db<br>", -1);
 } // if (array_key_exists(1,$arguments) && $arguments[1]=="yes") 
} // function end

function saveconfig($arguments) {
 global $globalsettings, $channelInfoNew;	
 if (array_key_exists(1,$arguments) && $arguments[1]=="yes") {
  $globalsettings["bot"]["channelinfo"]=$channelInfoNew;
  writeChannelConfig($channelInfoNew);
  sendmessageintochannel("pandabot owner", "config rewriten<br>", -1);
 } else {
  sendmessageintochannel("pandabot owner", "use: saveconfig yes<br>", -1);
 } // if (array_key_exists(1,$arguments) && $arguments[1]=="yes") 
} // function end

function user($arguments) {
 global $globalsettings, $channelInfoNew;	

/*
 $arguments is every time an array 
*/ 

$usage="user usage: <br>
user ".htmlspecialchars("<channelid>")."<br>
user ".htmlspecialchars("<username>")."<br>
user ".htmlspecialchars("<userid>")."<br>";

 if (count($arguments) == 0) { 
  sendmessageintochannel("pandabot owner", $usage ,-1);
  return;
 } // if (count($arguments) == 0) 

 if (array_key_exists(1, $arguments) && (array_key_exists($arguments[1], $channelInfoNew))) {
  $channelInfoKey=$arguments[1];
  usr_managment($channelInfoKey);
  $out="";
  foreach (array_keys($channelInfoNew[$channelInfoKey]["channeluser"]) as $userid) {
   $umout=usr_managment($channelInfoKey, "userid", $userid);
   if ($umout != false) {
	$out.="un: @".htmlspecialchars($umout[$userid]["username"])." fn: ".htmlspecialchars($umout[$userid]["full_name"])." role: ".htmlspecialchars($umout[$userid]["role"])."<br>";
   } else { 
    $out="no rights to read user on channel: ".$channelInfoNew[$channelInfoKey]["name"]."(".$channelInfoKey.")<br>";
   } // if ($umout != false)
  } // foreach ($channelInfoNew[$channelInfoKey]["channeluser"] $userid) 
  sendmessageintochannel("pandabot owner", $out, -1);
 } else {
  sendmessageintochannel("pandabot owner", "use: user ".htmlspecialchars("<channelid>")."<br>", -1);
 } // if (array_key_exists(1,$arguments) && $arguments[1]=="yes") 
} // function end

function loadconfig($arguments) {
 global $globalsettings, $channelInfoNew;	
 if (array_key_exists(1,$arguments) && $arguments[1]=="yes") {
  $globalsettings["bot"]["channelinfo"]=$channelInfoNew;
  initbot(true);
  sendmessageintochannel("pandabot owner", "config loaded<br>", -1);
 } else {
  sendmessageintochannel("pandabot owner", "use: loadconfig yes<br>", -1);
 } // if (array_key_exists(1,$arguments) && $arguments[1]=="yes") 
} // function end

function adminCommands($data, $startup) {
 global $globalsettings, $runtimeForwardCounter, $runtimeForwardCalls, $isJobRunning, $databaseMessageCount, $version, $channelInfoNew, $floodwait, $toForward, $forwardstopmsg;
 
 date_default_timezone_set('Europe/Berlin');
 $date=gmdate("Y-m-d H:i:s", time()+date("Z"));
 
 if (!is_array($data)) return;

 foreach($data['messages'] as $msg) {
  if (array_key_exists('message', $msg)) {
    
   unset($cmd);
   foreach ($globalsettings["bot"]["adminbotcommands"] as $admincmd) { if (substr($msg['message'],0,strlen($admincmd)) == $admincmd) $cmd=$admincmd; }

   if (isset($cmd)) {
    $msgid=$msg['id'];
    $message=$msg['message'];
    $date=$msg['date'];

    $admaction="";
    if ($startup) { $admaction=" - do nothing, startup"; logger("admincommand: ".$message.$admaction); }

    $sql="delete from cacheAsks where grpName='".pg_escape_string($globalsettings["db"]["pg_conn"], $globalsettings["bot"]["pandaownerid"])."' and grpid=-1 and msgid<(select max(msgid)-150 as msgid from cacheAsks where grpid=-1 and grpName='".pg_escape_string($globalsettings["db"]["pg_conn"], $globalsettings["bot"]["pandaownerid"])."')";
    $result=pg_query($globalsettings["db"]["pg_conn"], $sql);

    unset($result);
    unset($askid);
    $sql="select msgid from cacheAsks where grpid=-1 and grpName='".pg_escape_string($globalsettings["db"]["pg_conn"], $globalsettings["bot"]["pandaownerid"])."' and msgid=".$msgid;
    $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
    while ($row = pg_fetch_array($result)) { $askid=$row['msgid']; }
               
    if (!isset($askid)) { // no entry in db 
     unset($result);
     $sql=sprintf("insert into cacheAsks values (%s,'%s',%s,%s,'%s',%s,'%s')\n", -1, pg_escape_string($globalsettings["db"]["pg_conn"], $globalsettings["bot"]["pandaownerid"]), $msgid, -1, pg_escape_string($globalsettings["db"]["pg_conn"], $globalsettings["bot"]["pandaownerid"]), $date, pg_escape_string($globalsettings["db"]["pg_conn"], $message));
     $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
        
     if (!$startup) {
      $admaction="";
      logger("admincommand: ".$message.$admaction);

      switch ($cmd) {
      case "jobstatus": 
                      $sendMsg="<pre>".htmlspecialchars(var_dump($isJobRunning))."</pre>";
                      made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));
      break;
      case "help": 
                   $sendMsg="<b> avaible commands</b>:<br>";
                   foreach ($globalsettings["bot"]["adminbotcommands"] as $admincmd) $sendMsg.="-<code> ".$admincmd." </code><br>";
				   
                   made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg."<br>", "parse_mode" => "html"));
      break;
      case "topics": $channel=explode(" ", $message); 
                       if (!array_key_exists(1,$channel)) {
                        $sendMsg=" - usage: <code>topics</code> <b>".htmlspecialchars("<channelid>")."</b> use:<code> channelstatus</code>";
                       } else {
                        $sendMsg=" - <code>topics</code> <b>".htmlspecialchars("<channelid>")."</b> use:<code> channelstatus</code>";
                        if (array_key_exists(1,$channel)) {
                         $ck=getChannelKeyFromChanid($channel[1], $channelInfoNew);
                         if (is_numeric($channel[1])) $sendMsg=getTopicIds($ck); 
                        } // if (array_key_exists(1,$channel))
                       } // if (!array_key_exists(1,$channel)) - else

                       made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));
     break;
      case "download": $link=explode(" ", $message); 
                       if (!array_key_exists(1,$link)) {
                        $sendMsg=" - usage: <code>download</code> <b>".htmlspecialchars("<link>")."</b> use: <code>https://t.me/123456/654321</code>";
                       } else {
                        if (array_key_exists(1,$link)) {
						 $sendMsg=" - <code>download</code> <b>".htmlspecialchars($link[1])."</b>";
						 $regex ="/^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$/";if (preg_match($regex, $link[1])) {
						 // $sendMsg=" - <code>download</code> <b>".htmlspecialchars($link[1])."</b> is an link";
						  download($link[1]);
						 } else {
						  $sendMsg=" - <code>download</code> <b>".htmlspecialchars($link[1])."</b> no valid link";
					     } // if (preg_match($regex, $link[1]))
                        } // if (array_key_exists(1,$channel))
                       } // if (!array_key_exists(1,$channel)) - else

                       made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));
     break;
      case "stats": 
                           if ($floodwait != -1) {
                            $currenttime=time();
                            $waittime="<br><br><b>".$forwardstopmsg.": </b>".dhms($floodwait - $currenttime);
                           } else $waittime="";
                            $forwardqueue=realForwardCount();
                            $currentTime=time();
	                        $runtime=dhms($currentTime - $globalsettings["bot"]["starttime"]);  
              	            $sendMsg="runtime:           <b>".$runtime."</b> - load: <b>".$globalsettings["bot"]["systemload"][0].", ".$globalsettings["bot"]["systemload"][1].", ".$globalsettings["bot"]["systemload"][2]."</b><br>forwards:          <b>".$runtimeForwardCounter."</b> forwards in <b>".$runtimeForwardCalls."</b> steps<br>forwardqueue: <b>".$forwardqueue."</b><br><br>version: <b>".$globalsettings["bot"]["version"]."</b>".$waittime;
							
							$sendMsg.="<br>".generatebotmarker();
                            made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));
      break;

      case "reloadconfig":  loadPandabotConfig(); 
							$channelInfoNew=loadChannelConfig(true);
                            copyChannelConfig($channelInfoNew);
							
                            made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));
      break;

      case "channelstatus": $channel=explode(" ", $message); 
	                        if (array_key_exists(1,$channel)) { channel_detail($channel); break; }
	                        $sendMsg=""; $out=array();
                            foreach(array_keys($channelInfoNew) as $k) {
                             if ($channelInfoNew[$k]["mode"] != "a" ) {
                              if (mb_strlen($channelInfoNew[$k]['name']) >= 30) { $name=mb_substr($channelInfoNew[$k]['name'],0,30)."..."; } else $name=$channelInfoNew[$k]['name'];
                              if ($channelInfoNew[$k]["status"] == "nook" ) { 
                               $out[]=array("status" => "ERR", "info" => $channelInfoNew[$k]["info"], "name" => $name, "chanid" => $channelInfoNew[$k]["chanid"]);
                              } else {
                               $out[]=array("status" => "OK", "info" => $channelInfoNew[$k]["info"], "name" => $name, "chanid" => $channelInfoNew[$k]["chanid"]);
                              } // if ($channelInfoNew[$k]["status"] == "nook" )
                             } // if ($channelInfoNew[$k]["mode"] != "a" )
                            } // foreach(array_keys($channelInfoNew) as $k)
                            array_multisort(array_column($out, 'status'), SORT_DESC, $out); 
                            foreach($out as $o) {
                             $sendMsg.="<b>".$o["status"]."</b> - ".htmlspecialchars($o["info"])." : ".htmlspecialchars($o["name"])."<br><code>".$o["chanid"]."</code><br>";
                            } // foreach($out as $o) 

                            made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));
      break;
	  case "clearqueue": clearqueue($arguments=explode(" ", $message));
	  break;
	  case "saveconfig": saveconfig($arguments=explode(" ", $message));
	  break;
	  case "loadconfig": loadconfig($arguments=explode(" ", $message));
	  break;
	  case "setchannel": setchannel($arguments=explode(" ", $message));
	  break;
	  case "user": user($arguments=explode(" ", $message));
	  break;
	  case "lastbotcommands": showlastbotcommands($arguments=explode(" ", $message));
	  break;	  
      default: // does actual not work - admincmd will be filtered via settings...
              $sendMsg="<b>pandabot</b>: invalid admincmd: <b>".htmlspecialchars($cmd)."</b> use: <b>help</b><br>"; 
              made("messages","sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendMsg, "parse_mode" => "html"));

      } // switch ($cmd)
     } // if (!$startup) {
    } // if (!isset($askid)) 
    made("messages","deleteMessages", array("channel" => "me", "id" => array($msgid)));
   } // if (isset($cmd))
  } // if (array_key_exists('message', $msg))
 } // foreach($madeReturn['messages'] as $msg)
} // function end

