Location: PHPKode > projects > WaterFlea Database Maintenance Tool > waterflea-0.6-beta/include/Admin.php
<?php

/*#####################################################################################

WaterFlea - Database Maintenance Tool
Copyright (C) Benjamin Rafael F. Intal

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, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

WaterFlea project site is at http://www.sourceforge.net/projects/waterflea/
WaterFlea website is at http://waterflea.sourceforge.net/

If you have questions or suggestions, please visit the said URLs above,
or you could contact me via email at <hide@address.com> - just mention in the
WaterFlea in the subject and what it's all about.

#######################################################################################*/


class Admin
{
	/*
		DB CONNECTIVITY
	*/

        function connect()
        {
                //connect to mysql
                $db_link = mysql_connect(DB_HOSTNAME . ':' . DB_PORT, DB_USERNAME, DB_PASSWORD);
                if (!$db_link)
                {
                        die ("Error, MySQL is not activated or your configuration is invalid: " . mysql_error());
                }

                //connect to databse
                $db_selected = mysql_select_db(DB_DATABASE, $db_link);
                if (! $db_selected)
                {
                        die ("Error connecting to database: " . mysql_error());
                }
        }

        function executeSQL ($query)
        {
                $this->connect();
                return $result = mysql_query($query) or die(mysql_error());
        }

	/*
		PRIVATE FUNCTIONS
	*/

	// gets the name of the table where usernames and passwords of the admins are located
	function getAdminTable ()
	{
		if (defined("ADMIN_TABLE"))	
		{
			return ADMIN_TABLE;
		}
		else
		{
			return "admin";
		}
	}

	// gets the folder where the uploaded files are to be placed
	function getUploadFolder ()
	{
		if (defined("UPLOAD_FOLDER"))	
		{
			return UPLOAD_FOLDER;
		}
		else
		{
			return "";
		}
	}

	// gets the admin username field name in the admin table
	function getAdminUser ()
	{
		if (defined("ADMIN_FIELD_USER"))	
		{
			return ADMIN_FIELD_USER;
		}
		else
		{
			return "user";
		}
	}

	// gets the admin password field name in the admin table
	function getAdminPass ()
	{
		if (defined("ADMIN_FIELD_PASS"))	
		{
			return ADMIN_FIELD_PASS;
		}
		else
		{
			return "_password";
		}
	}

	// gets the admin access type field name in the admin table
	function getAdminAccess ()
	{
		if (defined("ADMIN_FIELD_ACCESS"))	
		{
			return ADMIN_FIELD_ACCESS;
		}
		else
		{
			return "";
		}
	}

	/*
		MAIN FUNCTIONS
	*/

	// $values: array. $values[$i][0] = field name $values[$i][1] = field row value
	function delRow($table, $values)
	{
		if (count($values) == 0)
		{
			return false;
		}
		$query = "DELETE FROM $table WHERE ";
		foreach ($values as $val)
		{
			$query .= "$val[0] = '$val[1]' AND ";
		}
		$query = substr($query, 0, strlen($query)-4);
                $result = mysql_query($query) or die(mysql_error());
		return true;
	}

	function getUploadError($code)
	{
		$firstText = "Error during upload! Server returned the following error: \\n\\n";
                $errorCodes = array(
                0=>"There is no error, the file uploaded with success",
                1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
                2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                3=>"The uploaded file was only partially uploaded",
                4=>"No file was uploaded",
                6=>"Missing a temporary folder",
		7=>"File is of an invalid format",
		8=>"File exceeds maximum allowed filesize"
                );
		$firstText .= "-  $errorCodes[$code]";
		return $firstText;
	}

	// checks if file being uploaded is valid
	function checkFileBeingUploaded($error, $type, $size, $uploadSupportedFileFormat, $uploadMaxFileSize)
	{
		settype ($error, "int");

		// if upload already has an error
                if ($error != 0)
                {
			return $error;
                }

                // check for type
                $formats = '';
                foreach ($uploadSupportedFileFormat as $f)
                {
                	$formats .= $f .", ";
                }
                $formats = substr($formats, 0, strlen($formats)-2);
                if (strpos($formats, $type) === false)
                {
			return 7;
                }

		// check for size
                $temp = $size;
                settype ($temp, "int");
                if ($temp > $uploadMaxFileSize)
                {
			return 8;
                }

		// no error
		return 0;
	}

	// returns an array containing all the fields which are primary keys in the table
	function getKeys($table)
	{
		$this->connect();
                $result = mysql_query("SHOW FIELDS IN $table") or die(mysql_error());
                $arr = array();
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
                        $arr[] = $row;
                }
		$arr2 = array();
		foreach ($arr as $elem)
		{
			if ($elem['Key'] == 'PRI')
			{
				$arr2[] = $elem['Field'];
			}
		}
                return $arr2;
	}

	// gets the total number of display pages of the given table according to the number-of-rows to display
	function getPages($table, $number=10)
	{
		$this->connect();
		$result = mysql_query("SELECT * FROM $table") or die(mysql_error());
		$num = mysql_num_rows($result);
		$num = $num / $number;
		if ($num > floor($num))
		{
			return floor($num)+1;
		}
		return floor($num);
	}

	// returns an array containing all the rows of the given table
        function getRows($table, $orderby='none', $orderasc='none', $page=0, $number=10)
        {
                $this->connect();
		$query = "SELECT * FROM $table ";
		if ($orderby != 'none')
		{
			$query .= "ORDER BY $order ";
			if ($orderasc != 'none' && strtoupper($orderasc) == 'DESC')
			{
				$query .= "DESC ";
			}
			else
			{
				$query .= "ASC ";
			}
		}
		settype($page, 'int');
		settype($number, 'int');
		$firstRow = $page * $number;
                $result = mysql_query("SELECT * FROM $table LIMIT $firstRow, $number") or die(mysql_error());
                $arr = array();
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
                        $arr[] = $row;
                }
                return $arr;
        }

	// returns all an array containing all the tables inside the database
        function getTables()
        {
                $this->connect();
                $result = mysql_query("SHOW TABLES") or die(mysql_error());
                $arr = array();
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
                        $arr[] = $row;
                }
                return $arr;
        }

	// returns all an array containing all the fields inside the table
        function getTableFields($table)
        {
                $this->connect();
                $result = mysql_query("SHOW FIELDS IN $table") or die(mysql_error());
                $arr = array();
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
                        $arr[] = $row;
                }
                return $arr;
        }

	// $values: array. $values[$i][0] = field name $values[$i][1] = field row value
	function saveRow($table, $values)
	{
		if (count($values) == 0)
		{
			return false;
		}
		$query = "INSERT INTO $table ";
		$fields = '';
		$vals = '';
		foreach ($values as $val)
		{
			// check for current time stamps
			// check for passwords
			$fields .= "$val[0], ";
			if (strstr(strtolower($val[1]), 'password(') !== false || strstr(strtolower($val[1]), 'password (') !== false)
			{
				$vals .= "$val[1], ";	
			}
			else
			{
				$vals .= "'$val[1]', ";	
			}
		}
		$fields = substr($fields, 0, strlen($fields)-2);
		$vals = substr($vals, 0, strlen($vals)-2);
		$query .= "( $fields ) VALUES ( $vals )";
                $result = mysql_query($query) or die(mysql_error());
		return true;
	}

	// uploads a file and returns filename of uploaded file or an empty string if uploading failed
	function uploadFile ($tmp, $filename)
	{
		// get & fix folder
		$folder = $this->getUploadFolder();
		if (substr($folder,strlen($folder)-1,1) != '/' && $folder != '') 
		{
			$folder .= '/';
		}
		// create random filename
		$checker = 1;
		while ($checker == 1)
		{
			$randfile = rand(10000,99999);
			if (! file_exists($folder.$randfile))
			{
				$checker = 0;
			}
			else
			{	
				$checker = 1;
			}
		}
		// get extension of file
		$newFilename = $randfile . substr($filename,strpos($filename,'.'));
		// move file
		if (move_uploaded_file($tmp, $folder.$newFilename)) 
		{
			return $folder.$newFilename;
		}
		else
		{
			return "";
		}
	}

	/*
		TABLE / FIELD PROPERTY FUNCTIONS
	*/
	
	// returns an array containing all the properties of all the fields in the table
	function getFieldProperties($table)
	{
		$temp = array();
                $this->connect();
                $result = mysql_query("SHOW FIELDS IN $table") or die(mysql_error());
                $arr = array();
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
                        $arr[] = $row;
                }
                $arr2 = array();
		$mysqlFetchedArray = $arr;
		$getProperties = false;
		include ('_DbProperties.php');
		return $arr;
	}

	// returns an array containing all the properties specified in the _DbProperties.php file
	function getProperties ()
	{
		$getProperties = true;
		include ('_DbProperties.php');
		return array($propertyNames,$properties);
	}

	// get enumeration choices
	function getEnumChoices ($table, $field)
	{
		$this->connect();
                $result = mysql_query("SHOW FIELDS IN $table") or die(mysql_error());
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
			if ($row['Field'] == $field)
			{
				$temp = $row;
				break;
			}
                }
		if (isset($temp))
		{
			if (strpos($temp['Type'],'enum(') !== false)
			{
				$s = substr(substr($temp['Type'],5+1),0,-1-1);
				$s = explode ("','",$s);
				return $s;
			}
			return false;
		}
		return false;
	}

	// 
	function isFieldEnum ($tableProperties, $field)
	{
		if (isset($tableProperties['Enumerations']))
		{
		        foreach ($tableProperties['Enumerations'] as $f)
	        	{
		                if ($field == $f)
		                {
        		                return true;
                		}
		        }
        		return false;
		}
		return false;
	}

	// 
	function isFieldUploadFile ($tableProperties, $field)
	{
		if (isset($tableProperties['FileUploads']))
		{
		        foreach ($tableProperties['FileUploads'] as $f)
	        	{
		                if ($field == $f)
		                {
        		                return true;
                		}
		        }
        		return false;
		}
		return false;
	}

	//
	function isFieldEditable ($tableProperties, $field)
	{
	        foreach ($tableProperties['uneditableFields'] as $uneditable)
        	{
	                if ($field == $uneditable)
	                {
        	                return false;
                	}
	        }
        	return true;
	}

	/*
		CONFIG CHECKING FUNCTIONS
	*/

        function checkAdmin()
        {
		$this->connect();
                $result = mysql_query("SELECT * FROM ". ADMIN_TABLE);
		$num = mysql_num_rows($result);
		if ($num == 0)
		{
			return "There are no existing administrators in the database!";
                }
		return true;
	}

        function checkAdminPass()
        {
		$this->connect();
                $result = mysql_query("SHOW FIELDS IN ". ADMIN_TABLE);
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
			if ($row['Field'] == ADMIN_FIELD_PASS)
			{
				return true;
			}
                }
		return "Admin table in database does not have a PASSWORD field!";
	}

        function checkAdminTable()
        {
		$this->connect();
                $result = mysql_query("SHOW TABLES");
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
			if ($row[0] == ADMIN_TABLE)
			{
				return true;
			}
                }
		return "Database requires one 'ADMINISTRATOR' table!";
	}

        function checkAdminUser()
        {
		$this->connect();
                $result = mysql_query("SHOW FIELDS IN ". ADMIN_TABLE);
                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
                {
			if ($row['Field'] == ADMIN_FIELD_USER)
			{
				return true;
			}
                }
		return "Admin table in database does not have a USERNAME field!";
	}

        function checkConnect()
        {
                //connect to mysql
                if (mysql_connect(DB_HOSTNAME . ':' . DB_PORT, DB_USERNAME, DB_PASSWORD) == false)
                {
                        return "Could not connect to MySQL!";
                }
		return true;
	}

	function checkDatabase()
	{
                //connect to databse
                $db_link = mysql_connect(DB_HOSTNAME . ':' . DB_PORT, DB_USERNAME, DB_PASSWORD);
                if (mysql_select_db(DB_DATABASE, $db_link) == false)
                {
                	return "Coult not connect to the database";
                }
		return true;
        }

        function checkTables()
        {
		$this->connect();
                $result = mysql_query("SHOW TABLES");
		$num = mysql_num_rows($result);
		if ($num == 0)
		{
			return "There are no tables in the database!";
                }
		return true;
	}

	function checkUploadable()
	{
		if (defined("UPLOAD_FOLDER"))
		{
			if (! is_writable (UPLOAD_FOLDER))
			{
				return "NO PERMISSION to write in the specified upload folder!";
			}
		}
		return true;
	}

	/*
		MISC FUNCTIONS
	*/

	// returns the current datetime
	function getDateNow()
	{
		// format YYYY-MM-DD HH:MM:SS
		return date("Y-m-d H:i:s");
	}

	// checks for correct login, returns true if successfully logged in, or false if not
	function login($user, $pass)
	{
		$this->connect();
		$adminTable = $this->getAdminTable();
		$adminUser = $this->getAdminUser();
		$adminPass = $this->getAdminPass();
		$adminAccess = $this->getAdminAccess();
		$result = mysql_query("SELECT * FROM $adminTable WHERE $adminUser='$user' AND $adminPass=password('$pass')") or die(mysql_error());
		$num = mysql_num_rows($result);
		if ($num >= 1)
		{
			if ($adminAccess = "")
			{
				return array('all');
			}
	                $arr = array();
	                while ($row = mysql_fetch_array($result, MYSQL_BOTH))
	                {
	                        $arr[] = $row;
	                }
			if (isset ($arr[0]) && isset($arr[0][$adminAccess]))
			{
				return $adminAccessType[$arr[0][$adminAccess]];
			}
			return array('all');
		}
		return false;
	}

	// returns a trimmed string with the last characters as three periods
	function trimString($str, $len=40)
	{
		if (strlen($str) > $len)
		{
			return substr($str,0,$len)."...";
		}
		return $str;
	}

	/*
		END OF FUNCTION LIST
	*/
}
?>
Return current item: WaterFlea Database Maintenance Tool