PageRenderTime 43ms CodeModel.GetById 33ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/_mmServerScripts/mysql.php

https://github.com/AvinashMudunuri/Modernize
PHP | 438 lines | 330 code | 66 blank | 42 comment | 58 complexity | cacc9e267f1942d1c5283a6cca9f07c6 MD5 | raw file
  1<?php
  2// If this file is not included from the MMHTTPDB possible hacking problem.
  3if (!function_exists('create_error')){
  4	die();
  5}
  6
  7define('MYSQL_NOT_EXISTS', create_error("Your PHP server doesn't have the MySQL module loaded or you can't use the mysql_(p)connect functions."));
  8define('CONN_NOT_OPEN_GET_TABLES', create_error('The Connection could not be opened when trying to retrieve the tables.'));
  9define('CONN_NOT_OPEN_GET_DB_LIST', create_error('The Connection could not be opened when trying to retrieve the database list.'));
 10			 
 11if (!function_exists('mysql_connect') || !function_exists('mysql_pconnect') || !extension_loaded('mysql')){
 12	echo MYSQL_NOT_EXISTS;
 13	die();
 14}
 15
 16// Now let's handle the crashes or any other PHP errors that we can catch
 17function KT_ErrorHandler($errno, $errstr, $errfile, $errline) { 
 18	global $f, $already_sent;
 19	$errortype = array ( 
 20		1   =>  "Error", 
 21		2   =>  "Warning", 
 22		4   =>  "Parsing Error", 
 23		8   =>  "Notice", 
 24		16  =>  "Core Error", 
 25		32  =>  "Core Warning", 
 26		64  =>  "Compile Error", 
 27		128 =>  "Compile Warning", 
 28		256 =>  "User Error", 
 29		512 =>  "User Warning", 
 30		1024=>  "User Notice",
 31		2048=>  "E_ALL",
 32		2049=>  "PHP5 E_STRICT"
 33	
 34	);
 35	$str = sprintf("[%s]\n%s:\t%s\nFile:\t\t'%s'\nLine:\t\t%s\n\n", date('d-m-Y H:i:s'),(isset($errortype[@$errno])?$errortype[@$errno]:('Unknown '.$errno)),@$errstr,@$errfile,@$errline);
 36	if (error_reporting() != 0) {
 37			@fwrite($f, $str);
 38			if (@$errno == 2 && isset($already_sent) && !$already_sent==true){
 39				$error = '<ERRORS>'."\n";
 40				$error .= '<ERROR><DESCRIPTION>An Warning Type error appeared. The error is logged into the log file.</DESCRIPTION></ERROR>'."\n";
 41				$error .= '</ERRORS>'."\n";
 42				$already_sent = true;
 43				echo $error;
 44			}
 45	}
 46}
 47if ($debug_to_file){
 48		$old_error_handler = set_error_handler("KT_ErrorHandler");
 49}
 50
 51class MySqlConnection
 52{
 53/*
 54 // The 'var' keyword is deprecated in PHP5 ... we will define these variables at runtime.
 55  var $isOpen;
 56	var $hostname;
 57	var $database;
 58	var $username;
 59	var $password;
 60	var $timeout;
 61	var $connectionId;
 62	var $error;
 63*/
 64	function MySqlConnection($ConnectionString, $Timeout, $Host, $DB, $UID, $Pwd)
 65	{
 66		$this->isOpen = false;
 67		$this->timeout = $Timeout;
 68		$this->error = '';
 69
 70		if( $Host ) { 
 71			$this->hostname = $Host;
 72		}
 73		elseif( preg_match("/host=([^;]+);/", $ConnectionString, $ret) )  {
 74			$this->hostname = $ret[1];
 75		}
 76		
 77		if( $DB ) {
 78			$this->database = $DB;
 79		}
 80		elseif( preg_match("/db=([^;]+);/",   $ConnectionString, $ret) ) {
 81			$this->database = $ret[1];
 82		}
 83		
 84		if( $UID ) {
 85			$this->username = $UID;
 86		}
 87		elseif( preg_match("/uid=([^;]+);/",  $ConnectionString, $ret) ) {
 88			$this->username = $ret[1];
 89		}
 90		
 91		if( $Pwd ) {
 92			$this->password = $Pwd;
 93		}
 94		elseif( preg_match("/pwd=([^;]+);/",  $ConnectionString, $ret) ) {
 95			$this->password = $ret[1];
 96		}
 97	}
 98
 99	function Open()
100	{
101	  $this->connectionId = mysql_connect($this->hostname, $this->username, $this->password);
102		if (isset($this->connectionId) && $this->connectionId && is_resource($this->connectionId))
103		{
104			$this->isOpen = ($this->database == "") ? true : mysql_select_db($this->database, $this->connectionId);
105		}
106		else
107		{
108			$this->isOpen = false;
109		}	
110	}
111
112	function TestOpen()
113	{
114		return ($this->isOpen) ? '<TEST status=true></TEST>' : $this->HandleException();
115	}
116
117	function Close()
118	{
119		if (is_resource($this->connectionId) && $this->isOpen)
120		{
121			if (mysql_close($this->connectionId))
122			{
123				$this->isOpen = false;
124				unset($this->connectionId);
125			}
126		}
127	}
128
129	function GetTables($table_name = '')
130	{
131		$xmlOutput = "";
132		if ($this->isOpen && isset($this->connectionId) && is_resource($this->connectionId)){
133			// 1. mysql_list_tables and mysql_tablename are deprecated in PHP5
134			// 2. For backward compatibility GetTables don't have any parameters
135			if ($table_name === ''){
136					$table_name = @$_POST['Database'];
137			}
138			//added backtick for handling reserved words and special characters
139			//http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
140			$sql = ' SHOW TABLES FROM ' . $this->ensureTicks($table_name) ;
141			$results = mysql_query($sql, $this->connectionId) or $this->HandleException();
142
143			$xmlOutput = "<RESULTSET><FIELDS>";
144
145			// Columns are referenced by index, so Schema and
146			// Catalog must be specified even though they are not supported
147
148			$xmlOutput .= '<FIELD><NAME>TABLE_CATALOG</NAME></FIELD>';		// column 0 (zero-based)
149			$xmlOutput .= '<FIELD><NAME>TABLE_SCHEMA</NAME></FIELD>';		// column 1
150			$xmlOutput .= '<FIELD><NAME>TABLE_NAME</NAME></FIELD>';		// column 2
151
152			$xmlOutput .= "</FIELDS><ROWS>";
153
154			if (is_resource($results) && mysql_num_rows($results) > 0){
155					while ($row = mysql_fetch_array($results)){
156							$xmlOutput .= '<ROW><VALUE/><VALUE/><VALUE>' . $row[0]. '</VALUE></ROW>';	
157					}
158			}
159			$xmlOutput .= "</ROWS></RESULTSET>";
160
161    }
162		return $xmlOutput;
163	}
164
165	function GetViews()
166	{
167		// not supported
168		return "<RESULTSET><FIELDS></FIELDS><ROWS></ROWS></RESULTSET>";
169	}
170
171	function GetProcedures()
172	{
173		// not supported
174		return "<RESULTSET><FIELDS></FIELDS><ROWS></ROWS></RESULTSET>";
175	}
176
177	function GetColumnsOfTable($TableName)
178	{
179		$xmlOutput = "";
180		//added backtick for handling reserved words and special characters
181		//http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
182		$query  = "DESCRIBE ".$this->ensureTicks($TableName);
183		$result = mysql_query($query) or $this->HandleException();
184
185		if ($result)
186		{
187			$xmlOutput = "<RESULTSET><FIELDS>";
188
189			// Columns are referenced by index, so Schema and
190			// Catalog must be specified even though they are not supported
191			$xmlOutput .= "<FIELD><NAME>TABLE_CATALOG</NAME></FIELD>";		// column 0 (zero-based)
192			$xmlOutput .= "<FIELD><NAME>TABLE_SCHEMA</NAME></FIELD>";		// column 1
193			$xmlOutput .= "<FIELD><NAME>TABLE_NAME</NAME></FIELD>";			// column 2
194			$xmlOutput .= "<FIELD><NAME>COLUMN_NAME</NAME></FIELD>";
195			$xmlOutput .= "<FIELD><NAME>DATA_TYPE</NAME></FIELD>";
196			$xmlOutput .= "<FIELD><NAME>IS_NULLABLE</NAME></FIELD>";
197			$xmlOutput .= "<FIELD><NAME>COLUMN_SIZE</NAME></FIELD>";
198
199			$xmlOutput .= "</FIELDS><ROWS>";
200
201			// The fields returned from DESCRIBE are: Field, Type, Null, Key, Default, Extra
202			while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
203			{
204				$xmlOutput .= "<ROW><VALUE/><VALUE/><VALUE/>";
205
206				// Separate type from size. Format is: type(size)
207				if (preg_match("/(.*)\((.*)\)/", $row["Type"], $ret))
208				{
209					$type = $ret[1];
210					$size = $ret[2];
211				}
212				else
213				{
214					$type = $row["Type"];
215					$size = "";
216				}
217
218				// MySQL sets nullable to "YES" or "", so we need to set "NO"
219				$null = $row["Null"];
220				if ($null == "")
221					$null = "NO";
222
223				$xmlOutput .= "<VALUE>" . $row["Field"] . "</VALUE>";
224				$xmlOutput .= "<VALUE>" . $type         . "</VALUE>";
225				$xmlOutput .= "<VALUE>" . $null         . "</VALUE>";
226				$xmlOutput .= "<VALUE>" . $size         . "</VALUE></ROW>";
227			}
228			mysql_free_result($result);
229
230			$xmlOutput .= "</ROWS></RESULTSET>";
231		}
232
233		return $xmlOutput;
234	}
235
236	function GetParametersOfProcedure($ProcedureName, $SchemaName, $CatalogName)
237	{
238		// not supported on MySQL
239		return '<RESULTSET><FIELDS></FIELDS><ROWS></ROWS></RESULTSET>';
240	}
241
242	function ExecuteSQL($aStatement, $MaxRows)
243	{
244		if ( get_magic_quotes_gpc() )
245		{
246				$aStatement = stripslashes( $aStatement ) ;
247		}
248				
249		$xmlOutput = "";
250
251		$result = mysql_query($aStatement) or $this->HandleException();
252		
253		if (isset($result) && is_resource($result))
254		{
255			$xmlOutput = "<RESULTSET><FIELDS>";
256
257			$fieldCount = mysql_num_fields($result);
258			for ($i=0; $i < $fieldCount; $i++)
259			{
260				$meta = mysql_fetch_field($result);
261				if ($meta)
262				{
263					$xmlOutput .= '<FIELD';
264					$xmlOutput .= ' type="'			    . $meta->type;
265					$xmlOutput .= '" max_length="'	. $meta->max_length;
266					$xmlOutput .= '" table="'			  . $meta->table;
267					$xmlOutput .= '" not_null="'		. $meta->not_null;
268					$xmlOutput .= '" numeric="'		  . $meta->numeric;
269					$xmlOutput .= '" unsigned="'		. $meta->unsigned;
270					$xmlOutput .= '" zerofill="'		. $meta->zerofill;
271					$xmlOutput .= '" primary_key="'	. $meta->primary_key;
272					$xmlOutput .= '" multiple_key="'. $meta->multiple_key;
273					$xmlOutput .= '" unique_key="'	. $meta->unique_key;
274					$xmlOutput .= '"><NAME>'			  . $meta->name;
275					$xmlOutput .= '</NAME></FIELD>';
276				}
277			}
278
279			$xmlOutput .= "</FIELDS><ROWS>";
280			$row = mysql_fetch_assoc($result);
281
282			for ($i=0; $row && ($i < $MaxRows); $i++)
283			{
284				$xmlOutput .= "<ROW>";
285
286				foreach ($row as $key => $value)
287				{
288					$xmlOutput .= "<VALUE>";
289					$xmlOutput .= htmlspecialchars($value);
290					$xmlOutput .= "</VALUE>";
291				}
292
293 				$xmlOutput .= "</ROW>";
294				$row = mysql_fetch_assoc($result);
295			}
296
297			mysql_free_result($result);
298
299			$xmlOutput .= "</ROWS></RESULTSET>";
300		}
301				
302		return $xmlOutput;
303	}
304
305	function GetProviderTypes()
306	{
307		return '<RESULTSET><FIELDS></FIELDS><ROWS></ROWS></RESULTSET>';
308	}
309
310	function ExecuteSP($aProcStatement, $TimeOut, $Parameters)
311	{
312		return '<RESULTSET><FIELDS></FIELDS><ROWS></ROWS></RESULTSET>';
313	}
314
315	function ReturnsResultSet($ProcedureName)
316	{
317		return '<RETURNSRESULTSET status=false></RETURNSRESULTSET>';
318	}
319
320	function SupportsProcedure()
321	{	
322		return '<SUPPORTSPROCEDURE status=false></SUPPORTSPROCEDURE>';
323	}
324
325	/*
326	*  HandleException added by InterAKT for ease in database translation answer
327	*/
328	function HandleException()
329	{
330		global $debug_to_file, $f;
331		$this->error = create_error(' MySQL Error#: '. ((int)mysql_errno()) . "\n\n".mysql_error());
332		log_messages($this->error);
333		die($this->error.'</HTML>');
334	}
335
336	function ensureTicks($inputSQL)
337	{
338		$outSQL = $inputSQL;
339		//added backtick for handling reserved words and special characters
340		//http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
341
342		//only add ticks if not already there
343		$oLength = strlen($outSQL);
344		$bHasTick = false;
345		if (($oLength > 0) && (($outSQL[0] == "`") && ($outSQL[$oLength-1] == "`")))
346		{
347			$bHasTick = true;
348		}
349		if ($bHasTick == false)
350		{
351			$outSQL = "`".$outSQL."`";
352		}
353		return $outSQL;
354	}
355
356	function GetDatabaseList()
357	{
358		$xmlOutput = '<RESULTSET><FIELDS><FIELD><NAME>NAME</NAME></FIELD></FIELDS><ROWS>';
359
360		if (isset($this->connectionId) && is_resource($this->connectionId)){
361				$dbList = mysql_list_dbs($this->connectionId);
362				
363				while ($row = mysql_fetch_object($dbList))
364				{
365					$xmlOutput .= '<ROW><VALUE>' . $row->Database . '</VALUE></ROW>';
366				}
367    }else{
368				$this->error = CONN_NOT_OPEN_GET_DB_LIST;
369				return $this->error;
370		}
371		$xmlOutput .= '</ROWS></RESULTSET>';
372
373		return $xmlOutput;
374	}
375
376	function GetPrimaryKeysOfTable($TableName)
377	{
378		$xmlOutput = '';
379		//added backtick for handling reserved words and special characters
380		//http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
381		$query  = "DESCRIBE ".$this->ensureTicks($TableName);
382		$result = mysql_query($query) or $this->HandleException();
383		
384		
385		if ($result)
386		{
387			$xmlOutput = '<RESULTSET><FIELDS>';
388
389			// Columns are referenced by index, so Schema and
390			// Catalog must be specified even though they are not supported
391			$xmlOutput .= '<FIELD><NAME>TABLE_CATALOG</NAME></FIELD>';		// column 0 (zero-based)
392			$xmlOutput .= '<FIELD><NAME>TABLE_SCHEMA</NAME></FIELD>';		// column 1
393			$xmlOutput .= '<FIELD><NAME>TABLE_NAME</NAME></FIELD>';			// column 2
394			$xmlOutput .= '<FIELD><NAME>COLUMN_NAME</NAME></FIELD>';
395			$xmlOutput .= '<FIELD><NAME>DATA_TYPE</NAME></FIELD>';
396			$xmlOutput .= '<FIELD><NAME>IS_NULLABLE</NAME></FIELD>';
397			$xmlOutput .= '<FIELD><NAME>COLUMN_SIZE</NAME></FIELD>';
398
399			$xmlOutput .= '</FIELDS><ROWS>';
400
401			// The fields returned from DESCRIBE are: Field, Type, Null, Key, Default, Extra
402			while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
403			{
404			  if (strtoupper($row['Key']) == 'PRI'){
405  				$xmlOutput .= '<ROW><VALUE/><VALUE/><VALUE/>';
406  
407  				// Separate type from size. Format is: type(size)
408  				if (preg_match("/(.*)\((.*)\)/", $row['Type'], $ret))
409  				{
410  					$type = $ret[1];
411  					$size = $ret[2];
412  				}
413  				else
414  				{
415  					$type = $row['Type'];
416  					$size = '';
417  				}
418  
419  				// MySQL sets nullable to "YES" or "", so we need to set "NO"
420  				$null = $row['Null'];
421  				if ($null == '')
422  					$null = 'NO';
423  
424  				$xmlOutput .= '<VALUE>' . $row['Field'] . '</VALUE>';
425  				$xmlOutput .= '<VALUE>' . $type         . '</VALUE>';
426  				$xmlOutput .= '<VALUE>' . $null         . '</VALUE>';
427  				$xmlOutput .= '<VALUE>' . $size         . '</VALUE></ROW>';
428  			}
429			}
430			mysql_free_result($result);
431
432			$xmlOutput .= '</ROWS></RESULTSET>';
433		}
434		return $xmlOutput;
435	}
436
437}	// class MySqlConnection
438?>