joomla 1.7

’tag’

Блокнот, 6 августа 2012

Август 6, 2012

. В классе JModelList есть переменная $cache. Однако, в ней хранится кэш на время исполнения скрипта. Если обратиться дважды к методу getItems(), то 2-й вызов не станет делать запрос к БД.

Метод getStoreId() формирует уникальный ID для хранения кэша:

protected function getStoreId($id = '')
{
	// Add the list state to the store id.
	$id	.= ':'.$this->getState('list.start');
	$id	.= ':'.$this->getState('list.limit');
	$id	.= ':'.$this->getState('list.ordering');
	$id	.= ':'.$this->getState('list.direction');

	return md5($this->context.':'.$id);
}

Видно, что ID формируется на основе переменной $context. Она же задается в конструкторе:

// Guess the context as Option.ModelName.
if (empty($this->context)) {
	$this->context = strtolower($this->option.'.'.$this->getName());
}

Либо можно задать ее вручную в модели.

  • $this->option - название компонента;
  • $this->getName() - постфикс имени класса модели.

Tags:
Записано в Joomla, Блокнот    |    Постоянная ссылка

Вывод списка записей через класс JModelList в Закрытой части сайта в Joomla 1.7

Июнь 6, 2012

Буду разбираться как в Закрытой части сайта вывести список записей из базы данных посредством класса JModelList с тем отличием от Открытой части сайта, что будут доступны элементы редактирования записей, такие как выделение, публикация и другие по желанию.

За основу беру компонент com_simple Открытой части сайта.

Файл simple.php

<?php
defined( '_JEXEC' ) or die;

jimport('joomla.application.component.controller');

$controller = JController::getInstance('Simple');
$controller->execute(JRequest::getCmd('task'));
$controller->redirect();

Подключаем класс SimpleController.

Файл контроллера controller.php

<?php
defined( '_JEXEC' ) or die;

jimport('joomla.application.component.controller');

class SimpleController extends JController
{
}

Функционал без изменений наследуется из класса JController.

Файл модели users.php

<?php
defined( '_JEXEC' ) or die;

jimport('joomla.application.component.modellist');

class SimpleModelUsers extends JModelList
{
	public function getListQuery()
	{
		$query = parent::getListQuery();

		$query->select('*');
		$query->from('#__users');

		return $query;
	}

	public function getItems()
	{
		$items = parent::getItems();

		foreach ($items as &$item) {
			$item->url = 'index.php?option=com_simple&amp;task=user.edit&amp;id=' . $item->id;
		}

		return $items;
	}
}

Принцип работы модели компонента

Вновь идет задействование класса JModelList, как это было при получении и выводе списка записей в компоненте Открытой части сайта:

Сначала через метод getListQuery() класса JModelList формируется запрос, который в последствии вызывается через метод getItems(), который в свою очередь обращается к методу _getListQuery().

Таким образом, в переменную $items помещается список объектов, которые возвращает метод _getList() класса JModel.

Главная особенность и отличие метода getItems() класса SimpleModelUsers Закрытой части сайта заключается в цикле, в котором составляются ссылки на редактирование для каждой записи:

foreach ($items as &$item) {
	$item->url = 'index.php?option=com_simple&amp;task=user.edit&amp;id=' . $item->id;
}

Интересно также, что массив $items перебирается по ссылке и дополняет сам себя новой записью url.

Как видно, задача task в ссылке указывается как user.edit. Это означает, что через класс контроллера SimpleControllerUser будет обращение к методу edit().

Файл шаблона компонента default.php

<?php defined( '_JEXEC' ) or die; ?>
<form action="index.php?option=com_simple&amp;view=users" method="post" name="adminForm" id="adminForm">
	<table class="adminlist">
		<thead>
			<tr>
				<th width="10">
					<input type="checkbox" name="checkall-toggle" value="" onclick="checkAll(this)" />
				</th>
				<th><?php echo JText::_('COM_SIMPLE_USER_NAME_LABEL'); ?></th>
				<th><?php echo JText::_('COM_SIMPLE_USER_BLOCK_LABEL'); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ($this->items as $i => $item) : ?>
				<tr class="row<?php echo $i % 2 ?>">
					<td class="center">
						<?php echo JHtml::_('grid.id', $i, $item->id); ?>
					</td>
					<td>
						<a href="<?php echo $item->url; ?>"><?php echo $this->escape($item->name); ?></a>
					</td>
					<td class="center">
						<?php echo JHtml::_('jgrid.published', $item->block, $i, 'users.', true, 'cb'); ?>
					</td>
				</tr>
			<?php endforeach; ?>
		</tbody>
	</table>
</form>

В данной форме в 1-ю очередь следует обратить внимание на следующие параметры:

  1. action="index.php?option=com_simple&amp;view=users"
  2. name="adminForm"

Оба параметра обязательны. 1-й образуется от текущего вида, 2-й постоянный.

Поле для ввода checkall-toggle при нажатии вызывает функцию JavaScript checkAll(), которая является частью CMS Joomla 1.7. Однако, в таком виде, в каком находится сейчас компонент, данная функция не будет работать.

Для работы функции необходимо обязательное подключение Панели с кнопками в верхней части экрана через класс JToolBarHelper из вида компонента.

Классы строк чередуются как row0 и row1, цвет их ячеек будет отличаться. Стили заданы в стандартном CSS Закрытой части Joomla 1.7:
/administrator/templates/bluestork/css/template.css 

table.adminlist tbody tr.row1 td {
	background: #f0f0f0;
	border-top: 1px solid #FFF;
}

Но это все мелочи, по сравнению с возможностями, которые предоставляет Joomla для отображения данных. Речь идет про эту строчку:

<?php echo JHtml::_('grid.id', $i, $item->id); ?>

и эту:

<?php echo JHtml::_('jgrid.published', $item->block, $i, 'users.', true, 'cb'); ?>

Вызывается статический метод _() класса JHtml. Данный метод подгружает дополнительный класс и его метод. В обоих случаях идет обращение к классу JHtmlJGrid.

Параметры, которые передаются в метод _() обрабатываются внутри метода следующим образом:

list($key, $prefix, $file, $func) = self::extract($key);

Строка с точкой ".", которая передается в метод _() обрабатывается следующим образом:

$prefix = (count($parts) == 3 ? array_shift($parts) : 'JHtml');
$file	= (count($parts) == 2 ? array_shift($parts) : '');
$func	= array_shift($parts);

prefix – имя префикса подгружаемого файла.

file – имя подгружаемого файла.

По-другому, в метод extract() передается строка вида (prefix).(class).function, где prefix и class передавать необязательно. Если они не будут переданы, то будет вызван метод класса JHtml.

При строке jgrid.published, подключается класс JHtmlJGrid и вызывается метод published().

Таким образом, следующий код в файле шаблона вида users Закрытой части сайта default.php:

<?php echo JHtml::_('jgrid.published', $item->block, $i, 'users.', true, 'cb'); ?>

превращается в:

<a class="jgrid" href="javascript:void(0);" onclick="return listItemTask('cb0','users.publish')" title="Publish Item">
	<span class="state unpublish">
		<span class="text">Unpublished</span>
	</span>
</a>

Как видно, при нажатии на ссылку сработает функция JavaScript listItemTask().

Следующий код:

<?php echo JHtml::_('grid.id', $i, $item->id); ?>

превращается в:

<input type="checkbox" id="cb0" name="cid[]" value="42" onclick="isChecked(this.checked);" title="Checkbox for row 1" />

В следующих записях я по возможности рассмотрю доступные методы класса JHtml и его подклассов.

Tags: , , , , , , , , , , , , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Определение нахождения на Главной странице в Joomla 2.5

Июнь 5, 2012

Задача тривиальная. Решение беру из официальной документации по Joomla:

Думаю, что лучший способ, который подойдет для любого сайта следующий:

<?php
$app = JFactory::getApplication();
$menu = $app->getMenu();
$lang = JFactory::getLanguage();
if ( $menu->getActive() == $menu->getDefault( $lang->getTag() ) ) {
	echo 'Главная страница';
}
else {
	echo 'Второстепенная';
}
?>

Решение работает, начиная с версии 1.6.

Tags: , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Переопределение шаблона компонента в Joomla 1.7

Май 29, 2012

Ранее я уже писал про переопределение шаблона модуля в используемой теме Joomla.

Шаблоны отображения определенного вида для компонента com_simple открытой части сайта, к примеру, user, хранятся в следующей папке:
/components/com_simple/views/user/tmpl

Как и для модуля, сначала в папке с выбранной темой, к примеру, beez_20 создаются последовательно папки html и com_simple:
/templates/beez_20/html/com_simple

Единственная особенность переопределения шаблона компонента от модуля является необходимость создать подпапку равную имени вида:
/templates/beez_20/html/com_simple/user

Далее из папки шаблона компонента в эту папку переносится нужный вид:
/templates/beez_20/html/com_simple/user/default.php

Теперь остается поменять сам файл default.php.

Tags: , , , , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Добавление файла CSS к шаблону компонента в Joomla 1.7

Май 29, 2012

Joomla 1.7 хранит CSS и JS файлы в следующей папке:
/media

При создании компонента в папке media должна быть подпапка равная имени компонента. При компоненте com_simple:
/media/com_simple

В данной папке создаем папку css и помещаем туда файл со стилями:
/media/com_simple/css/user.css

Теперь подключим CSS файл из вида user и шаблона default:

$document = JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'media/com_simple/css/user.css');

Сначала через класс JFactory и статический метод getDocument(), который вернет объект класса JDocument.

Объект класса JDocument будет записан в переменную $document и с помощью метода addStyleSheet() файл CSS со стилями будет подключен к шаблону.

Метод addStyleSheet() выглядит следующим образом:

public function addStyleSheet($url, $type = 'text/css', $media = null, $attribs = array())
{
	$this->_styleSheets[$url]['mime']		= $type;
	$this->_styleSheets[$url]['media']		= $media;
	$this->_styleSheets[$url]['attribs']	= $attribs;
}

Отмечу, что в данном случае ссылка, которая отправляется в метод addStyleSheet() не обрабатывается классом JRoute. С помощью класса JURI получается префикс для ссылки: имя домена – через метод base() и сцепляется с окончанием, которое прописывается вручную.

Tags: , , , , , , , , , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Использование класса JRoute в компоненте для отображения ссылок в Joomla 1.7

Май 29, 2012

Класс JRoute имеет один единственный метод «_». Данный метод позволяет при передаче ему ссылки отобразить ее как обычную ссылку, либо в SEF виде. Также при разработке не нужно заботиться о передаче имени домена сайта.

Следующая запись:

JRoute::_('index.php?option=com_simple&view=user&id=' . $user->user_id');

при $user->user_id равным 42 преобразуется в следующий вид:
http://localhost/joomla17/index.php?option=com_simple&view=user&id=42

Однако, если включен параметр "Search Engine Friendly URLs", то ссылка будет SEF вида.

Примечание

Класс JRoute следует использовать исключительно для перелинковки, а точнее применения полученной ссылки в теге <a>.

Tags: , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Использование языковых файлов в шаблоне компонента в Joomla 1.7

Май 29, 2012

Языковые файлы компонентов, отвечающие за открытую часть сайта, находятся в папке:
/language/ru-RU

Языковой файл компонента com_simple имеет следующее название:
ru-RU.com_simple.ini

Поместим в данный файл строчку:
COM_SIMPLE_USER_H1="Пользователь"

Теперь языковая переменная COM_SIMPLE_USER_H1 доступна из шаблона компонента в открытой части.

В папке tmpl находится шаблон default.php. Указываем содержимое:

<?php defined( '_JEXEC' ) or die; ?>

<h1><?php echo JText::_('COM_SIMPLE_USER_H1'); ?> <?php echo $this->escape($this->item->name); ?></h1>

Проверяем вывод на экран:
http://localhost/joomla17/index.php?option=com_simple&view=user&id=42

В теге h1 теперь находится:
Пользователь Super User

Для вывода и перевода строки COM_SIMPLE_USER_H1 используется класс JText и метод "_".

Если перевод для строки не задан, то будет отображено значение по-умолчанию. В данном случае COM_SIMPLE_USER_H1.

В Настройках Joomla 1.7 из Закрытой части сайта можно включить режим отладки языка, что позволит видеть все переводимые строки, окруженные символами **.

Tags: , , , , , , , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Онлайн документация по Joomla 1.7

Май 28, 2012

Чтобы избавить себя от вечного копания в исходниках Joomla 1.7 на локальном компьютере, создал онлайн документацию с помощью PHPDoctor.

Документация, включая исходные коды, по Joomla 1.7 доступна по постоянному адресу:

В отличие от PhpDocumentor версии 1.4.4, который не мог сформировать ссылки на исходные коды файлов (source code) и скопировать сами файлы, PHPDoctor отлично справился с задачей.

Tags: , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Комплексные запросы к базе данных в Joomla 1.7

Май 28, 2012

Ранее я писал про простой запрос в модели через прямое подключение к базе данных, например:

$user_id = JRequest::getInt('id');

$db = $this->getDbo();
$query = $db->getQuery(true);

$query->select('name');
$query->from('#__users')
	->where('id = ' . $user_id);

$db->setQuery($query);
$row = $db->loadObject();

Дополнительные возможности скрываются в файле databasequery.php:
/libraries/joomla/database/databasequery.php

Речь идет о следующих методах (часть):

  • join
  • rightJoin
  • leftJoin
  • outerJoin
  • group
  • length

Методы находятся в классе JDatabaseQuery.

По сути запрос может быть любого вида, но как мы видим, он не прописывается напрямую и вручную, а создается через подключение требуемых методов.

Так, более сложных запрос по выборке из двух страниц будет реализован так:

$query->select('m.id, m.title, description')
	->from('#__menu as m')
	->join('INNER', '#__menu_types AS t USING(id)')
	->where('description = ""');

Видно, что в запросе был использован тип объединения INNER JOIN (оператор).

При внимательном изучении файла databasequery.php видно, что можно использовать вместо join метод innerJoin:

public function innerJoin($conditions) {
	$this->join('INNER', $conditions);

	return $this;
}

Строка с запросом может быть в несколько строчек:

$query->select('m.id, m.title, description');
$query->from('#__menu as m');
$query->innerJoin('#__menu_types AS t USING(id)');
$query->where('description = ""');

Теперь можно не использовать класс JTable в модели компонента, который позволяет выводить запись по идентификатору, а использовать свой запрос любой сложности. Работа с классом JTable демонстрировалась в данной записи:

Файл databasequery.php

<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Database
 *
 * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;

/**
 * Query Element Class.
 *
 * @package     Joomla.Platform
 * @subpackage  Database
 * @since       11.1
 */
class JDatabaseQueryElement
{
	/**
	 * @var    string  The name of the element.
	 * @since  11.1
	 */
	protected $name = null;

	/**
	 * @var    array  An array of elements.
	 * @since  11.1
	 */
	protected $elements = null;

	/**
	 * @var    string  Glue piece.
	 * @since  11.1
	 */
	protected $glue = null;

	/**
	 * Constructor.
	 *
	 * @param   string  $name      The name of the element.
	 * @param   mixed   $elements  String or array.
	 * @param   string  $glue      The glue for elements.
	 *
	 * @return  JDatabaseQueryElement
	 *
	 * @since   11.1
	 */
	public function __construct($name, $elements, $glue = ',')
	{
		$this->elements	= array();
		$this->name		= $name;
		$this->glue		= $glue;

		$this->append($elements);
	}

	/**
	 * Magic function to convert the query element to a string.
	 *
	 * @return  string
	 *
	 * @since   11.1
	 */
	public function __toString()
	{
		if (substr($this->name, -2) == '()') {
			return PHP_EOL.substr($this->name, 0, -2).'('.implode($this->glue, $this->elements).')';
		}
		else {
			return PHP_EOL.$this->name.' '.implode($this->glue, $this->elements);
		}
	}

	/**
	 * Appends element parts to the internal list.
	 *
	 * @param   mixed  String or array.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 */
	public function append($elements)
	{
		if (is_array($elements)) {
			$this->elements = array_merge($this->elements, $elements);
		}
		else {
			$this->elements = array_merge($this->elements, array($elements));
		}
	}

	/**
	 * Gets the elements of this element.
	 *
	 * @return  string
	 *
	 * @since   11.1
	 */
	public function getElements()
	{
		return $this->elements;
	}
}

/**
 * Query Building Class.
 *
 * @package     Joomla.Platform
 * @subpackage  Database
 * @since       11.1
 */
abstract class JDatabaseQuery
{
	/**
	 * @var    resource  The database connection resource.
	 * @since  11.1
	 */
	protected $db = null;

	/**
	 * @var    string  The query type.
	 * @since  11.1
	 */
	protected $type = '';

	/**
	 * @var    string  The query element for a generic query (type = null).
	 * @since  11.1
	 */
	protected $element = null;

	/**
	 * @var    object  The select element.
	 * @since  11.1
	 */
	protected $select = null;

	/**
	 * @var    object  The delete element.
	 * @since  11.1
	 */
	protected $delete = null;

	/**
	 * @var    object  The update element.
	 * @since  11.1
	 */
	protected $update = null;

	/**
	 * @var    object  The insert element.
	 * @since  11.1
	 */
	protected $insert = null;

	/**
	 * @var    object  The from element.
	 * @since  11.1
	 */
	protected $from = null;

	/**
	 * @var    object  The join element.
	 * @since  11.1
	 */
	protected $join = null;

	/**
	 * @var    object  The set element.
	 * @since  11.1
	 */
	protected $set = null;

	/**
	 * @var    object  The where element.
	 * @since  11.1
	 */
	protected $where = null;

	/**
	 * @var    object  The group by element.
	 * @since  11.1
	 */
	protected $group = null;

	/**
	 * @var    object  The having element.
	 * @since  11.1
	 */
	protected $having = null;

	/**
	 * @var    object  The column list for an INSERT statement.
	 * @since  11.1
	 */
	protected $columns = null;

	/**
	 * @var    object  The values list for an INSERT statement.
	 * @since  11.1
	 */
	protected $values = null;

	/**
	 * @var    object  The order element.
	 * @since  11.1
	 */
	protected $order = null;

	/**
	 * Magic method to provide method alias support for quote() and quoteName().
	 *
	 * @param   string  $method  The called method.
	 * @param   array   $args    The array of arguments passed to the method.
	 *
	 * @return  string  The aliased method's return value or null.
	 *
	 * @since   11.1
	 */
	public function __call($method, $args)
	{
		if (empty($args)) {
			return;
		}

		switch ($method)
		{
			case 'q':
				return $this->quote($args[0], isset($args[1]) ? $args[1] : true);
				break;

			case 'qn':
				return $this->quoteName($args[0]);
				break;

			case 'e':
				return $this->escape($args[0], isset($args[1]) ? $args[1] : false);
				break;
		}
	}

	/**
	 * Class constructor.
	 *
	 * @param   JDatabase  $db  The database connector resource.
	 *
	 * @return  JDatabaseQuery
	 * @since   11.1
	 */
	public function __construct(JDatabase $db = null)
	{
		$this->db = $db;
	}

	/**
	 * Magic function to convert the query to a string.
	 *
	 * @return  string	The completed query.
	 *
	 * @since   11.1
	 */
	public function __toString()
	{
		$query = '';

		switch ($this->type)
		{
			case 'element':
				$query .= (string) $this->element;
				break;

			case 'select':
				$query .= (string) $this->select;
				$query .= (string) $this->from;
				if ($this->join) {
					// special case for joins
					foreach ($this->join as $join)
					{
						$query .= (string) $join;
					}
				}

				if ($this->where) {
					$query .= (string) $this->where;
				}

				if ($this->group) {
					$query .= (string) $this->group;
				}

				if ($this->having) {
					$query .= (string) $this->having;
				}

				if ($this->order) {
					$query .= (string) $this->order;
				}

				break;

			case 'delete':
				$query .= (string) $this->delete;
				$query .= (string) $this->from;

				if ($this->join) {
					// special case for joins
					foreach ($this->join as $join)
					{
						$query .= (string) $join;
					}
				}

				if ($this->where) {
					$query .= (string) $this->where;
				}

				break;

			case 'update':
				$query .= (string) $this->update;
				$query .= (string) $this->set;

				if ($this->where) {
					$query .= (string) $this->where;
				}

				break;

			case 'insert':
				$query .= (string) $this->insert;

				// Set method
				if ($this->set) {
					$query .= (string) $this->set;
				}
				// Columns-Values method
				elseif ($this->values) {
					if ($this->columns) {
						$query .= (string) $this->columns;
					}

					$query .= ' VALUES ';
					$query .= (string) $this->values;
				}

				break;
		}

		return $query;
	}

	/**
	 * Magic function to get protected variable value
	 *
	 * @param   String
	 * @return  mixed
	 *
	 * @since   11.1
	 */
	public function __get($name)
	{
		return isset($this->$name) ? $this->$name : null;
	}

	/**
	 * Casts a value to a char.
	 *
	 * Ensure that the value is properly quoted before passing to the method.
	 *
	 * @param   string  $value  The value to cast as a char.
	 *
	 * @return  string  Returns the cast value.
	 *
	 * @since   11.1
	 */
	public function castAsChar($value)
	{
		return $value;
	}

	/**
	 * Gets the number of characters in a string.
	 *
	 * Note, use 'length' to find the number of bytes in a string.
	 *
	 * @param   string  $value  A value.
	 *
	 * @return  string  The required char lenght call.
	 *
	 * @since 11.1
	 */
	public function charLength($field)
	{
		return 'CHAR_LENGTH('.$field.')';
	}

	/**
	 * Clear data from the query or a specific clause of the query.
	 *
	 * @param   string  $clear  Optionally, the name of the clause to clear, or nothing to clear the whole query.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 */
	public function clear($clause = null)
	{
		switch ($clause)
		{
			case 'select':
				$this->select = null;
				$this->type = null;
				break;

			case 'delete':
				$this->delete = null;
				$this->type = null;
				break;

			case 'update':
				$this->update = null;
				$this->type = null;
				break;

			case 'insert':
				$this->insert = null;
				$this->type = null;
				break;

			case 'from':
				$this->from = null;
				break;

			case 'join':
				$this->join = null;
				break;

			case 'set':
				$this->set = null;
				break;

			case 'where':
				$this->where = null;
				break;

			case 'group':
				$this->group = null;
				break;

			case 'having':
				$this->having = null;
				break;

			case 'order':
				$this->order = null;
				break;

			case 'columns':
				$this->columns = null;
				break;

			case 'values':
				$this->values = null;
				break;

			default:
				$this->type = null;
				$this->select = null;
				$this->delete = null;
				$this->update = null;
				$this->insert = null;
				$this->from = null;
				$this->join = null;
				$this->set = null;
				$this->where = null;
				$this->group = null;
				$this->having = null;
				$this->order = null;
				$this->columns = null;
				$this->values = null;
				break;
		}

		return $this;
	}

	/**
	 * Adds a column, or array of column names that would be used for an INSERT INTO statement.
	 *
	 * @param   mixed  $columns  A column name, or array of column names.
	 *
	 * @return  JDatabaseQuerySQLAzure  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	function columns($columns)
	{
		if (is_null($this->columns)) {
			$this->columns = new JDatabaseQueryElement('()', $columns);
		}
		else {
			$this->columns->append($columns);
		}

		return $this;
	}

	/**
	 * Concatenates an array of column names or values.
	 *
	 * @param   array   $values     An array of values to concatenate.
	 * @param   string  $separator  As separator to place between each value.
	 *
	 * @return  string  The concatenated values.
	 *
	 * @since   11.1
	 */
	function concatenate($values, $separator = null)
	{
		if ($separator) {
			return 'CONCATENATE('.implode(' || '.$this->quote($separator).' || ', $values).')';
		}
		else{
			return 'CONCATENATE('.implode(' || ', $values).')';
		}
	}

	/**
	 * Gets the current date and time.
	 *
	 * @return  string
	 *
	 * @since   11.1
	 */
	function currentTimestamp()
	{
		return 'CURRENT_TIMESTAMP()';
	}

	/**
	 * Returns a PHP date() function compliant date format for the database driver.
	 *
	 * @return  string  The format string.
	 *
	 * @since   11.1
	 */
	public function dateFormat()
	{
		return 'Y-m-d H:i:s';
	}

	/**
	 * Add a table name to the DELETE clause of the query.
	 *
	 * Note that you must not mix insert, update, delete and select method calls when building a query.
	 *
	 * @param   string  $table  The name of the table to delete from.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function delete($table = null)
	{
		$this->type	= 'delete';
		$this->delete	= new JDatabaseQueryElement('DELETE', null);

		if (!empty($table)) {
			$this->from($table);
		}

		return $this;
	}

	/**
	 * Method to escape a string for usage in an SQL statement.
	 *
	 * @param   string  $text   The string to be escaped.
	 * @param   bool    $extra  Optional parameter to provide extra escaping.
	 *
	 * @return  string  The escaped string.
	 *
	 * @since   11.1
	 * @throws  DatabaseError if the internal db property is not a valid object.
	 */
	public function escape($text, $extra = false)
	{
		if (!($this->db instanceof JDatabase)) {
			throw new DatabaseException('JLIB_DATABASE_ERROR_INVALID_DB_OBJECT');
		}

		$this->db->escape($text, $extra);
	}

	/**
	 * Add a table to the FROM clause of the query.
	 *
	 * Note that while an array of tables can be provided, it is recommended you use explicit joins.
	 *
	 * @param   mixed  $tables  A string or array of table names.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function from($tables)
	{
		if (is_null($this->from)) {
			$this->from = new JDatabaseQueryElement('FROM', $tables);
		}
		else {
			$this->from->append($tables);
		}

		return $this;
	}

	/**
	 * Add a grouping column to the GROUP clause of the query.
	 *
	 * @param   mixed  $columns  A string or array of ordering columns.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function group($columns)
	{
		if (is_null($this->group)) {
			$this->group = new JDatabaseQueryElement('GROUP BY', $columns);
		}
		else {
			$this->group->append($columns);
		}

		return $this;
	}

	/**
	 * A conditions to the HAVING clause of the query.
	 *
	 * @param   mixed   $conditions  A string or array of columns.
	 * @param   string  $glue        The glue by which to join the conditions. Defaults to AND.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function having($conditions, $glue='AND')
	{
		if (is_null($this->having)) {
			$glue = strtoupper($glue);
			$this->having = new JDatabaseQueryElement('HAVING', $conditions, " $glue ");
		}
		else {
			$this->having->append($conditions);
		}

		return $this;
	}

	/**
	 * Add an INNER JOIN clause to the query.
	 *
	 * @param   string  $conditions  A string or array of conditions.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function innerJoin($conditions)
	{
		$this->join('INNER', $conditions);

		return $this;
	}

	/**
	 * Add a table name to the INSERT clause of the query.
	 *
	 * Note that you must not mix insert, update, delete and select method calls when building a query.
	 *
	 * @param   mixed  $table  The name of the table to insert data into.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function insert($table)
	{
		$this->type	= 'insert';
		$this->insert	= new JDatabaseQueryElement('INSERT INTO', $table);

		return $this;
	}

	/**
	 * Add a JOIN clause to the query.
	 *
	 * @param   string  $type        The type of join. This string is prepended to the JOIN keyword.
	 * @param   string  $conditions  A string or array of conditions.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function join($type, $conditions)
	{
		if (is_null($this->join)) {
			$this->join = array();
		}
		$this->join[] = new JDatabaseQueryElement(strtoupper($type) . ' JOIN', $conditions);

		return $this;
	}

	/**
	 * Add a LEFT JOIN clause to the query.
	 *
	 * @param   string  $conditions  A string or array of conditions.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function leftJoin($conditions)
	{
		$this->join('LEFT', $conditions);

		return $this;
	}

	/**
	 * Get the length of a string in bytes.
	 *
	 * Note, use 'charLength' to find the number of characters in a string.
	 *
	 * @param   string  $value  The string to measure.
	 *
	 * @return  int
	 *
	 * @since   11.1
	 */
	function length($value)
	{
		return 'LENGTH('.$value.')';
	}

	/**
	 * Get the null or zero representation of a timestamp for the database driver.
	 *
	 * @param   boolean  $quoted  Optionally wraps the null date in database quotes (true by default).
	 *
	 * @return  string  Null or zero representation of a timestamp.
	 *
	 * @since   11.1
	 */
	public function nullDate($quoted = true)
	{
		if (!($this->db instanceof JDatabase)) {
			throw new DatabaseException('JLIB_DATABASE_ERROR_INVALID_DB_OBJECT');
		}

		$result = $this->db->getNullDate($quoted);

		if ($quoted) {
			return $this->db->quote($result);
		}

		return $result;
	}

	/**
	 * Add a ordering column to the ORDER clause of the query.
	 *
	 * @param   mixed  $columns  A string or array of ordering columns.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function order($columns)
	{
		if (is_null($this->order)) {
			$this->order = new JDatabaseQueryElement('ORDER BY', $columns);
		}
		else {
			$this->order->append($columns);
		}

		return $this;
	}

	/**
	 * Add an OUTER JOIN clause to the query.
	 *
	 * @param   string  $conditions  A string or array of conditions.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function outerJoin($conditions)
	{
		$this->join('OUTER', $conditions);

		return $this;
	}

	/**
	 * Method to quote and optionally escape a string to database requirements for insertion into the database.
	 *
	 * @param   string  $text    The string to quote.
	 * @param   bool    $escape  True to escape the string, false to leave it unchanged.
	 *
	 * @return  string  The quoted input string.
	 *
	 * @since   11.1
	 * @throws  DatabaseError if the internal db property is not a valid object.
	 */
	public function quote($text, $escape = true)
	{
		if (!($this->db instanceof JDatabase)) {
			throw new DatabaseException('JLIB_DATABASE_ERROR_INVALID_DB_OBJECT');
		}

		return $this->db->quote(($escape ? $this->db->escape($text) : $text));
	}

	/**
	 * Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection
	 * risks and reserved word conflicts.
	 *
	 * @param   string  $name  The identifier name to wrap in quotes.
	 *
	 * @return  string  The quote wrapped name.
	 *
	 * @since   11.1
	 * @throws  DatabaseError if the internal db property is not a valid object.
	 */
	public function quoteName($name)
	{
		if (!($this->db instanceof JDatabase)) {
			throw new DatabaseException('JLIB_DATABASE_ERROR_INVALID_DB_OBJECT');
		}

		return $this->db->quoteName($name);
	}

	/**
	 * Add a RIGHT JOIN clause to the query.
	 *
	 * @param   string  $conditions  A string or array of conditions.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function rightJoin($conditions)
	{
		$this->join('RIGHT', $conditions);

		return $this;
	}

	/**
	 * Add a single column, or array of columns to the SELECT clause of the query.
	 *
	 * Note that you must not mix insert, update, delete and select method calls when building a query.
	 * The select method can, however, be called multiple times in the same query.
	 *
	 * @param   mixed  $columns  A string or an array of field names.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function select($columns)
	{
		$this->type = 'select';

		if (is_null($this->select)) {
			$this->select = new JDatabaseQueryElement('SELECT', $columns);
		}
		else {
			$this->select->append($columns);
		}

		return $this;
	}

	/**
	 * Add a single condition string, or an array of strings to the SET clause of the query.
	 *
	 * @param   mixed   $conditions  A string or array of conditions.
	 * @param   string  $glue        The glue by which to join the condition strings. Defaults to ,.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function set($conditions, $glue=',')
	{
		if (is_null($this->set)) {
			$glue = strtoupper($glue);
			$this->set = new JDatabaseQueryElement('SET', $conditions, "\n\t$glue ");
		}
		else {
			$this->set->append($conditions);
		}

		return $this;
	}

	/**
	 * Add a table name to the UPDATE clause of the query.
	 *
	 * Note that you must not mix insert, update, delete and select method calls when building a query.
	 *
	 * @param   mixed  $tables  A string or array of table names.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function update($tables)
	{
		$this->type = 'update';
		$this->update = new JDatabaseQueryElement('UPDATE', $tables);

		return $this;
	}

	/**
	 * Adds a tuple, or array of tuples that would be used as values for an INSERT INTO statement.
	 *
	 * @param  string  $values  A single tuple, or array of tuples.
	 *
	 * @return  JDatabaseQuerySQLAzure  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	function values($values)
	{
		if (is_null($this->values)) {
			$this->values = new JDatabaseQueryElement('()', $values, '), (');
		}
		else {
			$this->values->append($values);
		}

		return $this;
	}

	/**
	 * Add a single condition, or an array of conditions to the WHERE clause of the query.
	 *
	 * @param   mixed   $conditions  A string or array of where conditions.
	 * @param   string  $glue        The glue by which to join the conditions. Defaults to AND.
	 *
	 * @return  JDatabaseQuery  Returns this object to allow chaining.
	 *
	 * @since   11.1
	 */
	public function where($conditions, $glue = 'AND')
	{
		if (is_null($this->where)) {
			$glue = strtoupper($glue);
			$this->where = new JDatabaseQueryElement('WHERE', $conditions, " $glue ");
		}
		else {
			$this->where->append($conditions);
		}

		return $this;
	}
}

Tags: , , , , , , , , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка

Прямое подключение к базе данных из модели в Joomla 1.7

Май 27, 2012

Подключиться из модели напрямую из метода к базе данных довольно просто и делается в одну строку:

$db = $this->getDbo();

Метод getDbo находится в классе JModel и возвращает объект базы данных.

Далее работа осуществляется посредством методов класса JDatabase:

<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Database
 *
 * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;

JLoader::register('DatabaseException', JPATH_PLATFORM.'/joomla/database/databaseexception.php');
jimport('joomla.filesystem.folder');

interface JDatabaseInterface {
	/**
	 * Test to see if the connector is available.
	 *
	 * @return  bool  True on success, false otherwise.
	 *
	 * @since   11.1
	 */
	static function test();
}

/**
 * Database connector class.
 *
 * @package     Joomla.Platform
 * @subpackage  Database
 * @since       11.1
 */
abstract class JDatabase implements JDatabaseInterface
{
	/**
	 * @var    string  The name of the database driver.
	 * @since  11.1
	 */
	public $name;

	/**
	 * @var    resource  The database connection resource.
	 * @since  11.1
	 */
	protected $connection;

	/**
	 * @var    integer  The number of SQL statements executed by the database driver.
	 * @since  11.1
	 */
	protected $count = 0;

	/**
	 * @var    resource  The database connection cursor from the last query.
	 * @since  11.1
	 */
	protected $cursor;

	/**
	 * @var    bool  The database driver debugging state.
	 * @since  11.1
	 */
	protected $debug = false;

	/**
	 * @var    integer  The affected row limit for the current SQL statement.
	 * @since  11.1
	 */
	protected $limit = 0;

	/**
	 * @var    array  The log of executed SQL statements by the database driver.
	 * @since  11.1
	 */
	protected $log = array();

	/**
	 * @var    string  The character(s) used to quote SQL statement names such as table names or field names,
	 *                 etc.  The child classes should define this as necessary.  If a single character string the
	 *                 same character is used for both sides of the quoted name, else the first character will be
	 *                 used for the opening quote and the second for the closing quote.
	 * @since  11.1
	 */
	protected $nameQuote;

	/**
	 * @var    string  The null or zero representation of a timestamp for the database driver.  This should be
	 *                 defined in child classes to hold the appropriate value for the engine.
	 * @since  11.1
	 */
	protected $nullDate;

	/**
	 * @var    integer  The affected row offset to apply for the current SQL statement.
	 * @since  11.1
	 */
	protected $offset = 0;

	/**
	 * @var    mixed  The current SQL statement to execute.
	 * @since  11.1
	 */
	protected $sql;

	/**
	 * @var    string  The common database table prefix.
	 * @since  11.1
	 */
	protected $tablePrefix;

	/**
	 * @var    bool  True if the database engine supports UTF-8 character encoding.
	 * @since  11.1
	 */
	protected $utf = false;

	/**
	 * @var         integer  The database error number
	 * @since       11.1
	 * @deprecated  12.1
	 */
	protected $errorNum = 0;

	/**
	 * @var         string  The database error message
	 * @since       11.1
	 * @deprecated  12.1
	 */
	protected $errorMsg;

	/**
	 * @var         bool  If true then there are fields to be quoted for the query.
	 * @since       11.1
	 * @deprecated  12.1
	 */
	protected $hasQuoted = false;

	/**
	 * @var         array  The fields that are to be quoted.
	 * @since       11.1
	 * @deprecated  12.1
	 */
	protected $quoted = array();

	/**
	 * @var    array  JDatabase instances container.
	 * @since  11.1
	 */
	protected static $instances = array();

	/**
	 * Get a list of available database connectors.  The list will only be populated with connectors that both
	 * the class exists and the static test method returns true.  This gives us the ability to have a multitude
	 * of connector classes that are self-aware as to whether or not they are able to be used on a given system.
	 *
	 * @return  array  An array of available database connectors.
	 *
	 * @since   11.1
	 */
	public static function getConnectors()
	{
		// Instantiate variables.
		$connectors = array();

		// Get a list of types.
		$types = JFolder::folders(dirname(__FILE__));

		// Loop through the types and find the ones that are available.
		foreach($types as $type)
		{
			// Ignore some folders.
			if (($type == 'database') || ($type == 'table') || ($type == '.') || ($type == '..')) {
				continue;
			}

			// Derive the class name from the type.
			$class = 'JDatabaseDriver'.ucfirst(trim($type));

			// If the class doesn't exist, let's look for it and register it.
			if (!class_exists($class)) {

				// Derive the file path for the driver class.
				$path = dirname(__FILE__).'/'.$type.'/driver.php';

				// If the file exists register the class with our class loader.
				if (file_exists($path)) {
					JLoader::register($class, $path);
				}
				// If it doesn't exist we are at an impasse so move on to the next type.
				else {
					continue;
				}
			}

			// If the class still doesn't exist we have nothing left to do but look at the next type.  We did our best.
			if (!class_exists($class)) {
				continue;
			}

			// Sweet!  Our class exists, so now we just need to know if it passes it's test method.
			if (call_user_func_array(array($class, 'test'), array())) {
				$connectors[] = $type;
			}
		}

		return $connectors;
	}

	/**
	 * Method to return a JDatabase instance based on the given options.  There are three global options and then
	 * the rest are specific to the database driver.  The 'driver' option defines which JDatabaseDriver class is
	 * used for the connection -- the default is 'mysql'.  The 'database' option determines which database is to
	 * be used for the connection.  The 'select' option determines whether the connector should automatically select
	 * the chosen database.
	 *
	 * Instances are unique to the given options and new objects are only created when a unique options array is
	 * passed into the method.  This ensures that we don't end up with unnecessary database connection resources.
	 *
	 * @param   array  $options  Parameters to be passed to the database driver.
	 *
	 * @return  JDatabase  A database object.
	 *
	 * @since   11.1
	 */
	public static function getInstance($options = array())
	{
		// Sanitize the database connector options.
		$options['driver'] = (isset($options['driver'])) ? preg_replace('/[^A-Z0-9_\.-]/i', '', $options['driver']) : 'mysql';
		$options['database'] = (isset($options['database'])) ? $options['database'] : null;
		$options['select'] = (isset($options['select'])) ? $options['select'] : true;

		// Get the options signature for the database connector.
		$signature = md5(serialize($options));

		// If we already have a database connector instance for these options then just use that.
		if (empty(self::$instances[$signature])) {

			// Derive the class name from the driver.
			$class = 'JDatabase'.ucfirst($options['driver']);

			// If the class doesn't exist, let's look for it and register it.
			if (!class_exists($class)) {

				// Derive the file path for the driver class.
				$path = dirname(__FILE__).'/database/'.$options['driver'].'.php';

				// If the file exists register the class with our class loader.
				if (file_exists($path)) {
					JLoader::register($class, $path);
				}
				// If it doesn't exist we are at an impasse so throw an exception.
				else {

					// Legacy error handling switch based on the JError::$legacy switch.
					// @deprecated  12.1
					if (JError::$legacy) {
						JError::setErrorHandling(E_ERROR, 'die');
						return JError::raiseError(500, JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
					}
					else {
						throw new DatabaseException(JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
					}
				}
			}

			// If the class still doesn't exist we have nothing left to do but throw an exception.  We did our best.
			if (!class_exists($class)) {

				// Legacy error handling switch based on the JError::$legacy switch.
				// @deprecated  12.1
				if (JError::$legacy) {
					JError::setErrorHandling(E_ERROR, 'die');
					return JError::raiseError(500, JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
				}
				else {
					throw new DatabaseException(JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
				}
			}

			// Create our new JDatabase connector based on the options given.
			try {
				$instance = new $class($options);
			}
			catch (DatabaseException $e) {

				// Legacy error handling switch based on the JError::$legacy switch.
				// @deprecated  12.1
				if (JError::$legacy) {
					JError::setErrorHandling(E_ERROR, 'ignore');
					return JError::raiseError(500, JText::sprintf('JLIB_DATABASE_ERROR_CONNECT_DATABASE', $e->getMessage()));
				}
				else {
					throw new DatabaseException(JText::sprintf('JLIB_DATABASE_ERROR_CONNECT_DATABASE', $e->getMessage()));
				}
			}

			// Set the new connector to the global instances based on signature.
			self::$instances[$signature] = $instance;
		}

		return self::$instances[$signature];
	}

	/**
	 * Splits a string of multiple queries into an array of individual queries.
	 *
	 * @param   string  Input SQL string with which to split into individual queries.
	 *
	 * @return  array   The queries from the input string separated into an array.
	 *
	 * @since   11.1
	 */
	public static function splitSql($sql)
	{
		$start = 0;
		$open = false;
		$char = '';
		$end = strlen($sql);
		$queries = array();

		for ($i = 0; $i < $end; $i++)
		{
			$current = substr($sql, $i, 1);
			if (($current == '"' || $current == '\'')) {
				$n = 2;

				while (substr($sql, $i - $n + 1, 1) == '\\' && $n < $i)
				{
					$n ++;
				}

				if ($n%2==0) {
					if ($open) {
						if ($current == $char) {
							$open = false;
							$char = '';
						}
					} else {
						$open = true;
						$char = $current;
					}
				}
			}

			if (($current == ';' && !$open)|| $i == $end - 1) {
				$queries[] = substr($sql, $start, ($i - $start + 1));
				$start = $i + 1;
			}
		}

		return $queries;
	}

	/**
	 * Magic method to provide method alias support for quote() and quoteName().
	 *
	 * @param   string  $method  The called method.
	 * @param   array   $args    The array of arguments passed to the method.
	 *
	 * @return  string  The aliased method's return value or null.
	 *
	 * @since   11.1
	 */
	public function __call($method, $args)
	{
		if (empty($args)) {
			return;
		}

		switch ($method)
		{
			case 'q':
				return $this->quote($args[0], isset($args[1]) ? $args[1] : true);
				break;
			case 'nq':
			case 'qn':
				return $this->quoteName($args[0]);
				break;
		}
	}

	/**
	 * Constructor.
	 *
	 * @param   array  $options  List of options used to configure the connection
	 *
	 * @return  void
	 *
	 * @since   11.1
	 */
	protected function __construct($options)
	{
		// Initialise object variables.
		$this->tablePrefix = (isset($options['prefix'])) ? $options['prefix'] : 'jos_';
		$this->count       = 0;
		$this->errorNum    = 0;
		$this->log         = array();
		$this->quoted      = array();
		$this->hasQuoted   = false;

		// Determine UTF-8 support.
		$this->utf = $this->hasUTF();

		// Set charactersets (needed for MySQL 4.1.2+).
		if ($this->utf){
			$this->setUTF();
		}
	}

	/**
	 * Adds a field or array of field names to the list that are to be quoted.
	 *
	 * @param       mixed  $quoted  Field name or array of names.
	 *
	 * @return      void
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function addQuoted($quoted)
	{
		// Deprecation warning.
		JLog::add('JDatabase::addQuoted() is deprecated.', JLog::WARNING, 'deprecated');

		if (is_string($quoted)) {
			$this->quoted[] = $quoted;
		}
		else {
			$this->quoted = array_merge($this->quoted, (array) $quoted);
		}

		$this->hasQuoted = true;
	}

	/**
	 * Determines if the connection to the server is active.
	 *
	 * @return  bool  True if connected to the database engine.
	 *
	 * @since   11.1
	 */
	abstract public function connected();

	/**
	 * Method to escape a string for usage in an SQL statement.
	 *
	 * @param   string  The string to be escaped.
	 * @param   bool    Optional parameter to provide extra escaping.
	 *
	 * @return  string  The escaped string.
	 *
	 * @since   11.1
	 */
	abstract public function escape($text, $extra = false);

	/**
	 * Method to fetch a row from the result set cursor as an array.
	 *
	 * @param   mixed  $cursor  The optional result set cursor from which to fetch the row.
	 *
	 * @return  mixed  Either the next row from the result set or false if there are no more rows.
	 *
	 * @since   11.1
	 */
	abstract protected function fetchArray($cursor = null);

	/**
	 * Method to fetch a row from the result set cursor as an associative array.
	 *
	 * @param   mixed  $cursor  The optional result set cursor from which to fetch the row.
	 *
	 * @return  mixed  Either the next row from the result set or false if there are no more rows.
	 *
	 * @since   11.1
	 */
	abstract protected function fetchAssoc($cursor = null);

	/**
	 * Method to fetch a row from the result set cursor as an object.
	 *
	 * @param   mixed   $cursor  The optional result set cursor from which to fetch the row.
	 * @param   string  $class   The class name to use for the returned row object.
	 *
	 * @return  mixed   Either the next row from the result set or false if there are no more rows.
	 *
	 * @since   11.1
	 */
	abstract protected function fetchObject($cursor = null, $class = 'stdClass');

	/**
	 * Method to free up the memory used for the result set.
	 *
	 * @param   mixed  $cursor  The optional result set cursor from which to fetch the row.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 */
	abstract protected function freeResult($cursor = null);

	/**
	 * Get the number of affected rows for the previous executed SQL statement.
	 *
	 * @return  integer  The number of affected rows.
	 *
	 * @since   11.1
	 */
	abstract public function getAffectedRows();

	/**
	 * Method to get the database collation in use by sampling a text field of a table in the database.
	 *
	 * @return  mixed  The collation in use by the database or boolean false if not supported.
	 *
	 * @since   11.1
	 */
	abstract public function getCollation();

	/**
	 * Method that provides access to the underlying database connection. Useful for when you need to call a
	 * proprietary method such as postgresql's lo_* methods.
	 *
	 * @return  resource  The underlying database connection resource.
	 *
	 * @since   11.1
	 */
	public function getConnection()
	{
		return $this->connection;
	}

	/**
	 * Get the total number of SQL statements executed by the database driver.
	 *
	 * @return  integer
	 *
	 * @since   11.1
	 */
	public function getCount()
	{
		return $this->count;
	}

	/**
	 * Returns a PHP date() function compliant date format for the database driver.
	 *
	 * @return  string  The format string.
	 *
	 * @since   11.1
	 */
	public function getDateFormat()
	{
		return 'Y-m-d H:i:s';
	}

	/**
	 * Get the database driver SQL statement log.
	 *
	 * @return  array  SQL statements executed by the database driver.
	 *
	 * @since   11.1
	 */
	public function getLog()
	{
		return $this->log;
	}

	/**
	 * Get the null or zero representation of a timestamp for the database driver.
	 *
	 * @return  string  Null or zero representation of a timestamp.
	 *
	 * @since   11.1
	 */
	public function getNullDate()
	{
		return $this->nullDate;
	}

	/**
	 * Get the number of returned rows for the previous executed SQL statement.
	 *
	 * @param   resource  $cursor  An optional database cursor resource to extract the row count from.
	 *
	 * @return  integer   The number of returned rows.
	 *
	 * @since   11.1
	 */
	abstract public function getNumRows($cursor = null);

	/**
	 * Get the common table prefix for the database driver.
	 *
	 * @return  string  The common database table prefix.
	 *
	 * @since   11.1
	 */
	public function getPrefix()
	{
		return $this->tablePrefix;
	}

	/**
	 * Get the current or query, or new JDatabaseQuery object.
	 *
	 * @param   bool   $new  False to return the last query set, True to return a new JDatabaseQuery object.
	 *
	 * @return  mixed  The current value of the internal SQL variable or a new JDatabaseQuery object.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function getQuery($new = false);

	/**
	 * Retrieves field information about the given tables.
	 *
	 * @param   mixed  $tables    A table name or a list of table names.
	 * @param   bool   $typeOnly  True to only return field types.
	 *
	 * @return  array  An array of fields by table.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function getTableColumns($tables, $typeOnly = true);

	/**
	 * Shows the table CREATE statement that creates the given tables.
	 *
	 * @param   mixed  $tables  A table name or a list of table names.
	 *
	 * @return  array  A list of the create SQL for the tables.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function getTableCreate($tables);

	/**
	 * Retrieves field information about the given tables.
	 *
	 * @param   mixed  $tables    A table name or a list of table names.
	 *
	 * @return  array  An array of keys for the table(s).
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function getTableKeys($tables);

	/**
	 * Method to get an array of all tables in the database.
	 *
	 * @return  array  An array of all the tables in the database.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function getTableList();

	/**
	 * Determine whether or not the database engine supports UTF-8 character encoding.
	 *
	 * @return  bool  True if the database engine supports UTF-8 character encoding.
	 *
	 * @since   11.1
	 */
	public function getUTFSupport()
	{
		return $this->utf;
	}

	/**
	 * Get the version of the database connector
	 *
	 * @return  string  The database connector version.
	 *
	 * @since   11.1
	 */
	abstract public function getVersion();

	/**
	 * Determines if the database engine supports UTF-8 character encoding.
	 *
	 * @return  boolean  True if supported.
	 *
	 * @since   11.1
	 */
	abstract public function hasUTF();

	/**
	 * Method to get the auto-incremented value from the last INSERT statement.
	 *
	 * @return  integer  The value of the auto-increment field from the last inserted row.
	 *
	 * @since   11.1
	 */
	abstract public function insertid();

	/**
	 * Inserts a row into a table based on an object's properties.
	 *
	 * @param   string  $table   The name of the database table to insert into.
	 * @param   object  $object  A reference to an object whose public properties match the table fields.
	 * @param   string  $key     The name of the primary key. If provided the object property is updated.
	 *
	 * @return  bool    True on success.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function insertObject($table, & $object, $key = null)
	{
		// Initialise variables.
		$fields = array();
		$values = array();

		// Create the base insert statement.
		$statement = 'INSERT INTO '.$this->quoteName($table).' (%s) VALUES (%s)';

		// Iterate over the object variables to build the query fields and values.
		foreach (get_object_vars($object) as $k => $v)
		{
			// Only process non-null scalars.
			if (is_array($v) or is_object($v) or $v === null) {
				continue;
			}

			// Ignore any internal fields.
			if ($k[0] == '_') {
				continue;
			}

			// Prepare and sanitize the fields and values for the database query.
			$fields[] = $this->quoteName($k);
			$values[] = $this->isQuoted($k) ? $this->quote($v) : (int) $v;
		}

		// Set the query and execute the insert.
		$this->setQuery(sprintf($statement, implode(',', $fields),  implode(',', $values)));
		if (!$this->query()) {
			return false;
		}

		// Update the primary key if it exists.
		$id = $this->insertid();
		if ($key && $id) {
			$object->$key = $id;
		}

		return true;
	}

	/**
	 * Method to get the first row of the result set from the database query as an associative array
	 * of ['field_name' => 'row_value'].
	 *
	 * @return  mixed  The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadAssoc()
	{
		// Initialise variables.
		$ret = null;

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get the first row from the result set as an associative array.
		if ($array = $this->fetchAssoc($cursor)) {
			$ret = $array;
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $ret;
	}

	/**
	 * Method to get an array of the result set rows from the database query where each row is an associative array
	 * of ['field_name' => 'row_value'].  The array of rows can optionally be keyed by a field name, but defaults to
	 * a sequential numeric array.
	 *
	 * NOTE: Chosing to key the result array by a non-unique field name can result in unwanted
	 * behavior and should be avoided.
	 *
	 * @param   string  $key     The name of a field on which to key the result array.
	 * @param   string  $column  An optional column name. Instead of the whole row, only this column value will be in
	 *                           the result array.
	 *
	 * @return  mixed   The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadAssocList($key = null, $column = null)
	{
		// Initialise variables.
		$array = array();

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get all of the rows from the result set.
		while ($row = $this->fetchAssoc($cursor))
		{
			$value = ($column) ? (isset($row[$column]) ? $row[$column] : $row) : $row;
			if ($key) {
				$array[$row[$key]] = $value;
			}
			else {
				$array[] = $value;
			}
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $array;
	}

	/**
	 * Method to get an array of values from the <var>$offset</var> field in each row of the result set from
	 * the database query.
	 *
	 * @param   integer  $offset  The row offset to use to build the result array.
	 *
	 * @return  mixed    The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadColumn($offset = 0)
	{
		// Initialise variables.
		$array = array();

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get all of the rows from the result set as arrays.
		while ($row = $this->fetchArray($cursor))
		{
			$array[] = $row[$offset];
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $array;
	}

	/**
	 * Method to get the next row in the result set from the database query as an object.
	 *
	 * @param   string  $class  The class name to use for the returned row object.
	 *
	 * @return  mixed   The result of the query as an array, false if there are no more rows.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadNextObject($class = 'stdClass')
	{
		static $cursor;

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return $this->errorNum ? null : false;
		}

		// Get the next row from the result set as an object of type $class.
		if ($row = $this->fetchObject($cursor, $class)) {
			return $row;
		}

		// Free up system resources and return.
		$this->freeResult($cursor);
		$cursor = null;

		return false;
	}

	/**
	 * Method to get the next row in the result set from the database query as an array.
	 *
	 * @return  mixed  The result of the query as an array, false if there are no more rows.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadNextRow()
	{
		static $cursor;

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return $this->errorNum ? null : false;
		}

		// Get the next row from the result set as an object of type $class.
		if ($row = $this->fetchArray($cursor)) {
			return $row;
		}

		// Free up system resources and return.
		$this->freeResult($cursor);
		$cursor = null;

		return false;
	}

	/**
	 * Method to get the first row of the result set from the database query as an object.
	 *
	 * @param   string  $class  The class name to use for the returned row object.
	 *
	 * @return  mixed   The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadObject($class = 'stdClass')
	{
		// Initialise variables.
		$ret = null;

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get the first row from the result set as an object of type $class.
		if ($object = $this->fetchObject($cursor, $class)) {
			$ret = $object;
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $ret;
	}

	/**
	 * Method to get an array of the result set rows from the database query where each row is an object.  The array
	 * of objects can optionally be keyed by a field name, but defaults to a sequential numeric array.
	 *
	 * NOTE: Chosing to key the result array by a non-unique field name can result in unwanted
	 * behavior and should be avoided.
	 *
	 * @param   string  $key    The name of a field on which to key the result array.
	 * @param   string  $class  The class name to use for the returned row objects.
	 *
	 * @return  mixed   The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadObjectList($key='', $class = 'stdClass')
	{
		// Initialise variables.
		$array = array();

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get all of the rows from the result set as objects of type $class.
		while ($row = $this->fetchObject($cursor, $class))
		{
			if ($key) {
				$array[$row->$key] = $row;
			}
			else {
				$array[] = $row;
			}
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $array;
	}

	/**
	 * Method to get the first field of the first row of the result set from the database query.
	 *
	 * @return  mixed  The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadResult()
	{
		// Initialise variables.
		$ret = null;

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get the first row from the result set as an array.
		if ($row = $this->fetchArray($cursor)) {
			$ret = $row[0];
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $ret;
	}

	/**
	 * Method to get the first row of the result set from the database query as an array.  Columns are indexed
	 * numerically so the first column in the result set would be accessible via <var>$row[0]</var>, etc.
	 *
	 * @return  mixed  The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadRow()
	{
		// Initialise variables.
		$ret = null;

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get the first row from the result set as an array.
		if ($row = $this->fetchArray($cursor)) {
			$ret = $row;
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $ret;
	}

	/**
	 * Method to get an array of the result set rows from the database query where each row is an array.  The array
	 * of objects can optionally be keyed by a field offset, but defaults to a sequential numeric array.
	 *
	 * NOTE: Chosing to key the result array by a non-unique field can result in unwanted
	 * behavior and should be avoided.
	 *
	 * @param   string  $key  The name of a field on which to key the result array.
	 *
	 * @return  mixed   The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function loadRowList($key=null)
	{
		// Initialise variables.
		$array = array();

		// Execute the query and get the result set cursor.
		if (!($cursor = $this->query())) {
			return null;
		}

		// Get all of the rows from the result set as arrays.
		while ($row = $this->fetchArray($cursor))
		{
			if ($key !== null) {
				$array[$row[$key]] = $row;
			}
			else {
				$array[] = $row;
			}
		}

		// Free up system resources and return.
		$this->freeResult($cursor);

		return $array;
	}

	/**
	 * Execute the SQL statement.
	 *
	 * @return  mixed  A database cursor resource on success, boolean false on failure.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function query();

	/**
	 * Method to quote and optionally escape a string to database requirements for insertion into the database.
	 *
	 * @param   string  $text    The string to quote.
	 * @param   bool    $escape  True to escape the string, false to leave it unchanged.
	 *
	 * @return  string  The quoted input string.
	 *
	 * @since   11.1
	 */
	public function quote($text, $escape = true)
	{
		return '\''.($escape ? $this->escape($text) : $text).'\'';
	}

	/**
	 * Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection
	 * risks and reserved word conflicts.
	 *
	 * @param   string  $name  The identifier name to wrap in quotes.
	 *
	 * @return  string  The quote wrapped name.
	 *
	 * @since   11.1
	 */
	public function quoteName($name)
	{
		// Don't quote names with dot-notation.
		if (strpos($name, '.') !== false) {
			return $name;
		}
		else {
			$q = $this->nameQuote;

			if (strlen($q) == 1) {
				return $q.$name.$q;
			}
			else {
				return $q{0}.$name.$q{1};
			}
		}
	}

	/**
	 * This function replaces a string identifier <var>$prefix</var> with the string held is the
	 * <var>tablePrefix</var> class variable.
	 *
	 * @param   string  $sql     The SQL statement to prepare.
	 * @param   string  $prefix  The common table prefix.
	 *
	 * @return  string  The processed SQL statement.
	 *
	 * @since   11.1
	 */
	public function replacePrefix($sql, $prefix='#__')
	{
		// Initialize variables.
		$escaped = false;
		$startPos = 0;
		$quoteChar = '';
		$literal = '';

		$sql = trim($sql);
		$n = strlen($sql);

		while ($startPos < $n)
		{
			$ip = strpos($sql, $prefix, $startPos);
			if ($ip === false) {
				break;
			}

			$j = strpos($sql, "'", $startPos);
			$k = strpos($sql, '"', $startPos);
			if (($k !== false) && (($k < $j) || ($j === false))) {
				$quoteChar	= '"';
				$j			= $k;
			} else {
				$quoteChar	= "'";
			}

			if ($j === false) {
				$j = $n;
			}

			$literal .= str_replace($prefix, $this->tablePrefix, substr($sql, $startPos, $j - $startPos));
			$startPos = $j;

			$j = $startPos + 1;

			if ($j >= $n) {
				break;
			}

			// quote comes first, find end of quote
			while (true)
			{
				$k = strpos($sql, $quoteChar, $j);
				$escaped = false;
				if ($k === false) {
					break;
				}
				$l = $k - 1;
				while ($l >= 0 && $sql{$l} == '\\')
				{
					$l--;
					$escaped = !$escaped;
				}
				if ($escaped) {
					$j	= $k+1;
					continue;
				}
				break;
			}
			if ($k === false) {
				// error in the query - no end quote; ignore it
				break;
			}
			$literal .= substr($sql, $startPos, $k - $startPos + 1);
			$startPos = $k+1;
		}
		if ($startPos < $n) {
			$literal .= substr($sql, $startPos, $n - $startPos);
		}

		return $literal;
	}

	/**
	 * Select a database for use.
	 *
	 * @param   string  $database  The name of the database to select for use.
	 *
	 * @return  bool  True if the database was successfully selected.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function select($database);

	/**
	 * Sets the database debugging state for the driver.
	 *
	 * @param   bool  $level  True to enable debugging.
	 *
	 * @return  bool  The old debugging level.
	 *
	 * @since   11.1
	 */
	public function setDebug($level)
	{
		$previous = $this->debug;
		$this->debug = (bool) $level;

		return $previous;
	}

	/**
	 * Sets the SQL statement string for later execution.
	 *
	 * @param   mixed    $query   The SQL statement to set either as a JDatabaseQuery object or a string.
	 * @param   integer  $offset  The affected row offset to set.
	 * @param   integer  $limit   The maximum affected rows to set.
	 *
	 * @return  JDatabase  This object to support method chaining.
	 *
	 * @since   11.1
	 */
	public function setQuery($query, $offset = 0, $limit = 0)
	{
		$this->sql		= $query;
		$this->limit	= (int) $limit;
		$this->offset	= (int) $offset;

		return $this;
	}

	/**
	 * Set the connection to use UTF-8 character encoding.
	 *
	 * @return  bool  True on success.
	 *
	 * @since   11.1
	 */
	abstract public function setUTF();

	/**
	 * Method to commit a transaction.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function transactionCommit();

	/**
	 * Method to roll back a transaction.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function transactionRollback();

	/**
	 * Method to initialize a transaction.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	abstract public function transactionStart();

	/**
	 * Updates a row in a table based on an object's properties.
	 *
	 * @param   string  $table   The name of the database table to update.
	 * @param   object  $object  A reference to an object whose public properties match the table fields.
	 * @param   string  $key     The name of the primary key.
	 * @param   bool    $nulls   True to update null fields or false to ignore them.
	 *
	 * @return  bool    True on success.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 */
	public function updateObject($table, & $object, $key, $nulls=false)
	{
		// Initialise variables.
		$fields = array();
		$where  = '';

		// Create the base update statement.
		$statement = 'UPDATE '.$this->quoteName($table).' SET %s WHERE %s';

		// Iterate over the object variables to build the query fields/value pairs.
		foreach (get_object_vars($object) as $k => $v)
		{
			// Only process scalars that are not internal fields.
			if (is_array($v) or is_object($v) or $k[0] == '_') {
				continue;
			}

			// Set the primary key to the WHERE clause instead of a field to update.
			if ($k == $key) {
				$where = $this->quoteName($k).'='.$this->quote($v);
				continue;
			}

			// Prepare and sanitize the fields and values for the database query.
			if ($v === null) {
				// If the value is null and we want to update nulls then set it.
				if ($nulls) {
					$val = 'NULL';
				}
				// If the value is null and we do not want to update nulls then ignore this field.
				else {
					continue;
				}
			}
			// The field is not null so we prep it for update.
			else {
				$val = $this->isQuoted($k) ? $this->quote($v) : (int) $v;
			}

			// Add the field to be updated.
			$fields[] = $this->quoteName($k).'='.$val;
		}

		// We don't have any fields to update.
		if (empty($fields)) {
			return true;
		}

		// Set the query and execute the update.
		$this->setQuery(sprintf($statement, implode(",", $fields), $where));
		return $this->query();
	}

	//
	// Deprecated methods.
	//

	/**
	 * Sets the debug level on or off
	 *
	 * @param       integer  $level  0 to disable debugging and 1 to enable it.
	 *
	 * @return      void
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function debug($level)
	{
		// Deprecation warning.
		JLog::add('JDatabase::debug() is deprecated, use JDatabase::setDebug() instead.', JLog::NOTICE, 'deprecated');

		$this->setDebug(($level == 0) ? false : true);
	}

	/**
	 * Diagnostic method to return explain information for a query.
	 *
	 * @return      string  The explain output.
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	abstract public function explain();

	/**
	 * Gets the error message from the database connection.
	 *
	 * @param       bool  $escaped  True to escape the message string for use in JavaScript.
	 *
	 * @return      string  The error message for the most recent query.
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function getErrorMsg($escaped = false)
	{
		// Deprecation warning.
		JLog::add('JDatabase::getErrorMsg() is deprecated, use exception handling instead.', JLog::WARNING, 'deprecated');

		if ($escaped) {
			return addslashes($this->errorMsg);
		} else {
			return $this->errorMsg;
		}
	}

	/**
	 * Gets the error number from the database connection.
	 *
	 * @return      integer  The error number for the most recent query.
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function getErrorNum()
	{
		// Deprecation warning.
		JLog::add('JDatabase::getErrorNum() is deprecated, use exception handling instead.', JLog::WARNING, 'deprecated');

		return $this->errorNum;
	}

	/**
	 * Method to escape a string for usage in an SQL statement.
	 *
	 * @param   string  The string to be escaped.
	 * @param   bool    Optional parameter to provide extra escaping.
	 *
	 * @return  string  The escaped string.
	 *
	 * @since   11.1
	 * @deprecated  11.1
	 */
	public function getEscaped($text, $extra = false)
	{
		// Deprecation warning.
		JLog::add('JDatabase::getEscaped() is deprecated. Use JDatabase::escape().', JLog::WARNING, 'deprecated');

		return $this->escape($text, $extra);
	}

	/**
	 * Retrieves field information about the given tables.
	 *
	 * @param   mixed  $tables    A table name or a list of table names.
	 * @param   bool   $typeOnly  True to only return field types.
	 *
	 * @return  array  An array of fields by table.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 * @deprecated  11.1
	 */
	public function getTableFields($tables, $typeOnly = true)
	{
		// Deprecation warning.
		JLog::add('JDatabase::getTableFields() is deprecated. Use JDatabase::getTableColumns().', JLog::WARNING, 'deprecated');

		$results = array();

		settype($tables, 'array');

		foreach ($tables as $table)
		{
			$results[$table] = $this->getTableColumns($table, $typeOnly);
		}

		return $results;
	}

	/**
	 * Get the total number of SQL statements executed by the database driver.
	 *
	 * @return      integer
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function getTicker()
	{
		// Deprecation warning.
		JLog::add('JDatabase::getTicker() is deprecated, use JDatabase::getCount() instead.', JLog::NOTICE, 'deprecated');

		return $this->count;
	}

	/**
	 * Checks if field name needs to be quoted.
	 *
	 * @param       string  $field  The field name to be checked.
	 *
	 * @return      bool
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function isQuoted($field)
	{
		// Deprecation warning.
		JLog::add('JDatabase::isQuoted() is deprecated.', JLog::WARNING, 'deprecated');

		if ($this->hasQuoted) {
			return in_array($field, $this->quoted);
		}
		else {
			return true;
		}
	}

	/**
	 * Method to get an array of values from the <var>$offset</var> field in each row of the result set from
	 * the database query.
	 *
	 * @param   integer  $offset  The row offset to use to build the result array.
	 *
	 * @return  mixed    The return value or null if the query failed.
	 *
	 * @since   11.1
	 * @throws  DatabaseException
	 * @deprecated  11.1
	 */
	public function loadResultArray($offset = 0)
	{
		// Deprecation warning.
		JLog::add('JDatabase::loadResultArray() is deprecated. Use JDatabase::getColumn().', JLog::WARNING, 'deprecated');

		return $this->loadColumn($offset);
	}

	/**
	 * Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection
	 * risks and reserved word conflicts.
	 *
	 * @param   string  $name  The identifier name to wrap in quotes.
	 *
	 * @return  string  The quote wrapped name.
	 *
	 * @since   11.1
	 * @deprecated  11.1
	 */
	public function nameQuote($name)
	{
		// Deprecation warning.
		JLog::add('JDatabase::nameQuote() is deprecated. Use JDatabase::quoteName().', JLog::WARNING, 'deprecated');

		return $this->quoteName($name);
	}

	/**
	 * Execute a query batch.
	 *
	 * @return      mixed  A database resource if successful, false if not.
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	abstract public function queryBatch($abortOnError = true, $transactionSafe = false);

	/**
	 * Return the most recent error message for the database connector.
	 *
	 * @param       bool  True to display the SQL statement sent to the database as well as the error.
	 *
	 * @return      string  The error message for the most recent query.
	 *
	 * @since       11.1
	 * @deprecated  12.1
	 */
	public function stderr($showSQL = false)
	{
		// Deprecation warning.
		JLog::add('JDatabase::stderr() is deprecated.', JLog::WARNING, 'deprecated');

		if ($this->errorNum != 0) {
			return JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $this->errorNum, $this->errorMsg)
				.($showSQL ? "<br />SQL = <pre>$this->sql</pre>" : '');
		}
		else {
			return JText::_('JLIB_DATABASE_FUNCTION_NOERROR');
		}
	}
}

Tags: , , , , , , , , ,
Записано в Joomla, Программирование    |    Постоянная ссылка