Joomla!-开源天空

2009-01-10
您所在的位置: 首页 > Joomla专栏 > 源代码分析 > 编写Joomla!搜索插件plugin

编写Joomla!搜索插件plugin

Joomla! 开源天空  作者:管理员  2008-10-23 15:43
  • 摘要:本文以实际代码说明了如何制作Joomla!的搜索插件,从而来给第三方的Joomla!扩展添加搜索功能。

默认的Joomla!系统搜索只能搜索文章,联系等等系统核心的内容,而对于第三方的扩展则不能搜索,本文将介绍如何给第三方的扩展加上搜索插件,从而能够通过Joomla!系统搜索时候能够包含相应的结果。制作自定义的Joomla!搜索插件需要至少两个文件,一个是XML定义文件,一个是同名的php文件。

XML file

XML文件与PHP文件同名,采用UTF-8字符集。

<?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE install PUBLIC 
  "-//Joomla! 1.5//DTD plugin 1.0//EN" "http://dev.joomla.org/xml/1.5/plugin-install.dtd">

下面这一行指定这是一个搜索插件:

<install version="1.5" type="plugin" group="search">

接下来定义一些信息: 

<name>Name of your search plugin</name>
<creationDate>Creation date</creationDate>
<author>Your name</author>
<authorEmail>Your e-mail address</authorEmail>
<authorUrl>Your website</authorUrl>
<copyright>Copyright information</copyright>
<license>License, for example GNU/GPL</license>
<version>Version of the plugin</version>
<description>Description of the plugin; showed during installation and when editing 
the plugin in the Plugin Manager</description>

接下来我们定义这个插件的文件,php文件的名字要与plugin=''的内容相同,当然还可以有其他文件,比如图片文件等等。

<files>
   <filename plugin="nameofplugin">nameofplugin.php</filename>
</files>

为了多语言版本,还应该定义语言文件,ini文件的命名规则如下:

<languages>
   <language tag="en-GB">language/en-GB/en-GB.plg_search_nameofplugin.ini</language>
</languages>

在XML文件中还可以定义插件的参数:

<params>
   <param name="paramname" type="typeofparameter" default="defaultsetting" label="title" description="description"/>
</params>
  • Param name: The name of the parameter. You will need this when creating the PHP file.
  • Param type: You could choose between several types of parameters. Look at this document to learn something about the different types: [3]
  • Param default: The default setting for this parameter.
  • Param label: The name of this parameter displayed in the edit screen of this plugin in the Plugin Manager.
  • Param description: The text which appears as a tool tip for this parameter.

最后不要忘记install标签的封闭:

</install>

PHP file

php文件是最重要的部分,其中应该包括两个注册事件,一个是'onSearchAreas',一个是onsearch,以下在文件中说明了应该注意的地方:

<?php
//First start with information about the Plugin and yourself. For example:
/**
 * @version		$Id: nameofplugin.php versionnumber date author
 * @copyright	        Copyright
 * @license		License, for example GNU/GPL
 * All other information you would like to add
 */
 
//To prevent accessing the document directly, enter this code:
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
 
//Now define the registerEvent and the language file. Replace 'nameofplugin' with the name of your plugin.
$mainframe->registerEvent( 'onSearch', 'plgSearchnameofplugin' );
$mainframe->registerEvent( 'onSearchAreas', 'plgSearchnameofpluginAreas' );
 
JPlugin::loadLanguage( 'plg_search_nameofplugin' );
 
//Then define a function to return an array of search areas. Replace 'nameofplugin' with the name of your plugin.
function &plgSearchnameofpluginAreas()
{
	static $areas = array(
		'nameofplugin' => 'Nameofplugin'
	);
	return $areas;
}
 
//Then the real function has to be created. The database connection should be made. 
//The function will be closed with an } at the end of the file.
function plgSearchnameofplugin( $text, $phrase='', $ordering='', $areas=null )
{
	$db		=& JFactory::getDBO();
	$user	=& JFactory::getUser(); 
 
//If the array is not correct, return it:
	if (is_array( $areas )) {
		if (!array_intersect( $areas, array_keys( plgSearchnameofpluginAreas() ) )) {
			return array();
		}
	}
 
//It is time to define the parameters! First get the right plugin; 'search' (the group), 'nameofplugin'. 
$plugin =& JPluginHelper::getPlugin('search', 'nameofplugin');
 
//Then load the parameters of the plugin..
$pluginParams = new JParameter( $plugin->params );
 
//And define the parameters. For example like this..
$limit = $pluginParams->def( 'nameofparameter', defaultsetting );
 
//Use the function trim to delete spaces in front of or at the back of the searching terms
$text = trim( $text );
 
//Return Array when nothing was filled in
if ($text == '') {
		return array();
	}
 
//After this, you have to add the database part. This will be the most difficult part, because this changes per situation.
//In the coding examples later on you will find some of the examples used by Joomla! 1.5 core Search Plugins.
//It will look something like this.
	$wheres = array();
	switch ($phrase) {
 
//search exact
		case 'exact':
			$text		= $db->Quote( '%'.$db->getEscaped( $text, true ).'%', false );
			$wheres2 	= array();
			$wheres2[] 	= 'LOWER(a.name) LIKE '.$text;
			$where 		= '(' . implode( ') OR (', $wheres2 ) . ')';
			break;
 
//search all or any
		case 'all':
		case 'any':
 
//set default
		default:
			$words 	= explode( ' ', $text );
			$wheres = array();
			foreach ($words as $word)
			{
				$word		= $db->Quote( '%'.$db->getEscaped( $word, true ).'%', false );
				$wheres2 	= array();
				$wheres2[] 	= 'LOWER(a.name) LIKE '.$word;
				$wheres[] 	= implode( ' OR ', $wheres2 );
			}
			$where = '(' . implode( ($phrase == 'all' ? ') AND (' : ') OR ('), $wheres ) . ')';
			break;
	}
 
//ordering of the results
	switch ( $ordering ) {
 
//alphabetic, ascending
		case 'alpha':
			$order = 'a.name ASC';
			break;
 
//oldest first
		case 'oldest':
 
//popular first
		case 'popular':
 
//newest first
		case 'newest':
 
//default setting: alphabetic, ascending
		default:
			$order = 'a.name ASC';
	}
 
//replace nameofplugin
	$searchnameofplugin = JText::_( 'Nameofplugin' );
 
//the database query; differs per situation! It will look something like this:
	$query = 'SELECT a.name AS title'
	. ' CONCAT_WS( " / ", '. $db->Quote($searchNameofplugin) .', b.title )AS section,'
	. ' "1" AS browsernav'
	. ' FROM #__nameofplugin AS a'
	. ' INNER JOIN #__categories AS b ON b.id = a.catid'
	. ' WHERE ( '. $where .' )'
	. ' AND a.published = 1'
	. ' AND b.access <= '. (int) $user->get( 'aid' )
	. ' ORDER BY '. $order
	;
 
//Set query
	$db->setQuery( $query, 0, $limit );
	$rows = $db->loadObjectList();
 
//The 'output' of the displayed link
	foreach($rows as $key => $row) {
		$rows[$key]->href = 'index.php?option=com_newsfeeds&view=newsfeed&catid='.$row->catslug.'&id='.$row->slug;
	}
 
//Return the search results in an array
return $rows;
}

INI file(s)

For internationalization it is good to use the INI files. You can add everything to the language file that outputs text to the user, in this order:

  • XML description tag
  • XML label and description attributes from parameters
  • JText::_( 'string' ) used by the plugin

Start your INI file with something like this:

# $Id: en-GB.plg_search_nameofplugin.ini
# Joomla! Project
# Copyright (C) 2005 - 2007 Open Source Matters. All rights reserved.
# License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
# Note : All ini files need to be saved as UTF-8 - No BOM

Of course, you could also add other information, like the author.

For example, this parameter:

<param name="search_limit" type="text" size="5" default="50" label="Search Limit" 
description="Number of Search items to return"/>

Will cause the following output in the INI file:

SEARCH LIMIT=Search Limit
NUMBER OF SEARCH ITEMS TO RETURN=Number of Search items to return

The file looks repetitive, but will be very useful for translaters.

When you want to make your search plugin available in more languages, first add them to the <languages> tag in the XML file. Then create the same INI file, and change the part after the =, for example the dutch version would be:

SEARCH LIMIT=Zoek limiet
NUMBER OF SEARCH ITEMS TO RETURN=Aantal weer te geven zoekresultaten

Coding examples

There are six Joomla! Core Search Plugins. If you look at them you can learn a lot, especially about the query part. You can see them 'working' when you go to the back-end of your Joomla! 1.5 installation, then go to the menu 'Extensions' and select the 'Plugin Manager'. Click on the name of the plugin to edit it; and see it working.

  • Plugin Search - Categories
    • \plugins\search\categories.XML
    • \plugins\search\categories.PHP
    • \language\en-GB\en-GB.plg_search_categories.INI
  • Plugin Search - Contacts
    • \plugins\search\contacts.XML
    • \plugins\search\contacts.PHP
    • \language\en-GB\en-GB.plg_search_contacts.INI
  • Plugin Search - Content
    • \plugins\search\content.XML
    • \plugins\search\content.PHP
    • \language\en-GB\en-GB.plg_search_content.INI
  • Plugin Search - Newsfeeds
    • \plugins\search\newsfeeds.XML
    • \plugins\search\newsfeeds.PHP
    • \language\en-GB\en-GB.plg_search_newsfeeds.INI
  • Plugin Search - Sections
    • \plugins\search\sections.XML
    • \plugins\search\sections.PHP
    • \language\en-GB\en-GB.plg_search_sections.INI
  • Plugin Search - Weblinks
    • \plugins\search\weblinks.XML
    • \plugins\search\weblinks.PHP
    • \language\en-GB\en-GB.plg_search_weblinks.INI

Quick tips

  • In the PHP file, people often forget to place an semicolon (;) at the end of a row. This causes errors. Check this before you test your plugin.
  • Make sure the parameters in the XML file are closed correctly. When you add options, for example, you need to close it with </param>.
  • It is easy to test on a localhost when you are still busy with editing your plugin.
  • When making a zip-file to test it, do not forget to make the directories for the language files. A typical zip will contain the following:
    • nameofplugin.XML
    • nameofplugin.PHP
    • language\en-GB\en-GB.plg_search_nameofplugin.INI

  发表您的文章评论

您的姓名 (昵称)
标题:
评分: 很差一般较好很好
评论:
验证码:
请输入验证码