<?php

function realForwardCount() {
 global $toForward;
 $c=0;
 foreach ($toForward as $f) { 
  if ($f["album"] == -1) $type="video";
  if ($f["album"] != -1) $type="album";
  if ($type=="video" && $f["cover"] != -1 ) $c++;
  $c++;
 }
 return $c;
} // function end

function asearch($key, $array) { // array_search do not work :/ ???
 for ($c=0;$c<=count($array)-1; $c++) if ($array[$c]==$key) return true;
 return false;
} // function end

function fwdStepperJob() {
 global $floodwait, $MadelineProto, $channelInfoNew, $toForward, $syncPrintMsg, $runtimeForwardCounter, $runtimeForwardCalls, $interval, $globalsettings, $startTime, $floodchallange, $forwardstopmsg, $maxforwards, $floodtimer, $alltimeforwards, $shm;

 $forward=array();

/* if ($floodwait != -1) {
  $runtime=dhms(time() - $floodchallange["floodtimer"], 2);
  $acthour=$runtime["day"] * 24 + $runtime["hour"];
  shm_put_var($shm, 3, array(0=>0, 1=> "forwards act. hour", 2=> $floodchallange["acthour-".$acthour]["forwardcount"])); 
 } // if ($floodwait != -1)

Exception:       Undefined array key "acthour-0" in fwdStepperJob.inc.php:28
Exception:       \danog\MadelineProto\Exception: Undefined array key "acthour-0" in /smb-mount/propapanda/inc/fwdStepperJob.inc.php:28

*grummel*
if isset - array key, set arraykey to 0 

channelReader, drop table, rename lock_ table... erstpart man sich das abgleichen...

START TRANSACTION;

 this will block until the last concurrent transaction
   that uses the table is done 
DROP TABLE tab;

ALTER TABLE tab_new RENAME TO tab;

COMMIT;

aus chan_ alles was nicht in lock_ ist, dann chan_ dropen und _lock zu chan_ renamen! **indexes testen -.- 


*/


 $floodwait=-1; // here shm if != -1 
  
  if (count($toForward) != 0) {

   $fakeys=array_keys($toForward); // get first key @ $toForward array
//   print_r($fakeys);
//   print_r($toForward);
   $fromto=$toForward[$fakeys[0]]["from"].$toForward[$fakeys[0]]["to"].$toForward[$fakeys[0]]["topic"]; // build selector

//   echo "fromto: ".$fromto."\n";
  
   $from=$toForward[$fakeys[0]]["from"];
//  echo "from: ".$from."\n";
  
   $to=$toForward[$fakeys[0]]["to"]; 
//  echo "to: ".$to."\n";
   $to_topic=$toForward[$fakeys[0]]["topic"]; 
  
   $totmp=explode("#",$to);
   if (array_key_exists("1", $totmp)) { $to=$totmp[0]; exit; }  // exit-> check if # in to:

   // forward queue bereinigen, wenn channels.conf angepasst wurde
   $fromChannelName=$channelInfoNew[$from]["name"];
   $toChannelName=$toForward[$fakeys[0]]["tochanname"];
//   echo $fromChannelName." -> ".$toChannelName." ".$channelInfoNew[$from]["redirectout"]."\n"; 
   

   if (mb_strlen($fromChannelName) >= 20) $fromChannelName=mb_substr($fromChannelName,0,20)."...";
   if (mb_strlen($toChannelName) >= 20) $toChannelName=mb_substr($toChannelName,0,20)."...";
 
   logger("job: fwdStepper - all forwards in queue: ".realForwardCount());
   logger("job: fwdStepper - actually forwards from: [".$fromChannelName."] to: [".$toChannelName."]");

   $fwdmsg=""; // reset fwdmsg 
   foreach($toForward as $f) { 

    if ($f["from"].$f["to"].$f["topic"] == $fromto) { // selector
     if ($f["album"] == -1) $type="video";
     if ($f["album"] != -1) $type="album";

     switch($type) {
      case "video": $filetargetcheck=syncChecktargetChannel($f["width"], $f["height"], $f["runtime"], $f["filedate"], $f["filesize"], $to);
                    if ($filetargetcheck == -1) {
                     if ($f["cover"] != -1 ) {
                      $fwdmsg.=$f["text"]." [".$f["cover"]."] -cover\n";
                      logger(mb_sprintf("job: fwdStepper - %-54s %s - from [%s][%s] to [%s]", $f["text"], "cover", $fromChannelName, $f["cover"], $toChannelName)); 
                       $forward[]=$f["cover"]; // cover
                     } // if ($f["cover"] != -1 )

                     $fwdmsg.=$f["width"]."x".$f["height"]." - ".$f["text"]." [".$f["msgid"]."] -video\n";
                     logger(mb_sprintf("job: fwdStepper - %-54s %s - from [%s][%s] to [%s]", $f["text"], $type, $fromChannelName, $f["msgid"], $toChannelName)); 
                     $forward[]=$f["msgid"]; // video

                     $toForwardarraykey=buildtoForwardKey($f["from"], $f["to"], $f["msgid"], $to_topic);   
                     unset($toForward[$toForwardarraykey]); // unset array element
                    } else {
                     logger(mb_sprintf("job: fwdStepper - %-54s %s - from: [%s(%s)] already [%sx] @ [%s]",$f['text'], $type, $fromChannelName, $f["msgid"], $filetargetcheck, $toChannelName));

                     $toForwardarraykey=buildtoForwardKey($f["from"], $f["to"], $f["msgid"], $to_topic);   
                     unset($toForward[$toForwardarraykey]); // unset array element
                     $sql="delete from forwardqueue where forwardkey='".pg_escape_string($globalsettings["db"]["pg_conn"], $toForwardarraykey)."'"; // delete from db where file already @ chan
                     pg_query($globalsettings["db"]["pg_conn"], $sql);
                    } // if ($filetargetcheck == -1) - else
      break; 
      case "album": 
                     foreach($toForward as $ap) {
                      if ($f["from"].$f["to"] == $ap["from"].$ap["to"] && $f["album"] == $ap["album"]) {
                        if ($ap["cover"] == "cover") {$albumtype="album-cover"; } else $albumtype="album-video";
                        if ($ap["cover"] != "cover") {
                         $filetargetcheck=syncChecktargetChannel($ap["width"], $ap["height"], $ap["runtime"], $ap["filedate"], $ap["filesize"], $ap["to"]); 
                         $filecounter=0;
                         if ($filetargetcheck == -1) {
                          $filecounter++;
                        } else logger(mb_sprintf("job: fwdStepper - %-54s %s - from [%s][%s] already [%sx] @ [%s]", $ap["text"], $albumtype, $fromChannelName, $ap["msgid"], $filetargetcheck, $toChannelName));  // if ($filetargetcheck == -1) - else
                       } // if ($ap["cover"] != "cover") 
                      } // if ($ap["from"].$ap["to"] == $f["from"].$f["to"] && $ap["album"] == $f["album"]) 
                     } // foreach($toForwards as $ap)

                     if (!isset($filecounter)) $filecounter=0;
                     if ($filecounter == 0) { // all files already in target channel
                      foreach($toForward as $ap) {
                       if ($f["from"].$f["to"].$f["topic"] == $ap["from"].$ap["to"].$to_topic && $f["album"] == $ap["album"]) {

                        $aparraykey=buildtoForwardKey($ap["from"], $ap["to"], $ap["msgid"], $to_topic);
                        unset($toForward[$aparraykey]); // unset all album messages including covers

                        $sql="delete from forwardqueue where forwardkey='".pg_escape_string($globalsettings["db"]["pg_conn"], $aparraykey)."'"; // delete from db where file already @ chan
                        pg_query($globalsettings["db"]["pg_conn"], $sql);
                       } // if ($ap["from"].$ap["to"] == $f["from"].$f["to"] && $ap["album"] == $f["album"]) 
                      } // foreach($toForwards as $ap)
                     } // if ($filecounter == 0) 

                     if ($filecounter != 0) { // one or more files not in target channel
                      foreach($toForward as $ap) {
                       if ($f["from"].$f["to"].$f["topic"] == $ap["from"].$ap["to"].$to_topic && $f["album"] == $ap["album"]) {
                        if ($ap["cover"] == "cover") {$albumtype="album-cover"; } else $albumtype="album-video";
                        if (!asearch($ap["msgid"], $forward)) { // if msgid not in $forward array

                         if ($ap["cover"] == "cover") { $fwdmsg.=$ap["text"]." [".$ap["msgid"]."] -".$albumtype."\n"; } else $fwdmsg.=$ap["width"]."x".$ap["height"]." - ".$ap["text"]." [".$ap["msgid"]."] -".$albumtype."\n";

                         logger(mb_sprintf("job: fwdStepper - %-54s %s - from [%s][%s] to [%s]", $ap["text"], $albumtype, $fromChannelName, $ap["msgid"], $toChannelName)); 
                         $forward[]=$ap["msgid"];

                         $aparraykey=buildtoForwardKey($ap["from"], $ap["to"], $ap["msgid"], $to_topic);
                         unset($toForward[$aparraykey]); // unset album messages 
                        } // if (!asearch($ap["msgid"], $forward))
                       } // if ($ap["from"].$ap["to"] == $f["from"].$f["to"] && $ap["album"] == $f["album"]) 
                      } // foreach($toForwards as $ap)
                     } // if ($filecounter != 0) 
                 
      break;
     } // switch($type) 
    } // if ($f["from"].$f["to"].$f["topic"] == $fromto)
    if (count($forward) >=40 ) break; // prevent rpc busy worker (40)
   } // foreach($toForward as $f)

   if (count($forward) != 0) {
 
    $runtimeForwardCounter+=count($forward); // little runtime statistics
    $runtimeForwardCalls++; // steps 
    $alltimeforwards+=count($forward);
	
    
    $sql="update settings set value = '".pg_escape_string($globalsettings["db"]["pg_conn"], $alltimeforwards)."' where variable='".pg_escape_string($globalsettings["db"]["pg_conn"], "alltimeforwards")."';";
    pg_query($globalsettings["db"]["pg_conn"], $sql);

    $sql="select value from settings where variable='".pg_escape_string($globalsettings["db"]["pg_conn"], "alltimeforwards")."';";
    $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
    $numrows=pg_num_rows($result);
    if ($numrows != 0) {
     while ($row = pg_fetch_array($result)) $alltimeforwards=$row["value"];
    } // if ($numrows != 0) 

    // check maxforwards per hour
    $currentTime=time();
    $runtime=dhms($currentTime - $floodchallange["floodtimer"], 2);
      
    $acthour=$runtime["day"] * 24 + $runtime["hour"];

    if (!isset($floodchallange["forwardcount"])) $floodchallange["forwardcount"]=0;
    if (!isset($floodchallange["acthour"])) $floodchallange["acthour"]=0;
    if (!isset($floodchallange["floodtimerreset"])) $floodchallange["floodtimerreset"]=-1;

    $floodchallange["acthour"]=$acthour;

    if ($floodchallange["floodtimerreset"]==1) {
     foreach (array_keys($floodchallange) as $k) {
      if (explode("-",$k)[0]=="acthour") unset($floodchallange[$k]);
     } // foreach (array_keys($floodchallange) as $k) 
     $floodchallange["floodtimerreset"]=-1;
    }  // if ($floodchallange["floodtimerreset"]==1) 
    
    if (!isset($floodchallange["acthour-".$acthour]["forwardcount"])) $floodchallange["acthour-".$acthour]["forwardcount"]=0;
    if (!isset($floodchallange["acthour-".$acthour]["forwardstep"])) $floodchallange["acthour-".$acthour]["forwardstep"]=0;
    if (!isset($floodchallange["acthour-".$acthour]["forwardbrake"])) $floodchallange["acthour-".$acthour]["forwardbrake"]=0;
    if (!isset($floodchallange["acthour-".$acthour]["floodwait"])) $floodchallange["acthour-".$acthour]["floodwait"]=0;

    $floodchallange["forwardcount"]+=count($forward);
    $floodchallange["acthour-".$acthour]["forwardcount"]+=count($forward);
    $floodchallange["acthour-".$acthour]["forwardstep"]++;
    
//    print_r($floodchallange); // debug

/*

*/

    if ($floodchallange["acthour-".$acthour]["forwardcount"] >= $maxforwards) {
     
     $floodchallange["acthour-".$acthour]["forwardbrake"]=1;
     $floodwait=(time()+((60 - $runtime["min"]) * 60)) + 120; // + 2 min overtime
     logger("job: fwdstepper - set forward brake to: ".$floodwait);
     $interval["fwdStepper"]['lastruntime']=$floodwait;
     $forwardstopmsg="forward brake";

     $sql="update settings set value = '".pg_escape_string($globalsettings["db"]["pg_conn"], $floodwait)."' where variable='".pg_escape_string($globalsettings["db"]["pg_conn"], "floodwait")."';";
     pg_query($globalsettings["db"]["pg_conn"], $sql);

     $sql="update settings set value = '".pg_escape_string($globalsettings["db"]["pg_conn"], $forwardstopmsg)."' where variable='".pg_escape_string($globalsettings["db"]["pg_conn"], "forwardstopmsg")."';";
     pg_query($globalsettings["db"]["pg_conn"], $sql);
    } // if ($floodchallange[$acthour]["forwardcount"] >= $maxforwards)  


    logger("job: fwdstepper - acthour: ".$acthour.", forwards: ".$floodchallange["acthour-".$acthour]["forwardcount"].", actmin: ".$runtime["min"]);

    logger("job: fwdStepper - ".$runtimeForwardCounter." Forwards in ".$runtimeForwardCalls." steps ...");

    $newtime=-1;
    switch($to_topic) {
      case "-1":
                made("messages", "forwardMessages", array("background" => true, "drop_author" => true, "from_peer" => $channelInfoNew[$from]["peerid"], "to_peer" => "-100".$to, "id" => $forward));
      break;
      default: 
                made("messages", "forwardMessages", array("background" => true, "drop_author" => true, "from_peer" => $channelInfoNew[$from]["peerid"], "to_peer" => "-100".$to, "id" => $forward, "top_msg_id" => $to_topic));
    } // switch($to_topic)

    // get target channel uptodate, has target a from section @ channels.conf
    foreach(array_keys($channelInfoNew) as $channelInfoKey) {
     if ($channelInfoNew[$channelInfoKey]["chanid"] == $to) {
      $data=getLastMessages($channelInfoKey, "1", false); 
      if ($data != false) insertData(parseData($data), $channelInfoKey);
      break;
     } // if ($channelInfoNew[$channelInfoKey]["chanid"] == $to)
    } // foreach(array_keys($channelInfoNew) as $channelInfoKey) 

   } // if (count($forward) != 0) 
   logger("job: fwdStepper - forwards in queue: ".realForwardCount());
  } // if (count($toForward) != 0)
} // function end


// these inc contains:
//
// fwdStepperJob()
// realForwardCount()
// asearch()
