<?
// TIME DINGY
function getmicrotime(){ 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec); 
} 
$time_start = getmicrotime();

include "config.php";
include "function.php";

session_start();
if (session_is_registered("dead_db_entrys")) { session_unregister("dead_db_entrys"); unset($dead_db_entrys); }
if (session_is_registered("unregged_files")) { session_unregister("unregged_files"); unset($unregged_files); }

if (!$conn) { $conn=connectdb(); }

// Reading dir and creating array.
if ($dir=opendir($filedir)) {
	if (count($dir)=='0') { $db_filenamearray=array(); }
	else {
	    while ($filename=readdir($dir)) {
		    if($filename=="." or $filename=="..") continue;
        	$dir_filenamearray[]=$filename;
	    }
	}
} else {
    $errormes.="Cannot open $filedir for reading.";
}

// Reading database and creating array.
if ($result=mysql_query("select filename from files", $conn)) {
	if (mysql_num_rows($result)=='0') { $db_filenamearray=array(); }
	else {
	    while ($row=mysql_fetch_array($result)) {
    	    $db_filenamearray[]=$row['filename'];
	    }
	}
} else {
    $errormes.="Error while querying database.";
}

/*
// Checking for files which are not regged in the db.
while (list($key, $filename)=each($dir_filenamearray)) {
    if (!in_array($filename, $db_filenamearray)) {
        $unregged_files[]=$filename;
    }
}
*/

$unregged_files=@array_diff($dir_filenamearray, $db_filenamearray);

/*
// Checking for dead db entrys.
while (list($key, $filename)=each($db_filenamearray)) {
    if (!in_array($filename, $dir_filenamearray)) {
        $dead_db_entrys[]=$filename;
    }
}
*/

$dead_db_entrys=@array_diff($db_filenamearray, $dir_filenamearray);

// If differences are found, save the arrays in the session.
if (is_array($unregged_files)) {
    session_register("unregged_files");
    $noticemes.=count($unregged_files)." unregistered files found.\n";
    $need_to_update=true;
} else {
    $noticemes.="No unregistered files found.\n";
}
if (is_array($dead_db_entrys)) {
    session_register("dead_db_entrys");
    $noticemes.=count($dead_db_entrys)." dead DB entry's found.\n";
    $need_to_update=true;
} else {
    $noticemes.="No dead DB entry's found.\n";
}

html_header();
start_maintable();
//echo "<p align=\"center\"><b>".nl2br($errormes)."</b>";
//echo nl2br($noticemes)."</p>";

if ($need_to_update) {
    echo "<p align=\"center\"><a href=\"updatedb.php\">Update the database now.</a></p>";
} else {
    echo "<p align=\"center\">The database looks up-to-date.</p>";
}
end_maintable();
html_footer();
$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "<!-- Did it in $time seconds -->";
?>