<?php

function manifest_cache_update($root_dir_joomla)
{
	
	$db_id = 'main';
	mysql_db_connect(get_db_address($db_id),
			get_db_login($db_id),
			get_db_password($db_id),
			get_db_name($db_id));

	//Front updates
	manifest_cache_updateExtensions($root_dir_joomla.'/components', 0, 'com_'); //OK
	manifest_cache_updateExtensions($root_dir_joomla.'/language', 0, ''); //OK
	manifest_cache_updateExtensions($root_dir_joomla.'/modules', 0, ''); //OK
	manifest_cache_updatePlugins($root_dir_joomla.'/plugins', ''); //OK
	manifest_cache_updateExtensions($root_dir_joomla.'/templates', 0, '', 'templateDetails'); //OK

	//Admin Updates
	manifest_cache_updateExtensions($root_dir_joomla.'/administrator/components', 1, 'com_'); //OK
	manifest_cache_updateExtensions($root_dir_joomla.'/administrator/language', 1, ''); //OK
	manifest_cache_updateLibraries($root_dir_joomla.'/administrator/manifests/libraries');
	manifest_cache_updateExtensions($root_dir_joomla.'/administrator/modules', 1, ''); //OK
	manifest_cache_updateExtensions($root_dir_joomla.'/administrator/templates', 1, '', 'templateDetails'); //OK

	//Joomla File
	manifest_cache_updateJoomlaFileType($root_dir_joomla.'/administrator/manifests/files/joomla.xml');

}

function manifest_cache_updateExtensions($folderPath, $client_id, $prefix='', $defaultDetailsFile='')
{
	$extensions = manifest_cache_getFolders($folderPath);
	foreach ($extensions as $extension)
	{
		$detailsFile = str_replace($prefix, '', $extension);
		if($defaultDetailsFile){
			$detailsFile=$defaultDetailsFile;
		}
		if (file_exists($folderPath . '/' . $extension . '/' . $detailsFile. '.xml'))
		{
			$manifest_details = manifest_cache_parseXMLInstallFile($folderPath . '/' . $extension . '/' . $detailsFile . '.xml');
			manifest_cache_updateDBValue($manifest_details, $client_id);
		}
	}
}

function manifest_cache_updatePlugins($folderPath)
{
	$folder_list = manifest_cache_getFolders($folderPath);

	foreach ($folder_list as $folder)
	{
		$file_list = manifest_cache_getItemsFiles($folderPath . '/' . $folder, '\.xml$');
		foreach ($file_list as $file)
		{
			$manifest_details = manifest_cache_parseXMLInstallFile($folderPath . '/' . $folder . '/' . $file);
			manifest_cache_updateDBValue($manifest_details, 0);
		}
		$folder_list_in = manifest_cache_getFolders($folderPath .'/' . $folder);
		foreach ($folder_list_in as $plugin_folder)
		{
			$file_list = manifest_cache_getItemsFiles($folderPath . '/' . $folder . '/' . $plugin_folder, '\.xml$');
			foreach ($file_list as $file)
			{
				$manifest_details = manifest_cache_parseXMLInstallFile($folderPath . '/' . $folder . '/' . $plugin_folder . '/' . $file);
				manifest_cache_updateDBValue($manifest_details, 0);
			}
		}

	}
}

function manifest_cache_updateLibraries($folderPath)
{
	$file_list = manifest_cache_getItemsFiles($folderPath, '\.xml$', true);

	foreach ($file_list as $file)
	{
		$manifest_details = manifest_cache_parseXMLInstallFile($folderPath . '/' . $file);
		manifest_cache_updateDBValue($manifest_details, 0);
	}
}

function manifest_cache_updateJoomlaFileType($folderPath)
{
	$manifest_details = manifest_cache_parseXMLInstallFile($folderPath);
	manifest_cache_updateDBJoomlaFileType($manifest_details);
}

function manifest_cache_getFolders($path)
{
	$filter = '.';
	$recurse = false;
	$full = false;
	$exclude = array('.svn', 'CVS', '.DS_Store', '__MACOSX');
	$excludefilter = array('^\..*');
	// Is the path a folder?
	if (!is_dir($path))
	{
		return false;
	}

	// Compute the excludefilter string
	if (count($excludefilter))
	{
		$excludefilter_string = '/(' . implode('|', $excludefilter) . ')/';
	}
	else
	{
		$excludefilter_string = '';
	}

	// Get the folders
	$arr = manifest_cache_getItems($path, $filter, $recurse, $full, $exclude, $excludefilter_string, false);

	// Sort the folders
	asort($arr);
	return array_values($arr);
}

function manifest_cache_getItems($path, $filter, $recurse, $full, $exclude, $excludefilter_string, $findfiles)
{
	@set_time_limit(ini_get('max_execution_time'));

	$arr = array();

	// Read the source directory
	if (!($handle = @opendir($path)))
	{
		return $arr;
	}

	while (($file = readdir($handle)) !== false)
	{
		if ($file != '.' && $file != '..' && !in_array($file, $exclude)
				&& (empty($excludefilter_string) || !preg_match($excludefilter_string, $file)))
		{
			// Compute the fullpath
			$fullpath = $path . '/' . $file;

			// Compute the isDir flag
			$isDir = is_dir($fullpath);

			if (($isDir xor $findfiles) && preg_match("/$filter/", $file))
			{
				// (fullpath is dir and folders are searched or fullpath is not dir and files are searched) and file matches the filter
				if ($full)
				{
					// Full path is requested
					$arr[] = $fullpath;
				}
				else
				{
					// Filename is requested
					$arr[] = $file;
				}
			}
			if ($isDir && $recurse)
			{
				// Search recursively
				if (is_int($recurse))
				{
					// Until depth 0 is reached
					$arr = array_merge($arr, manifest_cache_getItems($fullpath, $filter, $recurse - 1, $full, $exclude, $excludefilter_string, $findfiles));
				}
				else
				{
					$arr = array_merge($arr, manifest_cache_getItems($fullpath, $filter, $recurse, $full, $exclude, $excludefilter_string, $findfiles));
				}
			}
		}
	}
	closedir($handle);
	return $arr;
}

function manifest_cache_getItemsFiles($path, $filter = '.', $recurse = false)
{
	$full = false;
	$exclude = array('.svn', 'CVS', '.DS_Store', '__MACOSX');
	$excludefilter = array('^\..*', '.*~');
	// Is the path a folder?
	if (!is_dir($path))
	{
		return false;
	}

	// Compute the excludefilter string
	if (count($excludefilter))
	{
		$excludefilter_string = '/(' . implode('|', $excludefilter) . ')/';
	}
	else
	{
		$excludefilter_string = '';
	}

	// Get the files
	$arr = manifest_cache_getItems($path, $filter, $recurse, $full, $exclude, $excludefilter_string, true);

	// Sort the files
	asort($arr);
	return array_values($arr);
}

function manifest_cache_parseXMLInstallFile($path)
{
	// Read the file to see if it's a valid component XML file
	$xml = simplexml_load_file($path);
	if (!$xml)
	{
		return false;
	}

	// Check for a valid XML root tag.

	// Extensions use 'extension' as the root tag.  Languages use 'metafile' instead

	if ($xml->getName() != 'extension' && $xml->getName() != 'metafile')
	{
		unset($xml);
		return false;
	}

	$data = array();

	$data['name'] = (string) $xml->name;

	// Check if we're a language. If so use metafile.
	$data['type'] = $xml->getName() == 'metafile' ? 'language' : (string) $xml->attributes()->type;

	$data['creationDate'] = ((string) $xml->creationDate) ? (string) $xml->creationDate : 'Unknown';
	$data['author'] = ((string) $xml->author) ? (string) $xml->author : 'Unknown';

	$data['copyright'] = (string) $xml->copyright;
	$data['authorEmail'] = (string) $xml->authorEmail;
	$data['authorUrl'] = (string) $xml->authorUrl;
	$data['version'] = (string) $xml->version;
	$data['description'] = (string) $xml->description;
	$data['group'] = (string) $xml->group;

	return $data;
}

function manifest_cache_updateDBValue($manifest_details, $client_id)
{
	$db_id='main';
	$db_prefix = get_db_prefix($db_id);
	
	$extension_name=$manifest_details['name'];
	$extension_type=$manifest_details['type'];
	$manifest_cache_value=json_encode($manifest_details);

	$manifest_cache_value = manifest_cache_escape($manifest_cache_value);

	$sql = "UPDATE ".$db_prefix."jos_extensions SET `manifest_cache` = '".$manifest_cache_value."' WHERE `name`='".$extension_name."' AND `type`='". $extension_type."' AND `client_id`=".$client_id;

	$result = mysql_query($sql);
}

function manifest_cache_updateDBJoomlaFileType($manifest_details)
{
	$db_id='main';
	$db_prefix = get_db_prefix($db_id);
	
	$extension_name=$manifest_details['name'];
	$manifest_cache_value=json_encode($manifest_details);

	$manifest_cache_value = manifest_cache_escape($manifest_cache_value);

	$sql = "UPDATE ".$db_prefix."jos_extensions SET `name` = '" .$extension_name. "', `manifest_cache` = '".$manifest_cache_value."' WHERE `extension_id`=700";

	$result = mysql_query($sql);
}

function manifest_cache_escape($text, $extra = false)
{

	$result = mysql_real_escape_string($text);

	if ($extra)
	{
		$result = addcslashes($result, '%_');
	}

	return $result;
}

?>
