<?php
/************************************************************************/
/* Maximus CMS: Web Portal System                                       */
/* ==============================                                       */
/*                                                                      */
/* Copyright (c) 2002 - 2006                                            */
/* http://www.php-maximus.fr                                            */
/* dev@php-maximus.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.       */
/************************************************************************/
/* Based on PHP-NUKE: Web Portal System                                 */
/************************************************************************/
if (!defined('ADMIN_ALLOW') && !defined('ADMIN_MAX')) {
	die ("Access Denied");
}
if (!defined('DATABASE_MAX')) {
	die ("Access Denied");
}

if ($acces == 1) {
if ($admintest && $adminsecu)  {

if (!is_god($admin)) { redirect_url("".$admin_file.".php?op=database"); }
if (!is_admin($admin)) { redirect_url("".$admin_file.".php?op=database"); }
if (!is_user($user)) { redirect_url("".$admin_file.".php?op=database"); }

function menu_mysqltap($table = 0) {
        global $admin_file, $tablename, $dbhost, $dbname;
	br('1');
        Max_OpenTable();
        echo "<center><a href=\"".$admin_file.".php?op=mysqltap\"><font class='title'><b>"._DB_MYSQLTAP."</b></font></a></center>";
        Max_CloseTable();

        br('1');

	echo "&nbsp;<img src=\"images/arrow.png\" alt=\""._DB_SERVER."\" title=\""._DB_SERVER."\" />&nbsp;"._DB_SERVER.": <a href='".$admin_file.".php?op=mysqltap'><b>$dbhost</b></a>"
	    ."&nbsp;<img src=\"images/arrow.png\" alt=\""._DB_DATABASE."\" title=\""._DB_DATABASE."\" />&nbsp;"._DB_DATABASE.": <b>$dbname</b>";
	if ( !empty($table) ) {
        echo "&nbsp;<img src=\"images/arrow.png\" alt=\""._DB_TABLE."\" title=\""._DB_TABLE."\" />&nbsp;"._DB_TABLE.": <a href='".$admin_file.".php?op=mtbrowse&tablename=$tablename'><b>$tablename</b></a>";
	}

        br('2');
        if ( !empty($table) ) {
	echo "&nbsp;&nbsp;<a href=\"".$admin_file.".php?op=mtshowtable&tablename=$tablename\" class=\"bouton-relief\"><img src='images/blocks/calendar.gif' border='0' alt='' /> <b>"._DB_STRUCTURE."</b></a>";
	echo "<a href=\"".$admin_file.".php?op=mtbrowse&tablename=$tablename\" class=\"bouton-relief\"> <img src=\"images/view.gif\" border=\"0\" alt='' /> <b>"._DB_VIEW."</b></a>";
        } else {
        echo "<a href=\"".$admin_file.".php?op=mysqltap\" class=\"bouton-relief\"> <img src=\"images/blocks/calendar.gif\" border=\"0\" alt='' /> <b>"._DB_STRUCTURE."</b></a>";
	}
        echo "<a href=\"".$admin_file.".php?op=mtsqlimport\" class=\"bouton-relief\"> <img src=\"images/blocks/b_sql.png\" border=\"0\" alt='' /> <b>"._DB_SQL."</b></a>";
        br('1');
}

function editor_table($tablename, $field, $id) {
    global $bgcolor2, $prefix, $dbname, $tablename, $admin_file;
    incoh();
    menu();
    menu_mysqltap('1');
    br('1');
    if ( empty ($tablename) or empty ($id)) {    // No table?
    	message_die(GENERAL_ERROR, $lang['SQL_Admin_No_Table']);
    }
    echo "<form action=\"".$admin_file.".php\" method='post'>";

//                        nuke_autheur     aid      nsn
    $sql = "SELECT * FROM `$tablename` WHERE `$field`='$id' ";
    if ( !($result = $GLOBALS['db']->sql_query($sql)) ){
    	query_die(GENERAL_ERROR, 'Could not obtain '.$tablename.'', '', __LINE__, __FILE__, $sql);
    }
    $row = $GLOBALS['db']->sql_fetchrow($result);

    // Retrieve columns for this table:
//                                 nuke_auteur
    $sql1    = "SHOW COLUMNS FROM " . $tablename;
    $result1 = $GLOBALS['db']->sql_query($sql1);
    if (!$result1) {  // Right... no columns?!?
        message_die(GENERAL_ERROR, $lang['SQL_Admin_Columns_Error']);
    }
    // Go through columns list, saving each Field.
    // Also save a SELECT argument.
    $fieldcount  = 0;
    $fieldselect = '';            // SELECT $fieldselect FROM
    echo "<table border='1' width='100%'>";        // these are the available columns for this table...
    echo "<tr><td align='center'><b> Field </b></td><td align='center'><b> Type </b></td><td align='center'><b>Value</b>  </td></tr>";
    while ( $row1 = $GLOBALS['db']->sql_fetchrow($result1) ) {
    $fieldcount++;
    $Field  = stripslashes($row1['Field']);
    $Type   = stripslashes($row1['Type']);
       // if ($fieldcount > 1)
       // {
       //     $fieldselect .= ", ";
       // }
      //  $field[$fieldcount] = stripslashes($row1['Field']);
      //  $fieldselect .= stripslashes($row1['Field']);
// nom des champs                     aid                                               varchar
echo "<tr><td width='20%'>&nbsp;<b>".$Field."</b></td><td width='20%' valign='top'>&nbsp;$Type</td>";

//$zone1 = "<input name=\"\" value=\"\">";

// insert des champs
if ( $Field == $field ) {
 	echo "<td align='left'>&nbsp;<b>".$row[$Field]."</b></td></tr>";
} else {

	if ( $Type == "text" ) {
		echo  "<td align='left'><textarea name=\"".$Field."\" rows='5' wrap='virtual' cols='58'>".$row[$Field]."</textarea></td></tr>";
	} else {
		echo "<td align='left'><input type='text' name=\"".$Field."\" value=\"".$row[$Field]."\" size='60' maxlength='100'></td></tr>";
	}

    }

}
echo "<input type='hidden' name='tablename' value='$tablename' />"
    ."<input type='hidden' name='field' value='$field' />"
    ."<input type='hidden' name='id' value='$id' />"
    ."</table>"
    ."<center><input type='hidden' name='op' value='SaveTable' />"
    ."<input type='submit' value=\"sauve table\" /></center>"
    ."</form><br />";
incof();
}


function browsetable($tablename, $which) {
    global $bgcolor2, $prefix, $dbname, $tablename, $which;
    incoh();
    menu();
    menu_mysqltap('1');
    br('1');
    if ( empty ($tablename)) { // No table?
        message_die(GENERAL_ERROR, $lang['SQL_Admin_No_Table']);
    }
    if ( empty ($which)) {
	$which = 30;
	$first = "";
    } else {
	$which += 30;
    }
    // Retrieve columns for this table:
    $sql = "SHOW COLUMNS FROM " . $tablename;
    $result = $GLOBALS['db']->sql_query($sql);
    if (!$result) { // Right... no columns?!?
        message_die(GENERAL_ERROR, $lang['SQL_Admin_Columns_Error']);
    }
    // Go through columns list, saving each Field.
    // Also save a SELECT argument.
    $fieldcount = 0;
    $fieldselect = '';            // SELECT $fieldselect FROM
    $columnsbrowse = "<table border='1' width='100%'><tr><td></td>";        // these are the available columns for this table...
    while ($row = $GLOBALS['db']->sql_fetchrow($result)) {
        $fieldcount++;
        if ($fieldcount > 1)
        {
            $fieldselect .= ", ";
        }
        $field[$fieldcount] = stripslashes($row['Field']);
        $fieldselect   .= stripslashes($row['Field']);
        $columnsbrowse .= "<td align='center'><a href=\"" . $file . "?mode=browse&amp;tablename=" . $tablename . "&order=" . $fieldcount . "&sort=ASC\">" . $row['Field'] . "</a></td>";
    }
    $columnsbrowse .= "</tr>";
    // Found ourselves all the columns/fields... let's retrieve the information and build an output.
    // First, let us quickly fetch the total number of entries in this table:
    $sql = "SELECT " . $fieldselect . " FROM " . $tablename;
    $result       = $GLOBALS['db']->sql_query($sql);
    $totalentries = $GLOBALS['db']->sql_numrows($result);
    // OK, now that that is out of the way, let us continue:
    // order by?
    if (empty($order)) {
        $order = 1;
    }
    $sql = "SELECT " . $fieldselect . " FROM " . $tablename . " ORDER BY " . $field[$order] . " ";
    // check for additional options
    if (empty($sort) || ($sort == 'ASC')) {
        $sort = "ASC";
        $sql .= "ASC";
    } else {
        $sort = "DESC";
        $sql .= "DESC";
    }
    $sql .= " ";
#    if (empty($first)) {
        $first = $which - 30;
#    }
    $sql .= "LIMIT " . $first . ", 30";

    $result = $GLOBALS['db']->sql_query($sql);
    if (!$result) {  // No results?
        message_die(GENERAL_ERROR, sprintf($lang['SQL_Admin_Browse_Error'], $tablename));
    }
    // OK, we have the data... let's put it out to a thingy!
    while ($row = $GLOBALS['db']->sql_fetchrow($result)) {

	$tabledata .= "<tr><td><a href=\"" . $file . "?mode=submit&amp;this_query=DELETE FROM " . $tablename . " WHERE " . $field[1] . "=\"" . $row[$field[1]] . "\"\"><img src='images/nukesentinel/delete.png' border='0' alt=\""._DELETE."\" TITLE=\""._DELETE."\" /></a> <a href=\"" . $file . "?op=editor_table&amp;tablename=$tablename&amp;field=".$field[$order]."&amp;id=".$row[$field[1]]."\"><img src='images/edit.gif' border='0' alt=\""._EDIT."\" title=\""._EDIT."\" /></a></td>";

        for ($i = 1; $i <= $fieldcount; $i++) {
            $tabledata .= "<td align='center'>" . $row[$field[$i]] . "</td>";
        }
    $tabledata .= "</tr>";
    }

    // Assign some stuff to the template:
    $jumpprev = $first - 30;
    if ($jumpprev < 0) {
        $jumpprev = 0;
    }
    $columnbrowsetitle = sprintf ("<tr><td colspan=\"".++$fieldcount."\">"._DB_ROWS." $tablename");
    $columnbrowsetitle .= " - <a href=\"" . $file . "?mode=browse&amp;tablename=" . $tablename . "&first=0&sort=" . $sort . "&order=" . $order ."\">"._DB_PAGE1."</a>";
    $columnbrowsetitle .= " - <a href=\"" . $file . "?mode=browse&amp;tablename=" . $tablename . "&first=" . $jumpprev . "&sort=" . $sort . "&order=" . $order ."\">"._DB_PAGEPREVIOUS."</a>";
    $columnbrowsetitle .= " - <a href=\"" . $file . "?mode=browse&amp;tablename=" . $tablename . "&first=" . $jumpnext . "&sort=" . $sort . "&order=" . $order ."\">"._DB_PAGENEXT."</a>";
    $columnbrowsetitle .= " - <a href=\"" . $file . "?mode=browse&amp;tablename=" . $tablename . "&first=" . $first . "&sort=ASC&order=" . $order ."\">ASC</a>";
    $columnbrowsetitle .= " - <a href=\"" . $file . "?mode=browse&amp;tablename=" . $tablename . "&first=" . $first . "&sort=DESC&order=" . $order ."\">DESC</a></td></tr>";
    // Free result...
    $GLOBALS['db']->sql_freeresult($result);
    echo "<table><tr>".$columnbrowsetitle;
    echo "</tr><tr>".$columnsbrowse;
    echo "</tr><tr>".$tabledata."</table>";
    echo "<a href=\"$file?op=mtbrowse&amp;tablename=$tablename&amp;which=$jumpprev\">30 "._DB_PREVIOUS."</a> | ";
    echo "<a href=\"$file?op=mtbrowse&amp;tablename=$tablename&amp;which=$which\">30 "._DB_NEXT."</a>";
    echo "</table>";
    br('4');
    incof();
}


function showtable($tablename) {
        global $bgcolor2, $prefix, $dbname, $tablename;
	incoh();
	menu();
	menu_mysqltap('1');
      //  echo "<center><b>"._MYSQLTAPSHOW.": $tablename</b></center>";
        br('1');
        echo "<table border='0' width='100%'>";

    if ( empty ($tablename)) { // No table specified...
	echo "no tablename";
	break;
    }

    $sql = "SHOW COLUMNS FROM " . $tablename;

    $result = $GLOBALS['db']->sql_query($sql);
    if (!$result) {
	echo "no data";
	break;
    }
    // Found data (obviously), let's build an output...
    $columns = "<table border='1' width='100%'><tr><td></td><td><center><b>"._DB_FIELD."</b></center></td><td><center><b>"._DB_TYPE."</b><center></td><td width='1'><center><b>"._DB_NULL."</b></center></td><td width='1'><center><b>"._DB_KEY."</b></center></td><td width='1'><center><b>"._DB_DEFAULT."</b></center></td><td width='1'><center><b>"._DB_EXTRA."</b></center></td></tr>";
    while ($row = $GLOBALS['db']->sql_fetchrow($result))  {
 	$mt_field   = stripslashes($row['Field']);
 	$mt_null    = stripslashes($row['Null']);
 	$mt_type    = stripslashes($row['Type']);
 	$mt_key     = stripslashes($row['Key']);
 	$mt_default = stripslashes($row['Default']);
 	$mt_extra   = stripslashes($row['Extra']);

 ( $mt_null    == "" ) ? ( $mt_null = ""._DB_NO."" ) : ( $mt_null = ""._DB_YES."" );
 ( $mt_key     == "" ) ? ( $mt_key = "-" ) : ( $mt_key );
 ( $mt_default == "" ) ? ( $mt_default = "-" ) : ( $mt_default );
 ( $mt_extra   == "" ) ? ( $mt_extra = "-" ) : ( $mt_extra );

        $columns .= "<tr>";
        $columns .= "<td><a href=\"" . $file . "?op=mtsubmit&amp;query=DROP&amp;tablename=" . $tablename . "&field=" . $row['Field'] . "&confirm=yes\"><img src='images/nukesentinel/delete.png' border='0' align='absmiddle' alt=\""._DELETE."\" title=\""._DELETE."\" /></a>";
        $columns .= "</td><td>&nbsp;";
        $columns .= $mt_field;
        $columns .= "</td><td>&nbsp;";
        $columns .= $mt_type;
        $columns .= "</td><td><center>";
        $columns .= $mt_null;
        $columns .= "</center></td><td><center>";
        $columns .= $mt_key;
        $columns .= "</center></td><td><center>";
        $columns .= $mt_default;
        $columns .= "</center></td><td><center>";
        $columns .= $mt_extra;
        $columns .= "</center></td></tr>";
    }
    $columns .= "</table>";
    echo "$columns";
    $GLOBALS['db']->sql_freeresult($result);

  Max_CloseTable();
  br('1');
  incof();
}


function mysqltap() {
	global $bgcolor2, $prefix, $dbname, $tablename;
	incoh();
	menu();
	menu_mysqltap();
	br('1');
	echo "<table border='0' width='100%'>";

// Retrieving the currently existing tables:
	$sql = "SHOW TABLES";
	$result = $GLOBALS['db']->sql_query($sql);
	if (!$result){
    // this makes no sense, the board would be dead... :P
		echo "dead";
	}
// Make it into a semi-nice looking little list:
$fooh  = 'Tables_in_';
$fooh .= $dbname;
$grab  = 'Name';
$tablecount  = 0;
$recordcount = 0;
$sumtotal    = 0;
$tables  = "<table border='1' width='100%'>";
$tables .= "<tr><td></td><td><center><b>"._DB_TABLE."</b></center></td><td colspan='6'><center><b>"._DB_ACTION."</b></center></td><td><center><b>"._DB_DATAS."</b></center></td><td><center><b>"._DB_TYPE."</b></center></td><td><center><b>"._DB_SIZE."</b></center></td><td><center><b>"._DB_StatusDB."</b></center></td>";
while ($row = $GLOBALS['db']->sql_fetchrow($result)) {

    $sql2    = "SELECT COUNT(*) as CNT FROM ".$row[$fooh];
    $result2 = $GLOBALS['db']->sql_query($sql2);
    $row2    = $GLOBALS['db']->sql_fetchrow($result2);
    $cntrecords = $row2['CNT'];
    $recordcount += $cntrecords;
    $GLOBALS['db']->sql_freeresult($result2);

    $tablecount++;
    $tables .= "<tr>";
    $tables .= "<td>x</td>";
    $tables .= "<td>&nbsp;" . $row[$fooh] . "</td>";
    $tables .= "<td><a href=\"" . $file . "?op=mtshowtable&tablename=" . $row[$fooh] . "\">";
    $tables .= "<img src=\"images/blocks/calendar.gif\" border=\"0\" align=\"absmiddle\" alt=\""._DB_STRUCTURE."\" title=\""._DB_STRUCTURE."\" />";
    $tables .= "</a></td>";
    $tables .= "<td><a href=\"" . $file . "?op=mtbrowse&tablename=" . $row[$fooh] . "\">";
    $tables .= "<img src=\"images/view.gif\" border=\"0\" align=\"absmiddle\" alt=\""._DB_VIEW."\" title=\""._DB_VIEW."\" />";
    $tables .= "</a></td>";
    $tables .= "<td><a href=\"" . $file . "?op=mtoptimize&tablename=" . $row[$fooh] . "\">";
    $tables .= "<img src=\"images/blocks/sysinfo.png\" border=0 align=\"absmiddle\" alt=\""._DB_OptimizeDB."\" title=\""._DB_OptimizeDB."\" />";
    $tables .= "</a></td>";
    $tables .= "<td><a href=\"" . $file . "?op=mtrepair&tablename=" . $row[$fooh] . "\">";
    $tables .= "<img src=\"images/blocks/config.png\" border=\"0\" align=\"absmiddle\" alt=\""._DB_RepairDB."\" title=\""._DB_RepairDB."\" />";
    $tables .= "</a></td>";
    $tables .= "<td><a href=\"" . $file . "?op=submit&this_query=DELETE FROM " . $row[$fooh] . "&confirm=yes\">";
    $tables .= "<img src=\"images/trashmini.png\" border=0 align=\"absmiddle\" alt=\""._DB_EMPTY."\" title=\""._DB_EMPTY."\">";
    $tables .= "</a></td>";
    $tables .= "<td><a href=\"" . $file . "?op=submit&this_query=DROP TABLE " . $row[$fooh] . "&confirm=yes\">";
    $tables .= "<img src=\"images/nukesentinel/delete.png\" border=\"0\" align=\"absmiddle\" alt=\""._DELETE."\" title=\""._DELETE."\" />";
    $tables .= "</a></td>";
    $tables .= "<td><center>$cntrecords</center>";

    $tot_data = 0;
    $tot_idx  = 0;
    $tot_all  = 0;
    $local_query = "SHOW TABLE STATUS FROM ".$dbname." like '$row[$fooh]'";
    $result2 = $GLOBALS['db']->sql_query($local_query);
    if ($GLOBALS['db']->sql_numrows($result2)) {
        while ($row2 = @$GLOBALS['db']->sql_fetchrow($result2)) {
            $tot_data = $row2['Data_length'];
            $tot_idx  = $row2['Index_length'];
            $type  = $row2['Type'];
            $total = $tot_data + $tot_idx;
            $total = $total / 1024;
            $total = round ($total,3);
	    $sumtotal += $total;
            $gain = $row2['Data_free'];
            $gain = $gain / 1024 ;
            $total_gain += $gain;
            $gain = round ($gain,3);
        }
    }
    $tables .= "</td><td>$type</td>";
    $tables .= "<td><center>$total KB</center></td>";
    if ($gain == 0) {
	$tables .= "<td>"._DB_OPTIMIZED1."";
    } else {
	$tables .= "<td><a href=\"" . $file . "?op=mtoptimize&tablename=" . $row[$fooh] . "\">";
	$tables .= "<img src='images/admin/button_insert.png' border='0' align='absmiddle' alt=\""._MTOPTIMIZE."\" />";
	$tables .= "</a>";
    	$tables .= " "._DB_OPTIMIZED.": $gain KB";
	$sumgain += $gain;
    }
    $tables .= "</td></tr>";
}
$GLOBALS['db']->sql_freeresult($result);
$GLOBALS['db']->sql_freeresult($result2);
$tables .= "<tr><td></td><th>$tablecount table(s)<th colspan=\"6\">Total<th>$recordcount<th>--<th>$sumtotal KB<th>";
if ($sumtotal) {
	$tables .= ""._DB_LOOSE." $sumgain KB";
} else {
	$tables .= ""._DB_OPTIMIZE_ALL."";
}
$tables .= "</tr>";
$tables .= "</table>";
echo "$tables";


	br('1');
/*	Max_OpenTable();
	?>
	Utilisez cet Utilitaire avec pr�aution ! Vous assumez seul tout risque ! Ceci est une version B�a<br />
	<form action="admin.php" method="post">
	<textarea cols="85" rows="10" name="mtform"></textarea><br />
	<input type="submit" name="op" value="Envoyer ce Code SQL">
	</form>

	<?php
*/      //  echo "</table>";

//	echo "Copyright 2003 <a href=\"http://nukecops.com\">Nuke Cops</a>"
//	." & Zhen-Xjell - All Rights Reserved.";

	//Max_CloseTable();
	//br('1');
	incof();
}

function optimize($tablename) {
    global $prefix, $tablename, $dbname;
    incoh();
    menu();
    menu_mysqltap();
    Max_OpenTable();
    $sql = "OPTIMIZE TABLE ".$tablename;
    $result = $GLOBALS['db']->sql_query($sql);
    if (!$result) {
	echo "optimize error: $tablename";
	break;
    }
    $GLOBALS['db']->sql_freeresult($result);
    echo "<h2>"._DB_OPTIMIZED.": $tablename</h2>";
    Max_CloseTable();
    incof();
}

function mtsqlimport() {
    incoh();
    menu();
    menu_mysqltap();
    br('1');
    Max_OpenTable();

    echo ""._DB_CODEGO1."<br />"
        ."<form action=\"".$admin_file.".php\" method=\"post\">"
	."<textarea cols=\"85\" rows=\"10\" name=\"mtform\"></textarea><br />"
	."<input type=\"submit\" name=\"op\" value=\""._DB_CODEGO."\">"
	."</form>";

   Max_CloseTable();
   incof();
}

function mtformsubmit($mtform) {
    global $mtform;
    incoh();
    menu();
    menu_mysqltap();
    Max_OpenTable();

    $mtform = stripslashes($mtform);
    $result = $GLOBALS['db']->sql_query($mtform);

    if(!$result) {
	$error = $GLOBALS['db']->sql_error();
	echo "MySQL ERROR! $error[code] : $error[message]<br /><br />";
    }
    echo "<u>SQL CODE EXECUTED</u>:"
    ."<blockquote><hr />"
    .$mtform
    ."<hr /></blockquote>";
    $GLOBALS['db']->sql_freeresult($result);

    Max_CloseTable();
incof();
}

function repair($tablename) {
    global $prefix, $tablename, $dbname;
    incoh();
    menu();
    menu_mysqltap();
    Max_OpenTable();
    $sql = "REPAIR TABLE ".$tablename;
    $result = $GLOBALS['db']->sql_query($sql);
    if (!$result) {
        echo "repair error: $tablename";
        break;
    }
    $db->sql_freeresult($result);
    echo "<h2>Repaired: $tablename</h2>";
    Max_CloseTable();
    incof();
}

switch($op) {

	case "mysqltap":
		mysqltap();
		break;

	case "editor_table":
		editor_table($tablename, $field, $id);
		break;

	case "mtsqlimport":
		mtsqlimport();
		break;

    	case "mtshowtable":
		showtable($tablename);
		break;

	case "mtbrowse":
		browsetable($tablename,$which);
		break;

	case "mtoptimize":
		optimize($tablename);
		break;

	case "mtrepair":
		repair($tablename);
		break;
	case "SubmitSQL":
		mtformsubmit($mtform);
		break;

	case 'SaveTable':
	if ( !empty($_POST) ) {
   	 	foreach ($_POST as $key=>$secvalue) {
			$GLOBALS['db']->sql_query("UPDATE `".addslashes($tablename)."` SET `".addslashes($key)."`='".addslashes($secvalue)."'  WHERE `".addslashes($field)."`='".addslashes($id)."' ");
		}
	}
	redirect_url("".$admin_file.".php?op=editor_table&tablename=$tablename&field=$field&id=$id");
	break;
}
}

} else {
	echo "Access Denied";
}