<?php
### Verzeichnisse nach src/m3makefile,v durchsuchen
class dirlist {
 function listdir($dir) {
  global $flist,$fcut;
  if (is_readable($dir))
  {$handle=opendir($dir);
   while ($file = readdir($handle)) {
     if ($file != ".." && $file != ".")
       {
        if (is_dir($dir.'/'.$file)) 
         {
           $newins = new dirlist; 
           $newins->listdir($dir.'/'.$file);
         }
        else {if (strpos($dir.':'.$file,'/src:m3makefile,v') > 0)
                 { $dire = substr($dir,$fcut,strlen($dir)-4-$fcut);
                   $name = substr($dire,strrpos($dire,'/')+1,strlen($dire)-strrpos($dire,'/')-1);
                   $flist[$dire] = strtolower($name);};
             }
       }
   }
   closedir($handle);
  }
 }
}

### Dateigroesse in KB umwandeln
function fsize($size)
{
  $wert = (string) Floor($size / 102.4); if ($size<1024) {$wert="0".$wert;};
  return substr($wert,0,strlen($wert)-1).",".$wert[strlen($wert)-1]."&nbsp;kB";
}

### Dateiliste aller Paketdateien erstellen
class filelist {
 function listfiles($dir) {
  global $fcut,$totsize,$totfiles,$mdir;
  if (is_readable($dir))
  {$handle=opendir($dir);
   while ($file = readdir($handle)) {
     if ($file != ".." && $file != ".")
       {
        if (is_dir($dir.'/'.$file)) 
         {
           $newins = new filelist; 
           $newins->listfiles($dir.'/'.$file);
         }
        else { $name = substr($dir."/".$file,$fcut,strlen($dir."/".$file)-$fcut);
               if (is_readable($mdir."/".$name)) {echo"<tr><td align=\"right\">&nbsp;".fsize(filesize($mdir."/".$name))."&nbsp;</td><td>".$name."</td></tr>\n"; $totsize+=filesize($mdir."/".$name); $totfiles++;};};
       }
   }
   closedir($handle);
  }
 }
}

### HTML-Header ausgeben
function head() {
global $HTTP_USER_AGENT;
if (preg_match("/Win|MSIE/", $HTTP_USER_AGENT)) {$size1="10"; }
 else {$size1="12"; };
if (preg_match("/Opera/", $HTTP_USER_AGENT)) {$size1="12"; };

echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
    <title>Download CM3 packages</title>
   <link rel="stylesheet" type="text/css" href="style/elego_style.css">  
    <style type="text/css">
      <!--
      #sans {font-family:"Helvetica","Arial","Geneva","Swiss","SunSans-Regular","Sans Serif","Sans"; }

      #roman {font-family:"Times","Times New Roman","Serif"; }
      #black {color:black;}
      #blue {color:#0033cc;}
      .tab { font-size:'.$size1.'pt; color:#000000; }
      .err { color:#FF0000; }
      .colm { color:#000066; }
      .colf { color:#BB0000; }
      h2 { font-family: \'Lucida Sans Unicode\', Tahoma, Lucida, sans-serif ;
      font-size  : .98em ;
      background : #FFFFFF ;
      color      : #0077FF;
      text-align : center }
      h1,h3,h4,td,li {
      font-family:"Helvetica","Arial","Geneva","Swiss","SunSans-Regular","Sans Serif","Sans"; 
      color:black;
      a,font {
      font-family:"Helvetica","Arial","Geneva","Swiss","SunSans-Regular","Sans Serif","Sans"; 
      }
      }
      -->
    </style>
    <meta name="robots" content="noindex">
    <meta name="author" content="Jonas Hoge / Berlin">
  </head>'."\n";
  $fn = BODYPATH."/right-top-body-en.php";
  $alternativeback='<a href="m3dwnld.php">Back to M3 download</a>';
  $title = "";
  if (is_readable($fn)) { include($fn); };
}  

### HTML-Header fuer Dateidownload ausgeben
function download($filename,$cont) {

 global $HTTP_USER_AGENT;

 header("Pragma: no-cache");// HTTP/1.0
 header("Cache-Control: no-cache, must-revalidate");// HTTP/1.1
 header("Content-Type: ".$cont);
 if(preg_match("/MSIE 5.5/", $HTTP_USER_AGENT)) {
         $header = "Content-Disposition: filename=".$filename;
 }else {
         $header = "Content-Disposition: attachment; filename=".$filename;
 }

 header($header);
 header("Content-Transfer-Encoding: binary\n");
}

### Hinweis oder Fehlermeldung ausgeben
function msgout($message, $typ) {
  if ($typ=="f") {
    echo '<p><h1 class="err" align="center">Error!</h1></p><br>';};
 echo '<p class="col'.$typ.'" align="center">'.$message.'</p>';
}

### Sicherheit: Pruefen ob angeforderte Datei in der Liste vorhanden
function securitytest()
{
 global $flist,$dl;
 $dirli = new dirlist;
 $dirli->listdir(MAINDIR);
 $chkok=1;
 for ($i=0; $i<count($dl); $i++)
  {
   $exi=0;
   reset($flist);
   while (($key = key($flist))&&($exi==0)) 
   {
    next($flist);
    if ($key==$dl[$i]) {$exi=1;};
    }
   if ($exi==0) {$chkok=0;};
  }
 return $chkok;
}

### Verhindern das Pakete, welche sich in Unterverzeichnissen anderer Pakete
### befinden doppelt gepackt werden
function subdirfilter()
{
  global $dl;
  $counter=0;
  while ($counter < count($dl))
    {
      $counter2=0; $sout=0;
      while (($counter2 < count($dl))&&($sout==0))
        {
         if ((strlen($dl[$counter]) > strlen($dl[$counter2]))&&(strpos($dl[$counter],$dl[$counter2])===0)) {if ($dl[$counter][strlen($dl[$counter2])]=="/") {$sout=1;};};
         $counter2++;
        }
      if ($sout==1) {array_splice($dl,$counter,1);}
      else {$counter++;};
    }
}


### Ausgabefunktion zu fileconttotable
function filecontout()
{
  global $clist;
  for ($i=0; $i<count($clist); $i++)
    {echo $clist[$i];};
}

### Eintraege einer Textdatei als Tabelle oder Mehrfachauswahl konvertieren
function fileconttotable($rfiles,$prestr,$afterstr)
{
 global $rev, $clist;
  $fp = fopen(REVDIR."/".$rfiles, "r");
  while (!feof($fp)) {
    $buf = chop(fgets($fp, 256)); 
    if ($buf!="") 
     {if ($rev!="")
       {
        if ($buf==$rev) {$sel=" selected"; $rev="";} else {$sel="";}; 
        $clist[]="<option".$sel.">".$buf."</option>\n";
       }
      else
       {
        $clist[]=$prestr.$buf.$afterstr;
       };
     };
  };
  fclose($fp);
}

##### Hauptprogramm #####

$atype="gz";
$opt="source";
$sort="";
$dl="";
$dlsubmit=0;
$rst=0;
$datumrev="";
$datum="";
$rev="";
$modula="CM3";

### Querystring-Verarbeitung
if (isset($QUERY_STRING))
   {if ($QUERY_STRING=="dist=PM3") {$modula="PM3";};};
if (isset($HTTP_POST_VARS))
   {for (reset($HTTP_POST_VARS); $key = key($HTTP_POST_VARS); next($HTTP_POST_VARS))
    {
     $valu=array($key,$HTTP_POST_VARS[$key]);
     $val2=$key."=".$HTTP_POST_VARS[$key];
     if ($val2=="atype=bz2") {$atype="bz2";}
     elseif ($val2=="atype=zip") {$atype="zip";}
     elseif ($val2=="option=cvs") {$opt="cvs";}
     elseif ($val2=="sort=Name") {$sort="name";}
     elseif ($val2=="dist=PM3") {$modula="PM3";}
     elseif ($val2=="submit=Download selected packages") {$dlsubmit=1;}
     elseif ($val2=="submit=File list of selected packages") {$dlsubmit=2;}
#     elseif ($val2=="submit=List all revisions") {$dlsubmit=3; }
     else
     {
      if (($valu[0]=="revi") or (($valu[0]=="revi2")&&($rev===""))) {$rev=$valu[1];};
      if (($valu[0]=="date")&&(strlen(trim($valu[1]))>0)) {$datumrev.=" -D \"".EscapeShellCmd(trim($valu[1]))."\""; $datum=$valu[1];}
      elseif ($valu[1]=="Reset selection")
        {$rst=1;
         if ($valu[0]=="resetname") {$sort="name";}}
      elseif ($valu[0]=="Downld") {$dl=$valu[1];};
     };
    }
   }
    if ($rst==1) {$dl=""; $atype="gz"; $opt="source"; $datum=""; $rev="";};
    if ($dlsubmit==3) {$opt="source";};
    if (strlen(trim($rev))>0) {$datumrev.=" -r \"".EscapeShellCmd(trim($rev))."\"";}
###

$ch[$atype]="checked";
$che[$opt]="checked";

#### Verzeichnisdefinition
if ($modula=="CM3")
{
define("MAINDIR", "/usr/cvs/cm3");
define("MAINDIRCVS", "/usr/cvs");
define("SUBDIRCVS", "cm3");
$rfiles=array("cm3_tags");
}
else
{
define("MAINDIR", "/usr/cvs/pm3/m3/pm3");
define("MAINDIRCVS", "/usr/cvs/pm3");
define("SUBDIRCVS", "m3/pm3");
$rfiles=array("./pm3/pm3_tags");
};

define("BODYPATH", ".");
define("REVDIR", ".");
ini_set(max_execution_time,"36000"); #evtl. mehr Zeit
$fcut=1+strlen(MAINDIR);

#$rfiles2=array("all_tags_3", "all_tags_1", "all_tags_2", "all_tags_4");
#$rnames=array("devel", "release", "branch", "other");

if ($dlsubmit == 0) {
 $dirli = new dirlist;
 $dirli->listdir(MAINDIR);

# $rfiles=array("all_tags_1", "all_tags_2");

### Haupttabelle ausgeben
head();
 echo "<br><h2>".$modula." package download</h2>\n";
 include("pkg-download-txt-en.php");

echo '<form action="dlpckg.php" method=post>
&nbsp;<br>
<table class="blue" border="2" cellpadding="2" cellspacing="2" align="center" width="99%">
 <tr>
  <td bgcolor="#DDFFDD">Sort:</td>
  <td bgcolor="#DDDDFF">Archive type:</td>
  <td bgcolor="#FFDDDD"">Option:</td>
 </tr>
 <tr>
  <td bgcolor="#DDFFDD" align="center"><input type="submit" value="Name" name="sort"><br>
      <input type="submit" value="Path" name="sort"></td>
  <td bgcolor="#DDDDFF"><input type=radio name="atype" '.$ch['gz'].' value="gz">tar.gz<br>
      <input type=radio name="atype" '.$ch['bz2'].' value="bz2">tar.bz2<br>
      <input type=radio name="atype" '.$ch['zip'].' value="zip">ZIP</td>
  <td bgcolor="#FFDDDD"><input type=radio name="option" '.$che['source'].' value="source">Source<br>
      <input type=radio name="option" '.$che['cvs'].' value="cvs">CVS archive<br>
 <tr>
</table>
<hr class="blue">
<table class="tab" bgcolor="#e8f0ff" xbgcolor="black" border="1" cellpadding="2" cellspacing="2" align="center" width="99%">
  <tr bgcolor="#d4e4f0">
   <td><u><b>Packagename:</b></u></td>
   <td><u><b>Path:</b></u></td>
   <td>D/L?</td>
  </tr>';

 if ($sort == "name") {asort($flist);}
 else {ksort($flist);};

 for (reset($flist); $key = key($flist); next($flist))
 {
  $echk="";
  for ($i=0; $i<count($dl); $i++)
  { if ($dl[$i]==$key) {$echk="checked";}; }
  $name = substr($key,strrpos($key,'/')+1,strlen($key)-strrpos($key,'/')-1);
  $brstr = str_replace("/"," / ",$key);
  echo "<tr><td>".$name."</td><td>".$brstr."</td><td align=\"center\"><input type=\"checkbox\" ".$echk." value=\"".$key."\" name=\"Downld[]\"></td></tr>\n";
 }
 echo "</table><hr class=\"blue\">
      <div align=\"center\">\n
 <table border=\"0\">
 <tr>
  <td colspan=\"2\" align=\"center\">\n";
 if (($dl == "")&&($datumrev == ""))
   {echo"       <input type=\"reset\" value=\"Reset selection\">";}
 else
   {echo"       <input type=\"submit\" value=\"Reset selection\" name=\"reset".$sort."\">";};
echo"  </td>
 </tr>
 <tr>
  <td colspan=\"2\">&nbsp;<br>
       Optional CVS-parameters (only for source download):<br>&nbsp;  
  </td>
 </tr>
 <tr>
  <td>Revision:</td> 
  <td><select name=\"revi\" size=1>
       <option> </option>";
 $clist="";
 fileconttotable($rfiles[0],"<option>","</option>\n");
#fileconttotable($rfiles[1],"<option>","</option>\n");
 filecontout();
echo "      </select></td>
 </tr>
 <tr>
  <td>or<br>&nbsp;</td>
  <td>  <input name=\"revi2\" value=\"".$rev."\" size=28 maxlength=40><br>&nbsp;</td>
 </tr>
 <tr>
 <td>Date:</td>
 <td> <input name=\"date\" value=\"".$datum."\"size=20 maxlength=20>(YYYY-MM-DD)</td>
 </tr>
 <tr>
  <td colspan=\"2\" align=\"center\">&nbsp;<br>
       <input type=\"submit\" value=\"File list of selected packages\" name=\"submit\">\n";
##     <input type=\"submit\" name=\"submit\" value=\"List all revisions\">   
echo "  </td>
 </tr>
 <tr>
  <td colspan=\"2\" align=\"center\">&nbsp;<br>
       <input type=\"submit\" name=\"submit\" value=\"Download selected packages\"><br>&nbsp;      
  </td>
 </tr> 
 <tr>
  <td colspan=\"2\">\n";
 msgout("Note: If you have selected many and/or large packages it may take some minutes to complete your request.", "m");
echo "  </td>
 </tr>
      </table></div>
      <input type=\"hidden\" name=\"dist\" value=\"".$modula."\">
      </form>";
}
elseif ($dlsubmit<3) {
  ### Pruefen, Packen, Downloaden
  if ($dl == "") {head(); msgout("Nothing selected.", "f"); $dlsubmit=0;}
  else
  {
   if ($atype != "zip") {$atype="tar.".$atype;}
   $cdl=0;
   for ($i=0; $i<count($dl); $i++)
     { if (is_dir(MAINDIR."/".$dl[$i])) {$cdl++;}; }; 
   if ($cdl<count($dl)) {head(); msgout("One or more requested packages could not be found.", "f"); $dlsubmit=0;}
   else 
  {
       {if (securitytest()==0) {head(); msgout("Illegal request.<br>Only listed packages could be requested.", "f"); $dlsubmit=0;}
        else
          {$pathtopack=""; subdirfilter();
          if ($opt!="cvs") {$j=SUBDIRCVS."/";} else {$j="";};
         for ($i=0; $i<count($dl); $i++)
             {$pathtopack.=$j.$dl[$i]." ";};
         if (count($dl)==1) {$name = 'm3_'.substr($pathtopack,strrpos($pathtopack,'/')+1,strlen($pathtopack)-strrpos($pathtopack,'/')-2)."_".$opt;}
         else {$name="m3_package_".$opt;};
         if ($opt=="cvs")
          {
            $mdir=MAINDIR;
            $sta=0;
          }
         else
          {
            ### Bei der Auswahl "Source" einen CVS-Checkout durchfuehren
            $tmpdir=tempnam( "/tmp", "cvscheckout_tmp" );
            if (is_readable($tmpdir)) {unlink($tmpdir);};
            mkdir ($tmpdir, 0750);           
            $error=exec("cvschkout ".$tmpdir." ".MAINDIRCVS." ".$datumrev." ".$pathtopack,$dummy,$sta);
            $mdir=$tmpdir."/".SUBDIRCVS;
            if ($dlsubmit!=3) {$pathtopack=".";};
          }
           if ($sta!=0) {head(); msgout("CVS could not complete your request:<br>".$error, "f"); $dlsubmit=0;}
           else
             {
             if ($atype=="tar.gz") {$execstr='tar --gzip -cf - --block-size 1 -C '.$mdir.' '.$pathtopack; $mimet="x-gzip";}
             if ($atype=="tar.bz2") {$execstr='tar --bzip2 -cf - --block-size 1 -C '.$mdir.' '.$pathtopack; $mimet="x-bzip2";}
             if ($atype=="zip") {$execstr="zippack ".$mdir." ".$pathtopack; $mimet="x-zip-compressed";}
     if ($dlsubmit==1)
         {
           ### Downloaden
           download($name.".".$atype,"application/".$mimet);
           passthru($execstr);
         }
    else {   
           ### Nur Liste ausgeben
              head();
             $fcut=1+strlen($mdir);
             $totfilesall=0; $totsizeall=0;
             for ($i=0; $i<count($dl); $i++)
                 {
                   echo "<div align=\"center\"><h3><u>Package:</u> <i>".$dl[$i]."</i></h3>";
                   echo "<table class=\"tab\" border=\"1\"><tr><td align=\"center\">Size</td><td>File:</td></tr>\n";
                   $totsize=0; $totfiles=0;
                  $fileli = new filelist;
                  $fileli->listfiles($mdir."/".$dl[$i]);                  
                  echo "</table>\n";
                  echo $totfiles." files; ".fsize($totsize)." total (uncompressed).<br>&nbsp;</div>\n";
                  $totfilesall+=$totfiles; $totsizeall+=$totsize;
                 };
                 echo "<p align=\"center\"><b>All selected packages: ".$totfilesall." files; ".fsize($totsizeall)." total (uncompressed).</b></p>\n";
             }
         };
         #if ($opt!="cvs") {exec ("rm -dfr ".$tmpdir);};
           if ($opt!="cvs") 
            {$fp = fopen($tmpdir."/.transfer-done", "w");
             fclose($fp);};
       }
     }
   }
  }
}
else
{
  ### Anzeige aller Revisionen
  echo "Not enabled yet.";
#  head();
#  $rev="";
#  echo "<div align=\"center\"><table border=\"0\"><tr><td valign=\"top\">\n";
#  $clist="";
#for ($i=0; $i<4; $i++)
#  {
#   $clist[]="<h3><u>".$rnames[$i].":</u></h3>\n";
#   $clist[]="<table class=\"tab\" border=\"1\" width=\"100%\">\n";
#   fileconttotable($rfiles2[$i],"<tr><td>","</td></tr>\n");
#   $clist[]="</table>&nbsp;<br>\n";
#  };
#  $r=round((count($clist)/2))+1;
#for ($i=0; $i<count($clist); $i++)
#  {
#  if (strpos($clist[$i],"<h3><u>")===0)
#  {$rnames=substr($clist[$i],7,strpos($clist[$i],"</u></h3>")-7);};
#  if ($i==$r) {echo "</table>&nbsp;<br>\n</td><td width=\"50\">&nbsp;</td><td valign=\"top\"><h3><u>".$rnames."</u></h3>\n<table class=\"tab\" border=\"1\" width=\"100%\">\n";};
#  echo $clist[$i];
#  };
#  echo "</td></tr></table></div>\n";
}
if ($dlsubmit!=1) {
  $fn = BODYPATH."/right-bottom-body.php";
  if (is_readable($fn)) { find_pics_top($pics); include($fn); };
  echo '</html>';
};
?>
