<?php

defined('WikyBlog') or die("Not an entry point...");
	
class checkPrivs{
	function isGranted(){
		if( !checkPrivs::isGrantedCheck() ){
			message('To Continue with this script, you will need to grant Alter, Create, and Index privileges for your MySQL database user.');
			return false;
		}
		return true;
	}
	function isGrantedCheck($which=array('CREATE','ALTER','INDEX')){
		global $dbname;
		
		
		$query = 'SHOW GRANTS;';
		$result = @mysql_query( $query );
		if( !$result ){
			message('<b>Warning:</b> The script could not determine the MySQL user privileges. Make sure your database has Alter, Create and Index privileges before continuing.');
			return true;
		}
		$num = mysql_num_rows($result);
		if( $num < 1 ){
			return false;
		}
		
		$num = mysql_num_rows($result);
		if( $num < 1 ){
			return false;
		}
		
		$privs = false;
		while( $row = mysql_fetch_assoc($result) ){
			$temp = current($row);
			$temp = substr($temp,6); 			//strip "GRANT "
			
			$pos = strpos($temp,' ON ');
			$tempPrivs = substr($temp,0,$pos);
			
			$temp = substr($temp,$pos+4);		//strip -pivs- and " ON "
			$pos = strpos($temp,' TO ');
			$tempON = substr($temp,0,$pos);
			$tempON = str_replace(array('\_','\%'),array('_','%'),$tempON);
			
			//message($tempON.' :: '.$tempPrivs);
			if( $tempON == '`'.$dbname.'`.*'){
				$privs = $tempPrivs;
			}elseif( !$privs && $tempON == '*.*'){
				$privs = $tempPrivs;
			}
		}
		
		//
		//	test the found privileges
		//
		
			if( !$privs ){
				return true;
			}
			if( $privs  == 'ALL PRIVILEGES' ){
				return true;
			}
			if( $privs == 'USAGE' ){
				return false;
			}
			foreach($which as $priv){
				if( strpos($privs,$priv) === false ){
					return false;
				}
			}
			return true;
	}
}