<?php

// redirectout: channelid:link|id - default link $redirectout_mode

function generatebotmarker(){ 
 global $globalsettings; 
 
 $globalsettings["message"]["deletemarker"]=preg_replace("/[0-4]/u" ,",", $globalsettings["bot"]["starttime"]);
 $globalsettings["message"]["deletemarker"]=preg_replace("/[5-9]/u" ,".", $globalsettings["message"]["deletemarker"]);
 return $globalsettings["message"]["deletemarker"];
} // function end 

function cacheasks($infoarray) {
 global $globalsettings;
/*
 $infoarray['mode']="reply";
 $infoarray['channelid']=-1;
 $infoarray['channelname']=-1;
 $infoarray['msgid']=-1;
 $infoarray['msgdate']=-1;
 $infoarray['message']=-1;   
 $infoarray['userid']=-1;   
 $infoarray['username']=-1;
 $infoarray['topicid']=-1;
 $infoarray['replyid']=-1;   
 $infoarray['bot']=-1; 
 $infoarray['channelInfoKey']=$channelInfoKey;
*/

 $sql="select msgid from cacheAsks where grpid=".$infoarray["channelid"]." and msgid=".$infoarray["msgid"];
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 while ($row = pg_fetch_array($result)) {
   $askid=$row['msgid']; 
 } // while ($row = pg_fetch_array($result))
	 
 if (!isset($askid)) { // no entry in db
 
  getlastbotcommands($infoarray); 
 
 $sql=sprintf("insert into cacheAsks values (%s,'%s',%s,%s,'%s',%s,'%s');", $infoarray["channelid"], pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray["channelname"]), $infoarray["msgid"], $infoarray["userid"], pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray["username"]), $infoarray["msgdate"] ,pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray["message"]));
  pg_query($globalsettings["db"]["pg_conn"], $sql);	
  
  $sql="insert into deletemessages (channelid, msgid, timestamp) values (".$infoarray['channelid'].",".$infoarray['msgid'].",".$infoarray['msgdate'].") on conflict do nothing;";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
  
  return 1; // new command 
 } else { 
  return -1;
 } // if (!isset($askid)) - old command do nothing
} // function end

function sendmessageintochannel($channelInfoKey, $message, $topicid, $html=true) {
 global $channelInfoNew; // mode.... array(array("peer" =>) in made - switch, default... build array befor
  if ($topicid!=-1) { 
  made("messages", "sendMessage", array("peer" => $channelInfoNew[$channelInfoKey]["peerid"], "message" => $message, "top_msg_id" => $topicid, "parse_mode" => "html")); 
  made("messages", "sendMessage", array("peer" => $channelInfoNew[$channelInfoKey]["peerid"], "message" => $message, "top_msg_id" => $topicid, "parse_mode" => "html")); 
 } else {
  made("messages", "sendMessage", array("peer" => $channelInfoNew[$channelInfoKey]["peerid"], "message" => $message, "parse_mode" => "html")); 
 } // if ($topicid!=-1) 
} // function end 

function requestusage($channelInfoKey, $command, $mode="default") {
 global $channelInfoNew, $globalsettings;
 $usage="";
 switch($mode) {
   case "error":
     $usage.="<b>no valid (".$command.")<code> ".$globalsettings["request"]["requestcommand"]."</code> command!</b><br><br>please <b><u>delete</u></b> ur ".$globalsettings["request"]["requestcommand"]." and try another stunt.<br><br>";
   case "help": 
     $usage.="- <code>".$globalsettings["request"]["requestcommand"]."help</code><br>";
     $usage.="- <code>".$globalsettings["request"]["requestcommand"]."list</code><br>";
	 $usage.="- <code>".$globalsettings["request"]["requestcommand"]."#resolve</code> ".htmlspecialchars("<title> <year>")."<br><br>";

	 if ($channelInfoNew[$channelInfoKey]["redirectout"] != -1) {
      switch ($channelInfoNew[$channelInfoKey]["redirectout_mode"]) {
	   case "id": 
	    $usage.="<b>redirect mode</b>:<br>";
	    $usage.="- <code>".$globalsettings["request"]["requestcommand"]."#getfile</code> ".htmlspecialchars("<msgid>")."<br><br>";	   
	   break;
      } // switch ($channelInfoNew[$channelInfoKey]["redirectout_mode"]) 

		 

	 } // if ($channelInfoNew[$channelInfoKey]["redirectout"] != -1) 

   break;	 
   case "invalidrequest":
     $usage.="<b>no valid request: ".$command."</b><br><br>please <b><u>delete</u></b> ur ".$globalsettings["request"]["requestcommand"]." and try another stunt.<br><br>";
   break;
   case "alreadyondb":
   case "replyonrequest":
   case "fulfillednotcorrect":
   case "resolve":
     $usage.=$command."<br>";
   break;
 } // switch($mode)
 
 $default="- <code>".$globalsettings["request"]["requestcommand"]."</code> &lt;title&gt; &lt;year&gt;<br>eg. <code>".$globalsettings["request"]["requestcommand"]."</code>Kung Fu Panda 4 2024<br>";
 $usage.=$default;
 $usage.=generatebotmarker();
 return $usage;
 
} // function end

function listopenrequests($channelInfoKey, $topicid) {
 global $globalsettings, $channelInfoNew;
 
 $sql="select title, year, link from requests where channelid=".$channelInfoNew[$channelInfoKey]["chanid"]." and fulfills = -1 and deleted = -1";
// echo $sql."\n";
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
 $output="<b>open requests:</b><br>";
 
 if ($numrows != 0) { 
  while ($row = pg_fetch_array($result)) {
   $output.="<code>".$row['title']." ".$row['year']."</code>: <a href='".$row['link']."'>➡️</a><br>";
  } // while ($row = pg_fetch_array($result)) 
 } else {
  $output.="no open requests<br>";
 }//  if ($numrows != 0)

 $output.=generatebotmarker();
 sendmessageintochannel($channelInfoKey, $output, $topicid);

} // function end 


function workonrequest($channelInfoKey, $message, $topicid, $username, $userid, $channelname, $channelid, $msgid, $infoarray) {
 global $channelInfoNew, $globalsettings;

 preg_match_all("/(.+?)\W?(\d{4})?$/mu", $message, $res);
 $reqmsg="";

 $year=$res[count($res)-1][0];
  
 $title=$res[count($res)-2][0];
 $title=preg_replace("/^".strtolower($globalsettings["request"]["requestcommand"])."/u", "", strtolower($title));
 $title=preg_replace("/^\s+|\s+$|\s+(?=\s)/u", "", $title);
 $title=strtolower($title);
 $title=htmlspecialchars($title);

 $reqmsg.="channelname: ".$channelname."<br>";
// $reqmsg.="channelid: ".$channelid."<br>"; // security reason 
 $reqmsg.="messageid: ".$msgid."<br>";
 $reqmsg.="username: ".$username."<br>"; 
// $reqmsg.="userid: ".$userid."<br>"; // privacy reason 
  
 $link="https://t.me/c/".$channelid."/".$msgid;
// $reqmsg.="link: ".$link."<br>"; // security reason
 $reqmsg.="request: ".$message."<br>";

 $reqmsg.="title: ".$title."<br>";
 $reqmsg.="year: ".$year."<br>";

 if (explode(" ",$title)[0] == "#getfile" ) {
  $getfile_msgid=explode(" ",$message)[2];
  
  if (!ctype_digit($getfile_msgid)) {
   sendmessageintochannel($channelInfoKey, "❌<b>".$globalsettings["request"]["requestcommand"]." #getfile</b>: invalid message id: ".$getfile_msgid."<br>".generatebotmarker(), $topicid);
   return;
  } // if (!ctype_digit($input)) 
  
  redirect_getfile($channelInfoKey, $getfile_msgid, $topicid, $infoarray);
  return;
 } // if (explode(" ",$title)[0] == "#getfile" ) 

 if(!preg_match("/^\d{4}$/u", $year)) {
  sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, htmlspecialchars($message), "invalidrequest"), $topicid);
  return;
 } // if(!preg_match("/^\d{4}$/u", $year)) 

 if (explode(" ",$title)[0] == "#resolve" ) {
  resolve($channelInfoKey, $topicid, $title, $year, $infoarray);
  return;
 } // if (explode(" ",$title)[0] == "resolve" ) 



 if (substr(explode(" ",$title)[0],0,1) == "#" ) {
  sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, htmlspecialchars($message), "invalidrequest"), $topicid);	 
  return;
 } // if (substr(explode(" ",$title)[0],0) == "#" )	 

	 
 $sql="select channelid, msgid, link, fulfills, request, fulfillsmessage, fulfillslink from requests where channelid=".$channelid." and title='".pg_escape_string($globalsettings["db"]["pg_conn"], $title)."' and year=".$year;

 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 while ($row = pg_fetch_array($result)) {
  $reschannelid=$row['channelid']; 
  $resmsgid=$row['msgid']; 
  $reslink=$row['link']; 
  $fulfilled=$row['fulfills'];
  $request=$row['request'];
  $fulfillsmessage=$row['fulfillsmessage'];
  $fulfillslink=$row['fulfillslink'];
 } // while ($row = pg_fetch_array($result))
	 
 if (isset($reschannelid)) { // already in db
  if ($fulfilled==1) { $fmarker="and fulfilled"; } else $fmarker=""; // auto search? when fulfilled==1
  $alreadymsg="";
  $alreadymsg.="❌<b>".$title." ".$year." - already requested ".$fmarker."</b><br>";
  $alreadymsg.="<blockquote>".$request."</blockquote><br>";
  $alreadymsg.="<a href='".$reslink."'>↪️</a><br>";
  
  if ($fulfilled==1) { $alreadymsg.="<blockquote>".$fulfillsmessage."</blockquote><br><a href='".$fulfillslink."'>↪️</a><br>"; }
    
  sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, $alreadymsg, "alreadyondb"), $topicid);
  return;
 } // if (isset($reschannelid))

 $sql="insert into requests (channelid,
                             channelname,
                             msgid, 
                             userid,
                             username,
                             timestamp,
                             request,
                             title,
                             year,
                             link) values (".$channelid.",
                                          '".pg_escape_string($globalsettings["db"]["pg_conn"], $channelname)."',
                                           ".$msgid.",
                                           ".$userid.",
                                          '".pg_escape_string($globalsettings["db"]["pg_conn"], $username)."',
                                           ".time().",
                                          '".pg_escape_string($globalsettings["db"]["pg_conn"], $message)."',
                                          '".pg_escape_string($globalsettings["db"]["pg_conn"], $title)."',										   
                                           ".$year.",
                                          '".pg_escape_string($globalsettings["db"]["pg_conn"], $link)."')";

 pg_query($globalsettings["db"]["pg_conn"], $sql);
 $reqmsg.="<b>request saved</b><br>";
 sendmessageintochannel($channelInfoKey, "📝<b>request mode</b>:<br>".$reqmsg.generatebotmarker(), $topicid);

} // function end

function deletemessages($infoarray) {
 global $globalsettings;
 
 
 if (substr($infoarray["channelid"],0,4) == "-100" ) {
  print_r($infoarray);	
  exit;
 }

 if ($infoarray['userid'] == $globalsettings["bot"]["pandaownerid"] || $infoarray['bot'] == 1) {
  $sql="insert into deletemessages (channelid, msgid, timestamp) values (".$infoarray['channelid'].",".$infoarray['msgid'].",".$infoarray['msgdate'].") on conflict do nothing;";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
 } // if ($infoarray['userid'] == $pandaOwner)
} // function end

function deleteMarkedMessagesJob() {
 global $globalsettings, $channelInfoNew;
 
 logger("job: deleteMarkedMessages");
 
 $deltime=time() - $globalsettings["message"]["deletemessagestimer"];
 $sql="select channelid, msgid from deletemessages where timestamp < ".$deltime." order by channelid limit 50"; // delete only 50 message per run...

 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
 if ($numrows != 0) {
  while ($row = pg_fetch_array($result)) {
   $deletearray[$row['channelid']][]=$row['msgid'];
  } // while ($row = pg_fetch_array($result)) 
 
  foreach (array_keys($deletearray) as $deletemsgkey) { 
   made("channels", "deleteMessages", array("channel" => $channelInfoNew[$deletemsgkey]["peerid"], "id" => $deletearray[$deletemsgkey])); 
   foreach ($deletearray[$deletemsgkey] as $todelete) {
    $sql="delete from deletemessages where channelid=".$deletemsgkey." and msgid=".$todelete;
    pg_query($globalsettings["db"]["pg_conn"], $sql);
   } // foreach ($deletearray[$deletemsgkey] as $todelete) 
  } // foreach (array_keys($deletearray) as $deletemsgkey) 
 } // if ($numrows != 0) 
} // function end 

function deleteRequestMessagesJob() {
 global $globalsettings;	
 $deltime=time() - ($globalsettings["request"]["requestMessagesDeleteTimer"] * 86400);
 $sql="update requests set deleted = 1 where timestamp < ".$deltime;
 pg_query($globalsettings["db"]["pg_conn"], $sql);
} // function end

function checkfulfillmessage($infoarray) {
 $linktest=preg_match_all("/(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/mu", $infoarray['message'], $res);
 if (!$linktest) { 
  $message="";
  $message="❌<b>dear honored santa</b><br>";
  $message.="please reply with link<br>";
  $message.="<br>";
  $message.="eg.<br>";
  $message.="ur request are fulfilled:<br>";
  $message.="https://t.me/c/1234/1234<br>";
  
  sendmessageintochannel($infoarray['channelid'], requestusage($infoarray['channelInfoKey'], $message, "fulfillednotcorrect"), $infoarray['topicid']); 
 } else {
  $message="";
  $message="<b>dear honored santa</b><br>";
  $message.="found link on: ".$infoarray['msgid']."<br>";

  sendmessageintochannel($infoarray['channelid'], requestusage($infoarray['channelInfoKey'], $message, "fulfillednotcorrect"), $infoarray['topicid']); 
 } 
 return false;
} // function end

function requestsolution($infoarray) {
 global $globalsettings;
 
 $sql="select msgid, title, year, link from requests where channelid=".$infoarray['channelid']." and msgid=".$infoarray['replyid']." and fulfills = -1";
  
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
 if ($numrows != 0) {
  while ($row = pg_fetch_array($result)) {
   $requestfulfills['msgid']=$row['msgid'];
   $requestfulfills['title']=$row['title'];
   $requestfulfills['year']=$row['year'];
   $requestfulfills['link']=$row['link'];
  } // while ($row = pg_fetch_array($result))  	
 } // if ($numrows != 0) 
	 
 if (isset($requestfulfills)) {

// if (!checkfulfillmessage($infoarray)) return;
 
  
  $link="https://t.me/c/".$infoarray['channelid']."/".$infoarray['msgid'];
  $sql="update requests set fulfills=1,
                            fulfillsmsgid=".$infoarray['msgid'].",
							fulfillsmessage='".pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray['message'])."',
                            fulfillsuserid=".$infoarray['userid'].",
                            fulfillsusername='".pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray['username'])."',
                            fulfillstimestamp=".time().",
						    fulfillslink='".pg_escape_string($globalsettings["db"]["pg_conn"], $link)."'
        where channelid=".$infoarray['channelid']." and msgid=".$infoarray['replyid'];

  pg_query($globalsettings["db"]["pg_conn"], $sql);

  // clear up request message, when resolved over reply - non practicable ... ?!? 
  // time()+86400
  $sql="insert into deletemessages (channelid, msgid, timestamp) values (".$infoarray['channelid'].",".$infoarray['replyid'].",".time().") on conflict do nothing;";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
  
  $message="";
  $message="<b>request fulfilled</b><br>";
  $message.="link: ".$requestfulfills['link']."<br>";
  $message.="title: ".$requestfulfills['title']."<br>";
  $message.="year: ".$requestfulfills['year']."<br>";
  $message.="revolver: ".$infoarray['username']."<br>";
 
  sendmessageintochannel($infoarray['channelid'], requestusage($infoarray['channelInfoKey'], $message, "replyonrequest"), $infoarray['topicid']); 
 } // if (isset($requestfulfills)) 
} // function end

function getMessageMarker($infoarray) {
 global $globalsettings;
// print_r($infoarray);
 switch ($infoarray['mode']) {
  case "generatebotmarker": // check if userid == botowner...$infoarray['userid'] 
                            if (preg_match("/".generatebotmarker()."/u", $infoarray['message'])) deletemessages($infoarray);
  break;
  case "reply": 
               if ($infoarray['replyid'] != -1) {
    			requestsolution($infoarray);
			   }
  break;
 } // switch ($marker) 
} // function end

function getreplyid($data, $infoarray) {
 foreach($data['messages'] as $msg) {
  if ($msg['id']==$infoarray['msgid'] ) {
   if (array_key_exists('reply_to', $msg)) { 
    if (array_key_exists('reply_to_msg_id', $msg['reply_to'])) { // reply_to_top_id
	 if ($msg['reply_to']['forum_topic'] == 1 && (array_key_exists('reply_to_msg_id', $msg['reply_to']) && (array_key_exists('reply_to_top_id', $msg['reply_to']) && $msg['reply_to']['reply_to_msg_id'] != $msg['reply_to']['reply_to_top_id']))) {
	  return $msg['reply_to']['reply_to_msg_id'];
	 } // if ($msg['reply_to']['forum_topic'] == 1 && !array_key_exists('reply_to_top_id', $msg['reply_to'])) peu, peu 
	 if ($msg['reply_to']['forum_topic'] == "") {
	  return $msg['reply_to']['reply_to_msg_id'];
	 } // if ($msg['reply_to']['forum_topic'] == "")
	} // if (array_key_exists('reply_to_msg_id', $msg['reply_to'])) 
   } // if (!array_key_exists('reply_to', $msg))
  } // if ($msg['id']==$msgid )
 } // foreach($data['messages'] as $msg) 
 return -1;
} // function end

function resolve($channelInfoKey, $topicid, $title, $year, $infoarray) {
 global $channelInfoNew, $globalsettings;
 
 $link="https://t.me/c/".$infoarray['channelid']."/".$infoarray['msgid'];
 
 $title=str_replace("#resolve ", "", $title);
 $out="<b>resolve:</b><br><br>";
 $out.="title: ".$title."<br>";
 $out.="year: ".$year."<br>";
 $out.="revolver: ".$infoarray['username']."<br>";

 $sql="select channelid, msgid from requests where channelid=".$channelInfoNew[$channelInfoKey]["chanid"]." and title='".pg_escape_string($globalsettings["db"]["pg_conn"], $title)."' and year=".$year." and fulfills = -1 and deleted = -1"; 

 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
 
 if ($numrows != 0) {
  while ($row = pg_fetch_array($result)) {
   $channelid=$row["channelid"];
   $msgid=$row["msgid"];
  } // while ($row = pg_fetch_array($result)) 
  $sql="update requests set fulfills=1,
                            fulfillsmsgid=".$infoarray['msgid'].",
							fulfillsmessage='manualy resolved',
                            fulfillsuserid=".$infoarray['userid'].",
                            fulfillsusername='".pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray['username'])."',
                            fulfillstimestamp=".time().",
						    fulfillslink='".pg_escape_string($globalsettings["db"]["pg_conn"], $link)."'
        where channelid=".$infoarray['channelid']." and msgid=".$msgid;
  pg_query($globalsettings["db"]["pg_conn"], $sql);
  $out.="<br><b>request manualy solved</b> by user<br>";	 

 } else $out.="<br>❌<b>no open request</b><br>"; // if ($numrows != 0)
 
 sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, $out, "resolve") , $topicid);
} // function end

function clearupall($channelInfoKey,$topicid, $infoarray) {
 global $channelInfoNew, $globalsettings;
 
 $link="https://t.me/c/".$infoarray['channelid']."/".$infoarray['msgid']; // damn link! -> infoarray 

 $sql="update requests set fulfills=1,
                            fulfillsmsgid=".$infoarray['msgid'].",
							fulfillsmessage='clear up list',
                            fulfillsuserid=".$infoarray['userid'].",
                            fulfillsusername='".pg_escape_string($globalsettings["db"]["pg_conn"], $infoarray['username'])."',
                            fulfillstimestamp=".time().",
						    fulfillslink='".pg_escape_string($globalsettings["db"]["pg_conn"], $link)."'
        where fulfills = -1 and deleted = -1 and channelid=".$infoarray['channelid'];
		
 $sql="delete from requests where fulfills = -1 and deleted = -1 and channelid=".$infoarray['channelid'];

 pg_query($globalsettings["db"]["pg_conn"], $sql);
 
 sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, "done", "resolve") , $topicid);

} // function end


function request($data, $channelInfoKey) {
 global $channelInfoNew, $globalsettings; 

// $infoarray['channelInfoKey']=$channelInfoKey; ??? channelid, channelname obsolete 
 $infoarray['mode']="reply";
 $infoarray['channelid']=-1;
 $infoarray['channelname']=-1;
 $infoarray['msgid']=-1;
 $infoarray['msgdate']=-1;
 $infoarray['message']=-1;   
 $infoarray['userid']=-1;   
 $infoarray['username']=-1;
 $infoarray['topicid']=-1;
 $infoarray['replyid']=-1;   
 $infoarray['bot']=-1; 
 $infoarray['channelInfoKey']=$channelInfoKey;


 foreach($data['messages'] as $msg) {
  if (array_key_exists('message', $msg)) {

   $channelid=substr($data['chats'][0]['id'],4);
   $channelname=preg_replace("/[^a-zA-Z0-9]+!/u", "",$data['chats'][0]['title']);
   $msgid=$msg['id'];
   $msgdate=$msg['date'];
   $message=preg_replace("/[^a-zA-Z0-9]+!/u", "",$msg['message']);

   $userdata=getUserData($msg, $data);
   $userid=$userdata['user_id'];
   $username=$userdata['username'];
   $userfirstname=$userdata['first_name'];
   $userlastname=$userdata['last_name'];
   $botuser=$userdata['bot']; // gehen wir davon aus, dass wenn der user in einem channel posten kann, dann kann er auch löschen?!?

   $topicid=-1; // backwards to get reply on request - reply (fulsfills)    
   if (array_key_exists("reply_to", $msg)) {
    if (array_key_exists("forum_topic", $msg["reply_to"])) {
     $topicid=$msg["reply_to"]["reply_to_msg_id"]; 
     if (array_key_exists("reply_to_top_id",$msg["reply_to"])) $topicid=$msg["reply_to"]["reply_to_top_id"]; 
    } // if (array_key_exists("forum_topic", $msg["reply_to"))
   } // if (array_key_exists("reply_to", $msg)) 

   $infoarray['channelid']=$channelid;
   $infoarray['channelname']=$channelname;
   $infoarray['msgid']=$msgid;
   $infoarray['msgdate']=$msgdate;
   $infoarray['message']=$message;   
   $infoarray['userid']=$userid;   
   $infoarray['username']=$username;
   $infoarray['topicid']=$topicid;
   $infoarray['bot']=$botuser;   
  
   unset($getreplyid);
   $getreplyid=getreplyid($data, $infoarray);
   
   if (isset($getreplyid) && $getreplyid != -1) { $infoarray['replyid']=$getreplyid; } else { $infoarray['replyid']=-1; }
   getMessageMarker($infoarray); 


   $messagefix=substr($msg['message'],0,strlen($globalsettings["request"]["requestcommand"])); // single !request command without options fixed over str like function str_contains()?
   if (strlen(substr($msg['message'],0,strlen($globalsettings["request"]["requestcommand"])))+1 == strlen($globalsettings["request"]["requestcommand"])) $messagefix.=" "; // damn... linebreak direct after requestcommand, no check if more than one line... str_contains str_contains str_contains str_contains - take it!
   if (strtolower($messagefix) == strtolower($globalsettings["request"]["requestcommand"])) { // regex ^ ?!? 

    if (cacheasks($infoarray) == 1 ) {
     logger("request on channel: [".$channelInfoNew[$channelInfoKey]["name"]."] - request ".$msg['message'].": valid request command");
     $requestmsg=explode(" ",$message);
	 if (count($requestmsg) == 1) { $command=$requestmsg[0]; } else $command=$requestmsg[1];
	 switch (count($requestmsg)) {
	  case 1: sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, $command, "help"), $topicid);
	  break;
	  case 2:
	   switch ($requestmsg[1]) {
        case "help": sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, $command, "help"), $topicid);
		break;
        case "list": listopenrequests($channelInfoKey,$topicid);
        break;    
        case "clearupall": clearupall($channelInfoKey,$topicid, $infoarray);
        break;    

	    default:     sendmessageintochannel($channelInfoKey, requestusage($channelInfoKey, $command, "error"), $topicid);
	   } // switch ($requestmsg[1])  
	  break;
	  default:       workonrequest($channelInfoKey, $message, $topicid, $username, $userid, $channelname, $channelid, $msgid, $infoarray );
	 } // switch (count($requestmsg)) 
	} // if (cacheasks() == 1 ) 
   } // if (substr($msg['message'],0,strlen($globalsettings["request"]["requestcommand"])) == $globalsettings["request"]["requestcommand"]) 
  } // if (array_key_exists('message', $msg)) 
 } // foreach($data['messages'] as $msg) 
} // function end

// these inc contains:
//
// request();
// cacheasks();
// sendmessageintochannel();
// requestusage();
// workonrequest();
// generatebotmarker();
// deletemessages();
// deleteMarkedMessagesJob();
// getMessageMarker();
// getreplyid();
// deleteRequestMessagesJob(); 
// checkfulfillmessage();
// listopenrequests();

// use $lastMessagePerChan array to remove old entry's from cacheaskstable... 150-200 messages... would be work fine. (attention, deleted messages...)
// job, cleanasktableJob(), once @ day or so... job settings...