<?php
defined('_JEXEC') or die('Restricted access');
JToolBarHelper::title("Search Source");

//error_reporting(E_ALL);
//ini_set("display_errors", 1);

echo"
<form method='post'>
	Word: <input type='text' name='parola'>
	Db<input type='checkbox' value='db' name='dove'>
	File<input type='checkbox' value='file' name='dove'>
	<input type='submit' value='Search'>
</form>
";

function searchFile($folder, $cerca) 
{
	$folder = rtrim($folder, "/") . '/';
	if ($hd = opendir($folder)) 
	{
		while (false !== ($file = readdir($hd))) 
		{ 
			if($file != '.' && $file != '..') 
			{
				if(is_dir($folder . $file)) 
				{
					searchFile($folder. $file, $cerca);
				} 
				else 
				{
					$leggi=$folder . $file;
					if (!$p_file = fopen($leggi,"r")) 
					{
						echo "<b>Sorry, I can not open the file " . $file . "</b><br />";
					} 
					else 
					{
						$i=1;
						while(!feof($p_file))//ricerca della parola
						{
							$linea = fgets($p_file, 255);
							if(strstr($linea,$cerca))
							{
								echo "String present in " . $folder . $file . " at line " . $i . "<br />";
							}
							$i++;
						}
						fclose($p_file);
					}
				}
			}
		}
		closedir($hd); 
	}
}

function searchDb($parola){
	$app =& JFactory::getApplication();
	$host=$app->getCfg('host');
	$user=$app->getCfg('user');
	$password=$app->getCfg('password');
	$database=$app->getCfg('db');
	
	mysql_connect($host,$user,$password);
	@mysql_select_db($database) or die("Connection error");
	$tabelle=mysql_query("SHOW TABLE STATUS FROM $database");

	while($row=mysql_fetch_row($tabelle)){
		$colonne=mysql_query("SHOW COLUMNS FROM $row[0]");
		$where="";
		while($col=mysql_fetch_array($colonne)){
			if((!is_numeric($parola) && !strstr($col['Type'],"int"))){
				$where.="`".$col['Field']."` LIKE '%".$parola."%' OR ";
			}
		}
		if($where!=""){
			$where=substr($where,0,strlen($where)-3); 
		}else{
			$where="0=1";
		}

		//cerca la chiave primaria
		$pri=mysql_query("SHOW KEYS FROM ".$row[0]." WHERE Key_name = 'PRIMARY'");
		$Rpri=mysql_fetch_array($pri);
		$Rpri=$Rpri['Column_name'];
		if($Rpri==""){$Rpri="*";}
//echo "*** SELECT $Rpri FROM $row[0] WHERE $where <br><br>";
		$res=mysql_query("SELECT $Rpri FROM $row[0] WHERE $where");
		if(mysql_num_rows($res)>0){
			while($Val=mysql_fetch_array($res)){
				echo "String in the table: ".$row[0]." WHERE ".$Rpri."=".$Val[$Rpri]." <br />";
			}
		}
	}
}

if(JRequest::getVar('dove', '', 'post')=="file"){searchFile("../", JRequest::getVar('parola', '', 'post'));}
if(JRequest::getVar('dove', '', 'post')=="db"){searchDb(JRequest::getVar('parola', '', 'post'));}

