<?php

@( (bool)FALSE === strpos( $_SERVER['REQUEST_URI'], basename( __FILE__ ) ) ) OR exit( '!! ACCESS DENIED !!' );
error_reporting( _E_VALUE );


/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | myPHPNuke Version 188_8 RC2                                          |
// +----------------------------------------------------------------------+
// | License: GNU/GPL - http://www.gnu.org/copyleft/gpl.html              |
// +----------------------------------------------------------------------+
// | Support: http://myphpnuke.com/                                       |
// +----------------------------------------------------------------------+
// | Author: myPHPNuke Dev Team                                           |
// +----------------------------------------------------------------------+
// | Copyright: © 2001-2004 myPHPNuke Dev Team                            |
// +----------------------------------------------------------------------+
// $Id: savedb.php,v 1.1.2.8 2004/08/15 12:58:16 kirilt Exp $




/************************************************************************/
/* MYPHPNUKE: Web Portal System                                         */
/* ===========================                                          */
/*                                                                      */
/* Save the database of a MYPHPNuke web site                            */
/* Original script for phpnuke by                                       */
/* Thomas Rudant (thomas.rudant@grunk.net)                              */
/* http://www.grunk.net                                                 */
/*                                                                      */
/* Adaptation MyPhpNuke par Xavier JULIE                                */
/* http://www.securite-internet.org                                     */
/*                                                  */
/* 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.       */
/************************************************************************/

function saveDB()
{
    echo '<h1>' . translate( 'You have selected to save your database' ) . '.</h1><br />' . "\n";

    echo translate( 'This utility will create a .sql file with your entire database in sql format.' );
    echo '<br />' . "\n";

    echo translate( 'While this utility is convenient, the format is not compatible with phpMyAdmin.' );

    echo '<br /><br />' . "\n";

    echo translate( 'If you use phpMyAdmin to manage your database' ) . '<br />' . translate( 'it is recommended you backup your database from that utility.' );

    echo '<br /><br />' . "\n";

    echo '<b>' . translate( 'Please Note' ) . ':</b>  ' . translate( 'Depending on your database size and server speed' ) . ',<br />' . translate( 'the download may take up to 30 secs or more to start' );

    echo '<br /><br />' . "\n";

    echo '<a class="subtitle1" href="./admin.php?fct=dbutil&amp;op=savedbnow" title="Save DB Now">' . translate( 'Download Database Backup Now' ) . '</a>' . "\n";

}

function saveDBNow()
{


    @set_time_limit(600);
    $crlf="\n";

    // English Text
    $strNoTablesFound = translate("No tables found in database....");
    $strTableStructure = translate("Table structure for table");
    $strDumpingData = translate("Dumping data for table");
    $strError = translate("Error");
    $strSQLQuery = translate("SQL-query");
    $strMySQLSaid = translate("MySQL said: ");
    $strBack = translate("Back");
    $strName = translate("Database saved");
    $strDate = translate("Date");
    $strTime = translate("Time");
    $date_jour = date(translate("dumpdatestring"));

    if ( FunctionLibrary :: checkPHPVersion( 4.2 ) )
    {
        @ob_clean();
    }
    else
    {
        while( @ob_end_clean() );
    }

    @ob_start();

    header("Content-disposition: filename=mpn_database.sql");
    header("Content-type: application/zip");
    header("Pragma: no-cache");
    header("Expires: 0");

    // doing some DOS-CRLF magic...
    $client = getenv("HTTP_USER_AGENT");

    if(ereg('[^(]*\((.*)\)[^)]*',$client,$regs))
    {
    $os = $regs[1];
    // this looks better under WinX
    if (eregi("Win",$os))
        $crlf="\r\n";
    }

    include('./admin/original/dbconfig.php');

    $tables = mysql_list_tables($dbname);

    $num_tables = @mysql_numrows($tables);

    if($num_tables == 0)
    {
        echo $strNoTablesFound;
    }
    else
    {
        $i = 0;
        $heure_jour = date("H:i");
        echo "# ========================================================$crlf";
        echo "#$crlf";
        echo "# $strName : $dbname$crlf";
        echo "# $strDate : $date_jour$crlf";
        echo "# $strTime : $heure_jour$crlf";
        echo "#$crlf";
        echo "# ========================================================$crlf";
        echo "$crlf";

        while($i < $num_tables)
        {
            $table = mysql_tablename($tables, $i);

            echo $crlf;
            echo "# --------------------------------------------------------$crlf";
            echo "#$crlf";
            echo "# $strTableStructure '$table'$crlf";
            echo "#$crlf";
            echo $crlf;

            echo get_table_def($dbname, $table, $crlf).";$crlf$crlf";

        echo "#$crlf";
        echo "# $strDumpingData '$table'$crlf";
        echo "#$crlf";
        echo $crlf;

        get_table_content($dbname, $table, "my_handler");

            $i++;
        }
    }

    unset($dbhost, $dbuname, $dbpass, $dbname);

    @ob_end_flush();
    exit;
}

function my_handler($sql_insert)
{
    global $crlf;
    echo "$sql_insert;$crlf";
}

// Get the content of $table as a series of INSERT statements.
// After every row, a custom callback function $handler gets called.
// $handler must accept one parameter ($sql_insert);
function get_table_content($db, $table, $handler)
{
    $result = mysql_db_query($db, "SELECT * FROM $table") or mysql_die();
    $i = 0;
    while($row = mysql_fetch_row($result))
    {
//        set_time_limit(60); // HaRa
        $table_list = "(";

        for($j=0; $j<mysql_num_fields($result);$j++)
            $table_list .= mysql_field_name($result,$j).", ";

        $table_list = substr($table_list,0,-2);
        $table_list .= ")";

        if(isset($GLOBALS["showcolumns"]))
            $schema_insert = "INSERT INTO $table $table_list VALUES (";
        else
            $schema_insert = "INSERT INTO $table VALUES (";

        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= " NULL,";
            elseif($row[$j] != "")
                $schema_insert .= " '".addslashes($row[$j])."',";
            else
                $schema_insert .= " '',";
        }
        $schema_insert = ereg_replace(",$", "", $schema_insert);
        $schema_insert .= ")";
        $handler(trim($schema_insert));
        $i++;
    }
    return (true);
}

// Return $table's CREATE definition
// Returns a string containing the CREATE statement on success
function get_table_def($db, $table, $crlf)
{
    $schema_create = "";
    $schema_create .= "DROP TABLE IF EXISTS $table;$crlf";
    $schema_create .= "CREATE TABLE $table ($crlf";

    $result = mysql_db_query($db, "SHOW FIELDS FROM $table") or mysql_die();
    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]";
        $schema_create .= ",$crlf";
    }
    $schema_create = ereg_replace(",".$crlf."$", "", $schema_create);
    $result = mysql_db_query($db, "SHOW KEYS FROM $table") or mysql_die();
    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)";
    return (stripslashes($schema_create));
}

function mysql_die($error = "")
{
    echo "<b> $strError </b><p>";
    if(isset($sql_query) && !empty($sql_query))
    {
        echo "$strSQLQuery: <pre>$sql_query</pre><p>";
    }
    if(empty($error))
        echo $strMySQLSaid . mysql_error();
    else
        echo $strMySQLSaid . $error;
    echo "<br><a href=\"javascript:history.go(-1)\">$strBack</a>";
    exit;
}

?>
