<?php

function last($grpid, $limit, $channelInfoKey, $infoarray, $topic=false) {
 global $globalsettings, $channelInfoNew;

 if ($topic && $channelInfoNew[$channelInfoKey]["topicchannel"] == 1 && $topic!=strtolower("channel:current")) { $topicclausel=" and (lower(cleantopicname) like '%".pg_escape_string($globalsettings["db"]["pg_conn"], strtolower($topic))."%' or lower(topicname) like '%".pg_escape_string($globalsettings["db"]["pg_conn"], strtolower($topic))."%')"; } else $topicclausel="";

 
 $current=-1;
 if ($topic==strtolower("channel:current")) $current=1;
 


 $o_channelInfoKey=$grpid;
 if ($channelInfoNew[$grpid]["redirectout"] != -1 && $current==-1) {
  $o_channelInfoKey=$grpid; $grpid=$channelInfoNew[$grpid]["redirectout"];
 } else {
  if (array_key_exists("redirectout_tochannel", $channelInfoNew[$o_channelInfoKey]) && $channelInfoNew[$o_channelInfoKey]["redirectout_tochannel"] != -1) {
   $grpid=$channelInfoNew[$o_channelInfoKey]["redirectout_tochannel"];	  
  } // if ($channelInfoNew[$grpid]["redirectout_tochannel"] != -1) 
 } // if ($channelInfoNew[$grpid]["redirectout"] != -1 && $current==-1)

 $sql="select msgid, substr(message, 0, ".$globalsettings["message"]["cuttext"].") as message, substr(cleanmessage, 0, ".$globalsettings["message"]["cuttext"].") as cleanmessage, msgdate, link, width, height, size, filename, mime_type, grouped_id from chan_".$grpid." where type='messageMediaDocument'".$topicclausel." and (mime_type like 'audio%' or (mime_type like 'video%' and duration > 15) or ( mime_type like 'application%' and mime_type not like '%sticker%')) order by msgid desc limit ".$limit;
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);

 $numrows=pg_num_rows($result);
 if ($numrows == 0) {
  $returnMsg[0]="TOUSER";
  $returnMsg[1]="LAST".$limit.": no matches found";
  return $returnMsg;
 }

 $returnMsg[1]="";
 while ($row = pg_fetch_array($result)) {
  if ($row['grouped_id'] == -1) { $albumout="| Ⓢ"; } else $albumout="| Ⓐ";
  if ($row['width'] == -1) { $dim=""; } else  $dim="<code>".$row['width']."x".$row['height']."</code> ".$albumout." | ";
  
  $text=htmlspecialchars($row['cleanmessage']); 
  $link=$row['link'];
  $msgid=$row['msgid'];
   
  if (str_contains($row['mime_type'], 'audio')) { $performer=" | ".htmlspecialchars($row['message']); } else $performer="";

  if ($row['size']==-1) { $fsize=$row['filename']; } else $fsize=round($row['size'] / 1024 / 1024)." MB".$performer;

  $fname=$row['filename'];
  
  if (array_key_exists("redirectout_tochannel", $channelInfoNew[$o_channelInfoKey]) && $channelInfoNew[$o_channelInfoKey]["redirectout"] != -1 && $current == -1 ) { 
   switch ($channelInfoNew[$o_channelInfoKey]["redirectout_mode"]) {
	case "link": $returnMsgRevert[]=$dim."<a href=\"".$link."\">".$text."</a><br><code>".$fsize."</code><br>"; 
	break;
	case "id": 
               if ($topic==strtolower(substr($globalsettings["request"]["requestcommand"], 0, -1).":#getfile" )) { 
                $rightuserout=usr_managment($infoarray["channelid"], "userid", $infoarray["userid"])[$infoarray["userid"]]["role"];
                if ($rightuserout == "creator" || $rightuserout == "admin") {
				 redirect_getfile($o_channelInfoKey, $msgid, $infoarray["topicid"], array()); 
				 $returnMsgRevert[]=$dim.$text."<br>".$fsize."<br>";
     			} else { 
				 $returnMsgRevert[]=$dim.$text."<br><code>".$globalsettings["request"]["requestcommand"]."#getfile ".$msgid."</code><br>".$fsize."<br>"; 
			    } // if ($rightuserout == "creator" || $rightuserout == "admin") 
               } else {
				 $returnMsgRevert[]=$dim.$text."<br><code>".$globalsettings["request"]["requestcommand"]."#getfile ".$msgid."</code><br>".$fsize."<br>"; 
			   } // if ($topic==strtolower("#"+$globalsettings["request"]["requestcommand"]+":#getfile" )) 	
	break;
   } // switch ($channelInfoNew[$o_channelInfoKey]["redirectout_mode"]) 
  } else $returnMsgRevert[]=$dim."<a href=\"".$link."\">".$text."</a><br><code>".$fsize."</code><br>"; // if ($channelInfoNew[$o_channelInfoKey]["redirectout"] != -1 && $current == -1 )
 } // while ($row = pg_fetch_array($result)) 
 $returnMsg[0]="TOCHAN";
  for ($i=count($returnMsgRevert)-1;$i>=0; $i--) {
   $returnMsg[1].=$returnMsgRevert[$i];
 }
 return $returnMsg;
} // function end