CoreFiles by mySites.guru
database.php866 lines, 20,369 bytes, from Joomla_3.0.2-Stable-Full_Package.zip
Raw History Compare with 3.0.1
md5
d226155f038d56c4f9666cd3d488bca7
sha1
41ece49213614143a1bc5d60e6dabdb03672ef96
sha256
ee988eb2039847843a0cc3bd72e25e3ecdb67afa2a46f64d9bb791312d0fef5f
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
<?php
/**
 * @package    Joomla.Installation
 *
 * @copyright  Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
require_once JPATH_INSTALLATION . '/helpers/database.php';

/**
 * Database configuration model for the Joomla Core Installer.
 *
 * @package  Joomla.Installation
 * @since    3.0
 */
class InstallationModelDatabase extends JModelLegacy
{
	static protected $userId = 0;

	/**
	 * Generates the user ID
	 *
	 * @return  integer  The user ID
	 *
	 * @since   3.0
	 */
	protected static function generateRandUserId()
	{
		$session = JFactory::getSession();
		$randUserId = $session->get('randUserId');

		if (empty($randUserId))
		{
			// Create the ID for the root user only once and store in session
			$randUserId = mt_rand(1, 1000);
			$session->set('randUserId', $randUserId);
		}
		return $randUserId;
	}

	/**
	 * @since   3.0
	 */
	public static function resetRandUserId()
	{
		self::$userId = 0;
		$session = JFactory::getSession();
		$session->set('randUserId', self::$userId);
	}

	/**
	 * Retrieves the default user ID and sets it if necessary
	 *
	 * @return  integer  The user ID
	 *
	 * @since   3.0
	 */
	public static function getUserId()
	{
		if (!self::$userId)
		{
			self::$userId = self::generateRandUserId();
		}
		return self::$userId;
	}

	/**
	 * Method to initialise the database
	 *
	 * @param   array  $options  The options to use for configuration
	 *
	 * @return  boolean
	 *
	 * @since   3.0
	 */
	public function initialise($options)
	{
		// Get the options as a object for easier handling.
		$options = JArrayHelper::toObject($options);

		// Load the back-end language files so that the DB error messages work
		$lang 			= JFactory::getLanguage();
		$currentLang 	= $lang->getTag();

		// Load the selected language
		if (JLanguage::exists($currentLang, JPATH_ADMINISTRATOR))
		{
			$lang->load('joomla', JPATH_ADMINISTRATOR, $currentLang, true);
		}
		// Pre-load en-GB in case the chosen language files do not exist
		else
		{
			$lang->load('joomla', JPATH_ADMINISTRATOR, 'en-GB', true);
		}

		// Ensure a database type was selected.
		if (empty($options->db_type))
		{
			$this->setError(JText::_('INSTL_DATABASE_INVALID_TYPE'));
			return false;
		}

		// Ensure that a hostname and user name were input.
		if (empty($options->db_host) || empty($options->db_user))
		{
			$this->setError(JText::_('INSTL_DATABASE_INVALID_DB_DETAILS'));
			return false;
		}

		// Ensure that a database name was input.
		if (empty($options->db_name))
		{
			$this->setError(JText::_('INSTL_DATABASE_EMPTY_NAME'));
			return false;
		}

		// Validate database table prefix.
		if (!preg_match('#^[a-zA-Z]+[a-zA-Z0-9_]*$#', $options->db_prefix))
		{
			$this->setError(JText::_('INSTL_DATABASE_PREFIX_INVALID_CHARS'));
			return false;
		}

		// Validate length of database table prefix.
		if (strlen($options->db_prefix) > 15)
		{
			$this->setError(JText::_('INSTL_DATABASE_FIX_TOO_LONG'));
			return false;
		}

		// Validate length of database name.
		if (strlen($options->db_name) > 64)
		{
			$this->setError(JText::_('INSTL_DATABASE_NAME_TOO_LONG'));
			return false;
		}

		// Get a database object.
		try
		{
			return InstallationHelperDatabase::getDbo($options->db_type, $options->db_host, $options->db_user, $options->db_pass, $options->db_name, $options->db_prefix, $options->db_select);
		}
		catch (RuntimeException $e)
		{
			$this->setError(JText::sprintf('INSTL_DATABASE_COULD_NOT_CONNECT', $e->getMessage()));
			return false;
		}
	}

	/**
	 * @since   3.0
	 */
	public function createDatabase($options)
	{
		// Disable autoselect database before it's created
		$tmpSelect = true;
		if (isset($options['db_select']))
		{
			$tmpSelect = $options['db_select'];
		}
		$options['db_select'] = false;

		if (!$db = $this->initialise($options))
		{
			return false;
		}

		// Get the options as a object for easier handling.
		$options = JArrayHelper::toObject($options);

		// Check database version.
		$type = $options->db_type;
		try
		{
			$db_version = $db->getVersion();
		}
		catch (RuntimeException $e)
		{
			$this->setError(JText::sprintf('INSTL_DATABASE_COULD_NOT_CONNECT', $e->getMessage()));
			return false;
		}

		if (!$db->isMinimumVersion())
		{
			$this->setError(JText::sprintf('INSTL_DATABASE_INVALID_' . strtoupper($type) . '_VERSION', $db_version));
			return false;
		}

		if (($type == 'mysql') || ($type == 'mysqli'))
		{
			// @internal MySQL versions pre 5.1.6 forbid . / or \ or NULL
			if ((preg_match('#[\\\/\.\0]#', $options->db_name)) && (!version_compare($db_version, '5.1.6', '>=')))
			{
				$this->setError(JText::sprintf('INSTL_DATABASE_INVALID_NAME', $db_version));
				return false;
			}
		}

		// @internal Check for spaces in beginning or end of name
		if (strlen(trim($options->db_name)) <> strlen($options->db_name))
		{
			$this->setError(JText::_('INSTL_DATABASE_NAME_INVALID_SPACES'));
			return false;
		}

		// @internal Check for asc(00) Null in name
		if (strpos($options->db_name, chr(00)) !== false)
		{
			$this->setError(JText::_('INSTL_DATABASE_NAME_INVALID_CHAR'));
			return false;
		}

		// PostgreSQL database older than version 9.0.0 needs to run 'CREATE LANGUAGE' to create function.
		if (($options->db_type == 'postgresql') && (version_compare($db_version, '9.0.0', '<')))
		{
			$db->setQuery("CREATE LANGUAGE plpgsql");
			$db->query();
		}

		// Get database's UTF support
		$utfSupport = $db->hasUTFSupport();

		// Try to select the database
		try
		{
			$db->select($options->db_name);
		}
		catch (RuntimeException $e)
		{
			// If the database could not be selected, attempt to create it and then select it.
			if ($this->createDB($db, $options, $utfSupport))
			{
				$db->select($options->db_name);
			}
			else
			{
				$this->setError(JText::sprintf('INSTL_DATABASE_ERROR_CREATE', $options->db_name));
				return false;
			}
		}

		$options = (array) $options;
		// remove *_errors value
		foreach($options as $i => $option) {
			if (isset($i['1']) && $i['1'] == '*') {
				unset($options[$i]);
				break;
			}
		}
		$options = array_merge(array('db_created' => 1), $options);

		// Restore autoselect value after database creation
		$options['db_select'] = $tmpSelect;

		$session = JFactory::getSession();
		$session->set('setup.options', $options);

		return true;
	}

	/**
	 * @since   3.0
	 */
	public function handleOldDatabase($options)
	{
		if (!isset($options['db_created']) || !$options['db_created']) {
			return $this->createDatabase($options);
		}

		if (!$db = $this->initialise($options))
		{
			return false;
		}

		// Get the options as a object for easier handling.
		$options = JArrayHelper::toObject($options);

		// Set the character set to UTF-8 for pre-existing databases.
		$this->setDatabaseCharset($db, $options->db_name);

		// Should any old database tables be removed or backed up?
		if ($options->db_old == 'remove')
		{
			// Attempt to delete the old database tables.
			if (!$this->deleteDatabase($db, $options->db_name, $options->db_prefix))
			{
				$this->setError(JText::_('INSTL_DATABASE_ERROR_DELETE'));
				return false;
			}
		}
		else
		{
			// If the database isn't being deleted, back it up.
			if (!$this->backupDatabase($db, $options->db_name, $options->db_prefix))
			{
				$this->setError(JText::_('INSTL_DATABASE_ERROR_BACKINGUP'));
				return false;
			}
		}

		return true;
	}

	/**
	 * @since   3.0
	 */
	public function createTables($options)
	{
		if (!isset($options['db_created']) || !$options['db_created']) {
			return $this->createDatabase($options);
		}

		if (!$db = $this->initialise($options))
		{
			return false;
		}

		// Get the options as a object for easier handling.
		$options = JArrayHelper::toObject($options);

		// Check database type.
		$type = $options->db_type;

		// Set the character set to UTF-8 for pre-existing databases.
		$this->setDatabaseCharset($db, $options->db_name);

		// Set the appropriate schema script based on UTF-8 support.
		if ($type == 'mysqli' || $type == 'mysql')
		{
			$schema = 'sql/mysql/joomla.sql';
		}
		elseif ($type == 'sqlsrv' || $type == 'sqlazure')
		{
			$schema = 'sql/sqlazure/joomla.sql';
		}
		else
		{
			$schema = 'sql/' . $type . '/joomla.sql';
		}
		// Check if the schema is a valid file
		if (!is_file($schema))
		{
			$this->setError(JText::sprintf('INSTL_ERROR_DB', JText::_('INSTL_DATABASE_NO_SCHEMA')));
			return false;
		}

		// Attempt to import the database schema.
		if (!$this->populateDatabase($db, $schema))
		{
			$this->setError(JText::sprintf('INSTL_ERROR_DB', $this->getError()));
			return false;
		}

		// Attempt to update the table #__schema.
		$pathPart = JPATH_ADMINISTRATOR . '/components/com_admin/sql/updates/';
		if ($type == 'mysqli' || $type == 'mysql')
		{
			$pathPart .= 'mysql/';
		}
		elseif ($type == 'sqlsrv' || $type == 'sqlazure')
		{
			$pathPart .= 'sqlazure/';
		}
		else
		{
			$pathPart .= $type . '/';
		}
		$files = JFolder::files($pathPart, '\.sql$');

		if (empty($files))
		{
			$this->setError(JText::_('INSTL_DATABASE_ERROR_INITIALISE_SCHEMA'));
			return false;
		}
		$version = '';
		foreach ($files as $file)
		{
			if (version_compare($version, JFile::stripExt($file)) < 0)
			{
				$version = JFile::stripExt($file);
			}
		}
		$query = $db->getQuery(true);
		$query->insert($db->quoteName('#__schemas'));
		$query->columns(
			array(
				$db->quoteName('extension_id'),
				$db->quoteName('version_id')
			)
		);
		$query->values('700, ' . $db->quote($version));
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

		// Attempt to refresh manifest caches
		$query = $db->getQuery(true);
		$query->select('*');
		$query->from('#__extensions');
		$db->setQuery($query);

		$return = true;
		try
		{
			$extensions = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());
			$return = false;
		}

		JFactory::$database = $db;
		$installer = JInstaller::getInstance();
		foreach ($extensions as $extension)
		{
			if (!$installer->refreshManifestCache($extension->extension_id))
			{
				$this->setError(JText::sprintf('INSTL_DATABASE_COULD_NOT_REFRESH_MANIFEST_CACHE', $extension->name));
				return false;
			}
		}

		// Load the localise.sql for translating the data in joomla.sql
		if ($type == 'mysqli' || $type == 'mysql')
		{
			$dblocalise = 'sql/mysql/localise.sql';
		}
		elseif ($type == 'sqlsrv' || $type == 'sqlazure')
		{
			$dblocalise = 'sql/sqlazure/localise.sql';
		}
		else
		{
			$dblocalise = 'sql/' . $type . '/localise.sql';
		}
		if (is_file($dblocalise))
		{
			if (!$this->populateDatabase($db, $dblocalise))
			{
				$this->setError(JText::sprintf('INSTL_ERROR_DB', $this->getError()));
				return false;
			}
		}

		// Handle default backend language setting. This feature is available for localized versions of Joomla.
		$app = JFactory::getApplication();
		$languages = $app->getLocaliseAdmin($db);
		if (in_array($options->language, $languages['admin']) || in_array($options->language, $languages['site']))
		{
			// Build the language parameters for the language manager.
			$params = array();

			// Set default administrator/site language to sample data values:
			$params['administrator'] = 'en-GB';
			$params['site'] = 'en-GB';

			if (in_array($options->language, $languages['admin']))
			{
				$params['administrator'] = $options->language;
			}
			if (in_array($options->language, $languages['site']))
			{
				$params['site'] = $options->language;
			}
			$params = json_encode($params);

				// Update the language settings in the language manager.
				$query = $db->getQuery(true);
				$query->update($db->quoteName('#__extensions'));
				$query->set($db->quoteName('params') . ' = ' . $db->quote($params));
				$query->where($db->quoteName('element') . ' = ' . $db->quote('com_languages'));
				$db->setQuery($query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());
				$return = false;
			}
		}

		return $return;
	}

	/**
	 * Method to install the sample data
	 *
	 * @param   array  $options
	 *
	 * @return  boolean  True on success
	 *
	 * @since   3.0
	 */
	public function installSampleData($options)
	{
		if (!isset($options['db_created']) || !$options['db_created']) {
			return $this->createDatabase($options);
		}

		if (!$db = $this->initialise($options))
		{
			return false;
		}

		// Get the options as a object for easier handling.
		$options = JArrayHelper::toObject($options);

		// Build the path to the sample data file.
		$type = $options->db_type;
		if ($type == 'mysqli')
		{
			$type = 'mysql';
		}
		elseif ($type == 'sqlsrv')
		{
			$type = 'sqlazure';
		}

		$data = JPATH_INSTALLATION . '/sql/' . $type . '/' . $options->sample_file;

		// Attempt to import the database schema if one is chosen.
		if ($options->sample_file != '')
		{
			if (!file_exists($data))
			{
				$this->setError(JText::sprintf('INSTL_DATABASE_FILE_DOES_NOT_EXIST', $data));
				return false;
			}
			elseif (!$this->populateDatabase($db, $data))
			{
				$this->setError(JText::sprintf('INSTL_ERROR_DB', $this->getError()));
				return false;
			}

		$this->postInstallSampleData($db);
		}

		return true;
	}

	/**
	 * method to update the user id of the sample data content to the new rand user id
	 *
	 * @param   JDatabaseDriver  $db  Database connector object $db*
	 *
	 * @return  void
	 *
	 * @since   3.0
	 */
	protected function postInstallSampleData($db)
	{
		// Create the ID for the root user
		$userId = self::getUserId();

		// Update all created_by field of the tables with the random user id
		// categories (created_user_id), contact_details, content, newsfeeds, weblinks
		$updates_array = array(
			'categories' => 'created_user_id',
			'contact_details' => 'created_by',
			'content' => 'created_by',
			'newsfeeds' => 'created_by',
			'weblinks' => 'created_by',
		);

		foreach ($updates_array as $table => $field)
		{
			$db->setQuery(
				'UPDATE ' . $db->quoteName('#__' . $table) .
				' SET ' . $db->quoteName($field) . ' = ' . $db->Quote($userId)
			);
			$db->execute();
		}

	}

	/**
	 * Method to backup all tables in a database with a given prefix.
	 *
	 * @param   JDatabaseDriver  $db      JDatabaseDriver object.
	 * @param   string           $name    Name of the database to process.
	 * @param   string           $prefix  Database table prefix.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since	3.0
	 */
	public function backupDatabase($db, $name, $prefix)
	{
		$return = true;
		$backup = 'bak_' . $prefix;

		// Get the tables in the database.
		$tables = $db->getTableList();
		if ($tables)
		{
			foreach ($tables as $table)
			{
				// If the table uses the given prefix, back it up.
				if (strpos($table, $prefix) === 0)
				{
					// Backup table name.
					$backupTable = str_replace($prefix, $backup, $table);

					// Drop the backup table.
					try
					{
						$db->dropTable($backupTable, true);
					}
					catch (RuntimeException $e)
					{
						$this->setError($e->getMessage());
						$return = false;
					}

					// Rename the current table to the backup table.
					try
					{
						$db->renameTable($table, $backupTable, $backup, $prefix);
					}
					catch (RuntimeException $e)
					{
						$this->setError($e->getMessage());
						$return = false;
					}
				}
			}
		}

		return $return;
	}

	/**
	 * Method to create a new database.
	 *
	 * @param   JDatabaseDriver  $db       JDatabase object.
	 * @param   JObject          $options  JObject coming from "initialise" function to pass user
	 * 										and database name to database driver.
	 * @param   boolean          $utf      True if the database supports the UTF-8 character set.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.0
	 */
	public function createDB($db, $options, $utf)
	{
		// Build the create database query.
		try
		{
			// Run the create database query.
			$db->createDatabase($options, $utf);
		}
		catch (RuntimeException $e)
		{
			// If an error occurred return false.
			return false;
		}

		return true;
	}

	/**
	 * Method to delete all tables in a database with a given prefix.
	 *
	 * @param   JDatabaseDriver  $db      JDatabaseDriver object.
	 * @param   string           $name    Name of the database to process.
	 * @param   string           $prefix  Database table prefix.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.0
	 */
	public function deleteDatabase($db, $name, $prefix)
	{
		$return = true;

		// Get the tables in the database.
		$tables = $db->getTableList();
		if ($tables)
		{
			foreach ($tables as $table)
			{
				// If the table uses the given prefix, drop it.
				if (strpos($table, $prefix) === 0)
				{
					// Drop the table.
					try
					{
						$db->dropTable($table);
					}
					catch (RuntimeException $e)
					{
						$this->setError($e->getMessage());
						$return = false;
					}
				}
			}
		}

		return $return;
	}

	/**
	 * Method to import a database schema from a file.
	 *
	 * @param   JDatabaseDriver  $db      JDatabase object.
	 * @param   string           $schema  Path to the schema file.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.0
	 */
	public function populateDatabase($db, $schema)
	{
		$return = true;

		// Get the contents of the schema file.
		if (!($buffer = file_get_contents($schema)))
		{
			$this->setError($db->getErrorMsg());
			return false;
		}

		// Get an array of queries from the schema and process them.
		$queries = $this->_splitQueries($buffer);
		foreach ($queries as $query)
		{
			// Trim any whitespace.
			$query = trim($query);

			// If the query isn't empty and is not a MySQL or PostgreSQL comment, execute it.
			if (!empty($query) && ($query{0} != '#') && ($query{0} != '-'))
			{
				// Execute the query.
				$db->setQuery($query);

				try
				{
					$db->execute();
				}
				catch (RuntimeException $e)
				{
					$this->setError($e->getMessage());
					$return = false;
				}
			}
		}

		return $return;
	}

	/**
	 * Method to set the database character set to UTF-8.
	 *
	 * @param   JDatabaseDriver  $db    JDatabaseDriver object.
	 * @param   string           $name  Name of the database to process.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.0
	 */
	public function setDatabaseCharset($db, $name)
	{
		// Run the create database query.
		$db->setQuery($db->getAlterDbCharacterSet($name));
			/*'ALTER DATABASE '.$db->quoteName($name).' CHARACTER' .
			' SET `utf8`'
		);*/

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			return false;
		}

		return true;
	}

	/**
	 * Method to split up queries from a schema file into an array.
	 *
	 * @param   string  $sql  SQL schema.
	 *
	 * @return  array  Queries to perform.
	 *
	 * @since   3.0
	 */
	protected function _splitQueries($sql)
	{
		$buffer    = array();
		$queries   = array();
		$in_string = false;

		// Trim any whitespace.
		$sql = trim($sql);

		// Remove comment lines.
		$sql = preg_replace("/\n\#[^\n]*/", '', "\n" . $sql);

		// Remove PostgreSQL comment lines.
		$sql = preg_replace("/\n\--[^\n]*/", '', "\n" . $sql);

		// find function
		$funct = explode('CREATE OR REPLACE FUNCTION', $sql);
		// save sql before function and parse it
		$sql = $funct[0];

		// Parse the schema file to break up queries.
		for ($i = 0; $i < strlen($sql) - 1; $i++)
		{
			if ($sql[$i] == ";" && !$in_string)
			{
				$queries[] = substr($sql, 0, $i);
				$sql = substr($sql, $i + 1);
				$i = 0;
			}

			if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\")
			{
				$in_string = false;
			}
			elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset ($buffer[0]) || $buffer[0] != "\\"))
			{
				$in_string = $sql[$i];
			}
			if (isset ($buffer[1]))
			{
				$buffer[0] = $buffer[1];
			}
			$buffer[1] = $sql[$i];
		}

		// If the is anything left over, add it to the queries.
		if (!empty($sql))
		{
			$queries[] = $sql;
		}

		// add function part as is
		for ($f = 1; $f < count($funct); $f++)
		{
			$queries[] = 'CREATE OR REPLACE FUNCTION ' . $funct[$f];
		}

		return $queries;
	}
}

No other release has this exact content. See every version of this file.