Location: PHPKode > projects > HypatiaDB > hypatiadb/functions.php
<?php

function pass_hidden_form_values($values, $fieldname)
{
   for($i=0; $i < count($values); $i++)
      echo "<INPUT TYPE='hidden' NAME='" . $fieldname . $i . "' VALUE='$values[$i]'>";
}




function print_databases_dropdown_func($type, $selected_db)
{
   $databases_query = "SHOW DATABASES";
   ($databases_result = mysql_query($databases_query)) or die ("Query unsuccessful in print_database_dropdown()");

   if($type=="static")
   {
      echo "<SELECT NAME='database'>";
   }
   else if($type=="dynamic")
   {
      echo "<SELECT NAME='database' onChange='this.form.submit()'>";
   }

   echo "<OPTION VALUE=''>Select a Database</OPTION>";
   
   while ($row = mysql_fetch_array($databases_result))
   {
     //Do not include the 'HypatiaDB' and 'mysql' databases in the listing  
      if($row[0] != "HypatiaDB" && $row[0] != "mysql")  
         if($selected_db != $row[0])
            echo "<OPTION VALUE=" . $row[0] . ">$row[0]";
         else
            echo "<OPTION VALUE=" . $row[0] . " SELECTED>$row[0]";
   }
   
   echo "</SELECT>";

   return;
}



function print_tables_dropdown_func($type, $tables, $selected_table)
{
   if($type=="static")
   {
      echo "<SELECT NAME='tables'>";
   }
   else if($type=="dynamic")
   {
      echo "<SELECT NAME='table' onChange='this.form.submit()'>";
   }

   echo "<OPTION VALUE=''>Select a Table</OPTION>";
  
   while ($row = mysql_fetch_array($tables))
      if($selected_table != $row[0])
         echo "<OPTION VALUE=" . $row[0] . ">$row[0]";
      else
         echo "<OPTION VALUE=" . $row[0] . " SELECTED>$row[0]";

   echo "</SELECT>"; 

   return;
}





//This function is used to print the results of queries.
function print_query_results_func($query_result)
{
	echo '<table class="browse">';

	echo '<tr align="center" bgcolor="#D6D3CE">';
	for($i=0; $i < mysql_num_fields($query_result); $i++) {
		echo "<th class=\"firstrow\">";
		echo htmlspecialchars(mysql_field_name($query_result, $i), ENT_QUOTES);
		echo "</th>";
	}
	echo "</tr>";

	$rownum = 0;
	while($row = mysql_fetch_array($query_result)) {
		$rownum++;
		echo '<tr' . ($rownum % 2 == 0 ? ' class="banded"' : '') . '>';

		for($i=0; $i < mysql_num_fields($query_result); $i++) {
			echo '<td align="center">' . ($row[$i] == '' ? '&nbsp;' : htmlspecialchars($row[$i],ENT_QUOTES)) . "</td>";
		}      
		echo "</tr>";
	}

	echo "</table>";
}


//This function takes the name of a table as a parameter and returns the number of rows in that
//table

function table_count_func($table)
{
   $count_query = "SELECT COUNT(*) 
                   FROM $table";

   ($count_result = mysql_query($count_query)) or die("Count query unsuccesful");

   $row = mysql_fetch_array($count_result);
   $count = $row[0];
   
   return $count;
}


//This function returns the current database
function get_current_db()
{
   return $_SESSION['current_db']; 
}


//This function returns the current users status
function get_currentuser_status()
{
   return $_SESSION['session_user_status']; 
}


//This function is used to print out the function addition form where appropriate
//Deprecated in favour of saved reports

function favourtiesForm($query, $db, $table, $filename, $user_status)
{
/*echo '<form method="get" action="' . $filename . '" align="center" class="favf">';
echo '<input type="hidden" name="favourite" value="' . $query . '" />';
echo '<input type="hidden" name="table" value="' . $table . '" />';
echo '<input type="hidden" name="database" value="' . $db . '" />';

if($user_status == "viewer")
{
echo '<input type="text" name="fav_name" title="Favourite\'s Name" style="background: #FFE7C6" disabled="disabled" />';
echo '<input type="submit" value="Add to Favourites" disabled="disabled" />';
echo '</form>';
}

else
{
echo '<input type="text" name="fav_name" title="Favourite\'s Name" style="background: #FFE7C6;" />';
echo '<input type="submit" value="Add to Favourites" />';
echo '</form>';
}*/
}

//returns a list of databases, formatted according to fmt (using sprintf)
// * fmt		-- format to return
// * selected		-- the currently "selected" database
// * selected_fmt	-- format for the selected database
//The selected and selected_fmt variables are, of course, a cheap hack.
//If you need more flexibility, either write your own function, or turn
//$selected into a variable function call.
function listDbs($fmt, $selected = '', $selected_fmt = '') {
	$dbs = mysql_query("SHOW DATABASES");
	$rv = "";
	while($db = mysql_fetch_array($dbs)) {
		//we exclude:
		// * HypatiaDB		-- our own internal database
		// * mysql		-- mysql's internal database
		// * information_schema -- mysql's "informational" database
		if($db[0] != 'HypatiaDB' && $db[0] != 'mysql' && $db[0] != 'information_schema')
			if($db[0] == $selected)
				$rv .= sprintf($selected_fmt, $db[0]);
			else
				$rv .= sprintf($fmt, $db[0]);
	}
	return $rv;
}

//Lists tables according to $fmt (via sprintf)
// * $fmt	-- printf()-style format
// * $db	-- optionally, the database to get table list
//		   from (otherwise selected database is used)
function listTables($fmt,$db = '') {
	if($db!='')
		mysql_select_db($db);
	$rv = '';
	$tbls = mysql_query("SHOW TABLES");
	while($table = mysql_fetch_array($tbls)) {
		$rv .= sprintf($fmt, $table[0]);
	}
	return $rv;
}

function listFields($fmt, $db, $table) {
	mysql_select_db($db);
	$query = "DESCRIBE $table";
	($results = mysql_query($query)) or die(mysql_error());
	$rv = '';					//return value
	while($r = mysql_fetch_row($results)) {
		$rv .= sprintf($fmt, htmlspecialchars($r[0]));
	}
	return $rv;
}

//Connects to a database
//Basically a wrapper around mysql_connect.
function dbconnect($host, $username, $password) {
	global $database;
	return($database = mysql_connect($host, $username, $password));
}

function loadStrings($lang, $contexts) {
	$rarray = array();
	//loads strings for a specific language from the database
	if(is_array($contexts)) {
		$p = false;
		foreach($contexts as $c) {
			$p = true;
			if($p)
				$where_clause .= ' OR ';
			$where_clause = "context = '$c'";
		}
	} else {
		$where_clause = "context = '$contexts'";
	}
	$query = "SELECT name, string FROM strings WHERE lang = '$lang' AND ($where_clause)";
	mysql_select_db('HypatiaDB') or die(mysql_error());
	($result = mysql_query($query)) or die(mysql_error());
	while($r = mysql_fetch_array($result)) {
		$rarray["$r[name]"] = $r['string'];
	}
	return $rarray;
}

function headers() {		//send the headers
//We need to serve Content-Type: application/xhtml+xml to compliant browsers,
//and Content-Type: text/html to non-compliant browsers
	global $suppress_prologue;

	$suppress_prologue = false;
	if (isset($_SERVER['HTTP_ACCEPT']) && (boolean)strstr($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml')) {
		header('Content-Type: application/xhtml+xml');
	} else {
		$suppress_prologue = true;
		header('Content-Type: text/html');
	}
}

function html() {		//prints the html tag and doctype
	global $suppress_prologue,$lang;

	if(!$suppress_prologue) {
		echo('<' . '?xml version="1.0" encoding="UTF-8"?>');
	}
	echo('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
	echo('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $lang . '">');
}

function head($title, $scripts = "") {		//prints out the head element, with the specified title
				//TODO:L10N:??
	echo("<head><title>$title</title>");
	if(is_array($scripts)) {
		foreach($scripts as $script) {
			echo('<script type="text/javascript" src="' . $script . '"></script>');
		}
	}

echo('<script type="text/javascript">var ndb;
function clearElem(s) {
 var e = document.getElementById(s); while(e.firstChild) e.removeChild(e.firstChild);
}</script>
<link rel="stylesheet" href="styles/default.css" type="text/css" media="screen" title="Default Style"/>
<link rel="stylesheet" href="styles/default-print.css" type="text/css" media="print" title="Default Style"/>
');		//the scripts are needed by the navigation pane

	echo('<script type="text/javascript" src="xhr/create-xhr.php?target=\'xhr/get-data.php?action=table-list\'%2BString.fromCharCode(38)%2B\'db=\'%2Bndb&amp;caller=loadDb&amp;tid=lptablelist&amp;tfunc=clearElem(\'lptablelist\');"></script>
	<script type="text/javascript" src="js/menu.js"></script>
	
	</head>');

}

//menu -- prints out the body open-tag and the menu
// * onload	-- the contents of the onload attribute of the body tag (if any)
// * $suppress	-- suppresses printing the menu (for example, for the log in screen)
function menu($onload = "", $suppress = false, $need_login = true) {
	global $lang;
	echo('<body');
	if($onload != "") {
		echo(" onload=\" $onload\"");
	}
	echo('>');
	//User authentication:
	//check to see if the user is currently authenticated
	//if not, then we spit out an error, endhtml() and die
	$literals = loadStrings($lang,'MENU');
	if($need_login && !(isset($_SESSION['session_user']) && $_SESSION['session_user'] != '' && isset($_SESSION['session_user_password']) && $_SESSION['session_user_password'] != '')) {
		echo('<p class="error">' . $literals['MENU_NOAUTH'] . '</p>');
		endhtml(); exit(0);
	}
	if(!$suppress)
		include('menu.php');
}

function endhtml() {		//closes the <html> tag and the <body> tag
	echo('</body></html>');
}

function navpane() {		//prints the navigation frame
	global $lang;
	$literals = loadStrings($lang, 'LEFTPANE');
	echo('<div id="navpane"><p>'); 
	printf($literals['LP_WELCOME'],$_SESSION['session_user']);
	echo('</p><form action="#" method="post"><label for="db">'.$literals['LP_LDATABASE'] .' <select name="db" onchange="ndb = this.value; loadDb();"><option value="">' . $literals['LP_SELDB'] . '</option>');	//L10N
//	$qr = mysql_query("SHOW DATABASES");
//	while($db = mysql_fetch_array($qr)) {
//		if($db['Database'] != 'HypatiaDB' && $db['Database'] != 'mysql')
	echo(listDbs('<option value="%1$s">%1$s</option>', $_SESSION['current_db'], '<option value="%1$s" selected="selected">%1$s</option>'));
//	}
	echo('</select></label></form><div id="lptablelist">');
	if($_SESSION['current_db'] != '') {	//get the tables if a database is selected
		echo('<ul>');
		echo(listTables('<li><a href="browse.php?database=' . $_SESSION['current_db'] . '&amp;table=%1$s">%1$s</a></li>', $_SESSION['current_db']));
		echo('</ul>');
	}
	echo('</div></div>');
}

// authenticate_user	-- authenticates a user and sets appropriate session variables
function authenticate_user($username, $password) {
	//username and password are assumed to be unsafe (i.e, not scrubbed by mysql_escape_string
	//or similar)
	$login_name = mysql_escape_string($username);
	$login_password = mysql_escape_string($password);
	mysql_select_db('HypatiaDB') or die("Couldn't select database HypatiaDB");
	$login_query = "SELECT status
			FROM users
			WHERE username = '$login_name' AND password ='$login_password'";
	($login_result = mysql_query($login_query)) or die ("login_query unsuccessful");
	if(mysql_num_rows($login_result) == 0) {
		//Wrong username/password
		return false;
	} else {
		//Correct password. Log them in.
		$_SESSION['session_user'] = $login_name;
		$_SESSION['session_user_status'] = mysql_result($login_result,0,'status');
		$_SESSION['session_user_password'] = $login_password;
		$_SESSION['current_db'] = '';
		return true;
	}
}


//prints out the "I don't know which database/table
//to use" form. If the database is known, pass the variable
//appropriately, and it will preselect that database
//The target is what it should put into the "action"
//attribute of the form element
// * target 	-- the "action" attribute of the form element
// * database	-- default database in the select box
// * custom	-- optional value to insert right after the opening form tag

function printRequestForm($target, $database = '', $custom = '') {
	$strings = loadStrings('en-au', 'PRQF');
	echo<<<ENDFORM
<form action="$target" method="get" class="standalone lblock">$custom
<p>$strings[PRQ_SELECTDB]</p>
<label for="database">$strings[PRQ_FDATABASE] <select name="database" onchange="indb=this.value;reloadTables();"><option value="">
ENDFORM;
	echo($strings['PRQ_SELDB'] . '</option>');
	if($database == '') {
		echo(listDbs('<option name="%1$s">%1$s</option>'));
	} else {
		echo(listDbs('<option name="%1$s">%1$s</option>', $database, '<option name="%1$s" selected="selected">%1$s</option>'));
	}
	echo<<<ENDFORM
</select></label>
<label for="table">$strings[PRQ_FTABLE]<span id="tbl">
ENDFORM;
	if($database != '') {
		echo('<select name="table">' . listTables('<option name="%1$s">%1$s</option>',$database) . '</select>');
	}
	echo('</span></label><input type="submit" name="confirm" value="' . $strings['PRQ_FSUB'] . '" />
		</form></div>');
	endhtml(); exit(0);
}

//This function echoes appropriate XHTML for the Report Wizard's
//steps.
// * $currentStep 	-- one-based integer indicate the current
//			   step in the report
// * $reportId		-- the report's unique id


function getReportSteps($currentStep, $reportId) {
	global $lang;
	$literals = loadStrings($lang, 'RPTWIZARDS');
	echo('<div id="rptsteps"><h2>' . $literals['RPTW_STEPSTITLE'] . '</h2><ol>');
	echo('<li>' . (($currentStep != 1) ? '<form action="report.php" method="post"><input type="hidden" name="report_id" value="' . $reportId . '" /><input type="submit" value="' . $literals['RPTW_STEP1'] . '" /></form>' : $literals['RPTW_STEP1']) . '</li>');
	echo('<li>' . (($currentStep != 2) ? '<form action="report2.php" method="post"><input type="hidden" name="report_id" value="' . $reportId . '" /><input type="submit" value="' . $literals['RPTW_STEP2'] . '" /></form>' : $literals['RPTW_STEP2']) . '</li>');
	echo('<li>' . (($currentStep != 3) ? '<form action="report3.php" method="post"><input type="hidden" name="report_id" value="' . $reportId . '" /><input type="submit" value="' . $literals['RPTW_STEP3'] . '" /></form>' : $literals['RPTW_STEP3']) . '</li>');
	echo('<li>' . (($currentStep != 4) ? '<form action="report4.php" method="post"><input type="hidden" name="report_id" value="' . $reportId . '" /><input type="submit" value="' . $literals['RPTW_STEP4'] . '" /></form>' : $literals['RPTW_STEP4']) . '</li>');
	echo('<li>' . (($currentStep != 5) ? '<form action="report5.php" method="post"><input type="hidden" name="report_id" value="' . $reportId . '" /><input type="submit" value="' . $literals['RPTW_STEP5'] . '" /></form>' : $literals['RPTW_STEP5']) . '</li>');
	echo('</ol></div>');
}

//Gets the human readable version of the output of the operator enum
//in the reports table
//
// * $operator		the operator
// * $negative		is this a negative operator?
function getFriendlyOperator($operator, $positive) {
	global $lang;
	$literals = loadStrings($lang, 'GETFOP');
	switch($operator) {
//'equal','lessthan','greaterthan','like','rlike','contains','between'
		case 'equal':
			return ($positive ? $literals['GF_EQUAL'] : $literals['GF_NOTEQUAL']);
		case 'lessthan':
			return ($positive ? $literals['GF_LT'] : $literals['GF_GTE']);
		case 'greaterthan':
			return ($positive ? $literals['GF_GT'] : $literals['GF_LTE']);
		case 'like':
			return ($positive ? $literals['GF_LIKE'] : $literals['GF_NOTLIKE']);
		case 'rlike':
			return ($positive ? $literals['GF_RLIKE'] : $literals['GF_NOTRLIKE']);
		case 'contains':
			return ($positive ? $literals['GF_CONTAINS'] : $literals['GF_NOTCONTAINS']);
		case 'between':
			return ($positive ? $literals['GF_BETWEEN'] : $literals['GF_NOTBETWEEN']);
	}
}

function getMySQLOperator($operator) {
	switch($operator) {
		case 'equal':
			return '=';
		case 'lessthan':
			return '<';
		case 'greaterthan':
			return '>';
		case 'like':
			return 'LIKE';
		case 'rlike':
			return 'RLIKE';
		case 'contains':
			return 'LIKE';
		case 'between':
			return 'BETWEEN';
	}
}

// This function builds an SQL query a specific report
// * $report_id		-- the report id from which to build the sql query

function buildReportSQL($report_id) {
	//Get the fields
	($fields = mysql_query("SELECT tbl,col FROM report_fields WHERE report = $report_id")) or die(mysql_error());
	$tbl = "";
	$select_fields = array();
	while($field = mysql_fetch_array($fields)) {
		if($tbl == "") {
			$tbl = $field['tbl'];
			$select_fields[] = $field['col'];
		} else if($tbl == $field['tbl']) {
			$select_fields[] = $field['col'];
		} //else, it uses a differnt table, and we don't support joins (yet)
	}

	//Get the conditions
	($conditions = mysql_query("SELECT report_fields.col as `lvalue`, report_conditions.rvalue, report_conditions.operator, report_conditions.positive FROM report_conditions, report_fields WHERE report_conditions.report = $report_id AND report_fields.id = report_conditions.lvalue") or die(mysql_error()));
	$select_conditions = array();
	while($c = mysql_fetch_array($conditions)) {
		$sc = '(' .
			($c['positive'] == 1 ? '' : 'NOT ') .
			$c['lvalue'] . ' ' . getMySQLOperator($c['operator']) . ' ';
		if($c['operator'] == 'contains') {
			$sc .= '"%' . mysql_real_escape_string($c['rvalue']) . '%"';
		} else {
			$sc .= '"' . mysql_real_escape_string($c['rvalue']) . '%"';
		}
		$sc .= ')';
		$select_conditions[] = $sc;
	}

	//And, finally, get the sort conditions
	($sorts = mysql_query("SELECT report_fields.col as `field`, report_sorts.type, report_sorts.priority FROM report_sorts, report_fields WHERE report_sorts.report = $report_id AND report_fields.id = report_sorts.field") or die(mysql_error()));

	$select_sorts = array();
	while($s = mysql_fetch_array($sorts)) {
		$select_sorts[$s['priority'] - 1] = "$s[field] $s[type]";		//this, incidentally, auto-sorts
	}


	//Now, we build the query
	$select = "SELECT " . implode(', ', $select_fields) . " FROM $tbl ";

	if(count($select_conditions) != 0)
		$select .= "WHERE " . implode(' AND ', $select_conditions);

	if(count($select_sorts) != 0)
		$select .= ' ORDER BY ' . implode(', ', $select_sorts);

	return $select;
}

function printAuthError() {	//prints an "unauthorised" error and exits for you. Call this after menu(), before mainpane
	global $lang;
	$literals = loadStrings($lang, 'UNAUTH');
	echo('<div id="mainpane">');
	printError($literals['UNAUTH_NEEDADMIN']);
	die();	//and we're done
}

function printError($errorstr) {	//print error and die
	echo('<p class="alert">' . $errorstr . '</p></div>');		//</div> for mainpane
	endhtml();
	die();
}

function getRowCount($db, $tbl) {
	return intval(mysql_result(mysql_query("SELECT COUNT(*) FROM `$db`.`$tbl`"), 0, 0));
}

function generateInputField($row, $name, $defaultval = "") {
	if(substr($row[1],0,4) == "enum") {
		$retval = "<select name=\"$name\">";
		//get the values
		$values = explode(',', substr($row[1], 5, -1));
		foreach($values as $value) {
			$value = substr($value, 1, -1);
			if($value == $defaultval) {
				$retval .= '<option selected="selected" value="' . htmlspecialchars($value, 1, -1) . '">' . htmlspecialchars($value, 1, -1) . '</option>';
			} else {
				$retval .= '<option value="' . htmlspecialchars($value) . '">' . htmlspecialchars($value) . '</option>';
			}
		}
		return ($retval . '</select>');
	} elseif(is_int(strpos($row[5],'auto_increment'))) {
		return "(auto)<input type=\"hidden\" name=\"" . htmlspecialchars($name) . "\" value=\"" . htmlspecialchars($defaultval) . "\" />";
	} else {
		if($defaultval == "") {
			$defaultval = $row[4];
			if($defaultval=="NULL")
				$defaultval = "";
		}
		return "<input type=\"text\" name=\"$name\" value=\"$defaultval\" />";
	}
}

?>
Return current item: HypatiaDB