<?php

require_once 'include/i18n.php';
require_once 'MDB.php';

// A class of static functions to manipulate databases.

class Databases
{
	/** Return the list of defined databases.
	 * @return array A hash of dbid => name pairs
	 */
	function All()
	{
		$data = Config::ReadConfig('database');
		
		$rv = array();
		foreach ($data as $id => $vals)
		{
			$name = @$vals['name'];
			if (!$name)
			{
				$name = _("Unknown database");
			}
			
			$rv[$id] = $name;
		}

		return $rv;
	}

	/** List of uninitialised databases.
	 * Similar in concept to Databases::List(), but instead does a
	 * check on each configured database to see if it looks like a
	 * configured IRM database, and if so, does not put it in the list.
	 */
	function Uninitialised()
	{
		$data = Config::ReadConfig('database');
		
		$rv = array();
		foreach ($data as $id => $vals)
		{
			$DSN = @$vals['DSN'];
			$dbh = MDB::Connect($DSN);
			if (MDB::isError($dbh))
			{
				continue;
			}

			// Bollocks query just to try and trigger an error if
			// there's no table
			$err = $dbh->query("SELECT * FROM computers WHERE ID=0");
			
			if (MDB::isError($err))
			{
				$name = @$vals['name'];
				if (!$name)
				{
					$name = _("Unknown database");
				}
			
				$rv[$id] = $name;
			}
			
			$dbh->disconnect();
		}

		return $rv;
	}
}
