<?PHP
/*********************************************************************************************/
/* NPDS V - SavemySQL_Databases 0.5     (20040611)                                           */
/* based on SaveDB addon by Thomas Rudant (thomas.rudant@grunk.net)                          */
/* originally inspired by the build_dump librarie of phpMyAdmin (http://www.phpmyadmin.org)  */
/* Adapted by : M. PASCAL aKa EBH (plan.net@free.fr)                                         */
/*                                                                                           */
/* This program is free software. You can redistribute it and/or modify it under the terms   */
/* of the GNU General Public License as published by the Free Software Foundation either     */
/* version 2 of the license.                                                                 */
/*                                                                                           */
/* ver 0.5 : Hexa, ajout du decoupage par tables/lignes suivant parametre $savemysql_mode    */
/*           $savemysql_mode:                                                                */
/*            - 1 ou autres => fonctionnement classique                                      */
/*            - 2 => fnct table/table, tables non scindées ($savemysql_size)                 */
/*            - 3 => fnct table/table, lignes/lignes, tables scindées ($savemysql_size)      */
/*           Ajout d'une conversion de chaine de carateres (PrepareString)                   */
/*                                                                                           */
/* ver 0.4c : externalisation de send_file et get_os dans lib/archive.php                    */
/*                                                                                           */
/* ver 0.4b : optimisation (non utilisation de la fonction 'ereg_replace')                   */
/*                                                                                           */
/* ver 0.4a : correction de l'instruction @header(Content-Type) en fonction de l'OS          */
/*                                                                                           */
/* ver 0.4 : compression automatique de l'archive (zip/gzip), adaptation à NPDS V            */
/*                                                                                           */
/* ver 0.3 : modification des instructions @header(*)                                        */
/*                                                                                           */
/* ver 0.2a : utilisation de HTML/CSS                                                        */
/*                                                                                           */
/* ver 0.2 : intégration des traductions aux fichiers de langues de NPDS                     */
/*                                                                                           */
/* ver 0.1 : adaptation de SaveDB                                                            */
/*                                                                                           */
/*********************************************************************************************/
function Access_Error () {
  if (file_exists("meta/meta.php"))
     include ("meta/meta.php");
  echo "<title>NPDS</title></head><body bgcolor=\"white\"><br /><p align=\"center\"><span style=\"font-size: 14px; font-family: Arial; font-weight: bold; color: red;\">";
  echo "Access Denied / Acc&egrave;s Refus&eacute;";
  if (cur_charset=="utf-8") echo" / &#x901A;&#x5165;&#x88AB;&#x5426;&#x8BA4;";
  echo "</span>";
  echo "<br /><br /><span style=\"font-size: 12px; font-family: Arial; font-weight: bold; color: black;\">NPDS - Portal System";
  echo "</span></p></body></html>";
  die();
}
if (!eregi("admin.php", $PHP_SELF)) { Access_Error(); }
include("lib/archive.php");
global $pdst; $pdst="0";

$result = mysql_query("SELECT radminsuper, name FROM authors WHERE aid='$aid'");
list($radminsuper, $name) = mysql_fetch_row($result);
if ($radminsuper != 1) {
   Access_Error();
} else {

   function PrepareString($a_string = '') {
      $search       = array('\\','\'',"\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required
      $replace      = array('\\\\','\\\'','\0', '\n', '\r', '\Z');

      return str_replace($search, $replace, $a_string);
   }
    
   function get_table_def($table) {
      global $dbname, $crlf, $crlf2;

      $k = 0;
      $result = mysql_query("SELECT * FROM $table limit 1");
      $count = mysql_num_fields($result);

      $schema_create = "";
      $schema_create .= "DROP TABLE IF EXISTS $table;$crlf";
      $schema_create .= "CREATE TABLE $table ($crlf";
      $result = mysql_query("SHOW FIELDS FROM $table");
      while($row = mysql_fetch_array($result))
      {
         $schema_create .= " $row[Field] $row[Type]";
         if(isset($row["Default"]) && (!empty($row["Default"]) || $row["Default"] == "0"))
         {
            $schema_create .= " DEFAULT '$row[Default]'";
         }
         if($row["Null"] != "YES")
         {
            $schema_create .= " NOT NULL";
         }
         if($row["Extra"] != "")
         {
            $schema_create .= " $row[Extra]";
         }
         if ($k < ($count - 1)) { $schema_create .= ",$crlf"; }
         $k++;
      }
      $result = mysql_query("SHOW KEYS FROM $table");
      while($row = mysql_fetch_array($result))
      {
         $kname = $row['Key_name'];
         if(($kname != "PRIMARY") && ($row['Non_unique'] == 0))
         {
            $kname="UNIQUE|$kname";
         }
         if(!isset($index[$kname]))
         {
            $index[$kname] = array();
         }
         $index[$kname][] = $row['Column_name'];
      }
      while(list($x, $columns) = @each($index))
      {
         $schema_create .= ",$crlf";
         if($x == "PRIMARY")
         {
            $schema_create .= "   PRIMARY KEY (".implode($columns, ", ").")";
         }
         elseif (substr($x,0,6) == "UNIQUE")
         {
            $schema_create .= "   UNIQUE ".substr($x,7)." (".implode($columns, ", ").")";
         }
         else
         {
            $schema_create .= "   KEY $x (".implode($columns, ", ").")";
         }
      }
      $schema_create .= "$crlf)";
      $schema_create = stripslashes($schema_create);
      $schema_create .= ";";
      mysql_free_result($result);
      return($schema_create);
   }


   function get_table_content($table)
   {
      global $dbname, $crlf, $crlf2;
      $table_list = "";
      $schema_insert = "";
      $result = mysql_query("SELECT * FROM $table");
      $count = mysql_num_fields($result);
      while($row = mysql_fetch_row($result))
      {
         $schema_insert .= "INSERT INTO $table VALUES (";
         for($j = 0; $j < $count; $j++)
         {
            if(!isset($row[$j]))
            {
               $schema_insert .= " NULL";
            }
            else
            if ($row[$j] != "")
            {
               $schema_insert .= " '".PrepareString($row[$j])."'";
            }
            else
            {
               $schema_insert .= " ''";
            }
            if($j < ($count -1))
            {
               $schema_insert .= ",";
            }
         }
         $schema_insert .= ");$crlf";
      }
      if($schema_insert != "")
      {
         $schema_insert = trim($schema_insert);
         return($schema_insert);
      }
   }

   function dbSave() {
      global $language, $dbname, $name, $MSos, $crlf;
      @set_time_limit(600);
      switch($language)
      {
         case english :
            $date_jour = date("m-d-Y");
            $date_op = date("mdy");
            break;
         default :
            $date_jour = date("d-m-Y");
            $date_op = date("dmy");
            break;
      }
      $filename = $dbname."-".$date_op;
      $tables = mysql_list_tables($dbname);
      $num_tables = mysql_num_rows($tables);
      if($num_tables == 0)
      {
         echo "&nbsp;".adm_translate("Aucune table n'a été trouvée")."\n";
      }
      else
      {
         $heure_jour = date("H:i");
         $data = "# ========================================================$crlf"
            ."# $crlf"
            ."# ".adm_translate("Sauvegarde de la base de données")." : ".$dbname." $crlf"
            ."# ".adm_translate("Effectuée le")." ".$date_jour." : ".$heure_jour." ".adm_translate("par")." ".$name." $crlf"
            ."# $crlf"
            ."# ========================================================$crlf";
         for($i = 0; $i < $num_tables; $i++)
         {
            $table = mysql_tablename($tables, $i);
            $data .= "$crlf"
               ."# --------------------------------------------------------$crlf"
               ."# $crlf"
               ."# ".adm_translate("Structure de la table")." '".$table."' $crlf"
               ."# $crlf$crlf";
            $data .= get_table_def($table)
               ."$crlf$crlf"
               ."# $crlf"
               ."# ".adm_translate("Contenu de la table")." '".$table."' $crlf"
               ."# $crlf$crlf";
            $data .= get_table_content($table)
               ."$crlf$crlf"
               ."# --------------------------------------------------------$crlf";
         }
      }
      send_file($data,$filename,"sql",$MSos);
   }

   function dbSave_tofile($repertoire, $linebyline=0, $savemysql_size=256) {
      global $language, $dbname, $name, $MSos, $crlf, $crlf2;

      @set_time_limit(600);
      switch($language)
      {
         case english :
            $date_jour = date("m-d-Y");
            $date_op = date("ymd");
            break;
         default :
            $date_jour = date("d-m-Y");
            $date_op = date("ymd");
            break;
      }
      $filename = $dbname."-".$date_op;
      $tables = mysql_list_tables($dbname);
      $num_tables = mysql_num_rows($tables);
      if($num_tables == 0)
      {
         echo "&nbsp;".adm_translate("Aucune table n'a été trouvée")."\n";
      }
      else
      {
         if ((!isset($repertoire)) or ($repertoire=="")) $repertoire=".";
         if (!is_dir($repertoire)) 
         {
            @umask("0000");
            @mkdir($repertoire,0777);
            $fp = fopen($repertoire."/index.html", 'w');
            fclose($fp);
         }

         $heure_jour = date("H:i");
         $data0 = "# ========================================================$crlf"
            ."# $crlf"
            ."# Sauvegarde de la base de données : ".$dbname." $crlf"
            ."# Effectuée le ".$date_jour." : ".$heure_jour." par ".$name." $crlf"
            ."# $crlf"
            ."# ========================================================$crlf";
         $data1="";
         $ifile=0;
         for($i = 0; $i < $num_tables; $i++)
         {
            $table = mysql_tablename($tables, $i);
            $data1 .= "$crlf"
               ."# --------------------------------------------------------$crlf"
               ."# $crlf"
               ."# Structure de la table '".$table."' $crlf"
               ."# $crlf$crlf";
            $data1 .= get_table_def($table)
               ."$crlf$crlf"
               ."# $crlf"
               ."# Contenu de la table '".$table."' $crlf"
               ."# $crlf$crlf";
            $result = mysql_query("SELECT * FROM $table");
            $count_line = mysql_num_fields($result);
            while($row = mysql_fetch_row($result))
            {
               $schema_insert = "INSERT INTO $table VALUES (";
               for($j = 0; $j < $count_line; $j++)
               {
                  if(!isset($row[$j]))
                  {
                     $schema_insert .= " NULL";
                  }
                  else 
                  if ($row[$j] != "")
                  {
                     $schema_insert .= " '". PrepareString($row[$j])."'";
                  }
                  else
                  {
                     $schema_insert .= " ''";
                  }
                  if($j < ($count_line -1))
                  {
                     $schema_insert .= ",";
                  }
               }
               $schema_insert .= ");$crlf";

               $data1 .= $schema_insert;

               if ($linebyline==1)
               {
                  if ( strlen($data1) > ($savemysql_size*1024))
                  {
                     send_tofile($data0.$data1,$repertoire,$filename."-".sprintf("%03d", $ifile),"sql",$MSos);
                     $data1="";
                     $ifile++;
                  }
               }
            }

            $data1 .= "$crlf$crlf"
               ."# --------------------------------------------------------$crlf";

            if ($linebyline==0)
            {
               if ( strlen($data1) > ($savemysql_size*1024))
               {
                  send_tofile($data0.$data1,$repertoire,$filename."-".sprintf("%03d", $ifile),"sql",$MSos);
                  $data1="";
                  $ifile++;
               }
            }
         } 
         if ( strlen($data1) > 0)
         {
            send_tofile($data0.$data1,$repertoire,$filename."-".sprintf("%03d", $ifile),"sql",$MSos);
            $data1="";
            $ifile++;
         }
      }
   }

   switch($op) {
      case "SavemySQL":
         $MSos=get_os();
         if ($MSos=="Win") {$crlf="\r\n";} else {$crlf="\n";}
         if ($MSos=="Win") {$crlf2="\\r\\n";} else {$crlf2="\\n";}

         if ($savemysql_mode==2) {
            dbSave_tofile("logs",0, $savemysql_size);
            echo "<SCRIPT type=\"text/javascript\" language=\"JavaScript\">
                  alert('".adm_translate("Sauvegarde terminée. Les fichiers sont disponibles dans le repertoire /logs")."');
                  </SCRIPT>";
            redirect_url("admin.php");
         } else if ($savemysql_mode==3) {
            dbSave_tofile("logs",1, $savemysql_size);
            echo "<SCRIPT type=\"text/javascript\" language=\"JavaScript\">
                  alert('".adm_translate("Sauvegarde terminée. Les fichiers sont disponibles dans le repertoire /logs")."');
                  </SCRIPT>";
            redirect_url("admin.php");
         } else {
            dbSave();
            header("Location: admin.php");
         }
         break;

      default:
         header("Location: index.php");
         break;
   }
}
?>
