Actions

J1.5

Difference between revisions of "Creating a content plugin"

From Joomla! Documentation

(onAfterContentSave)
Line 135: Line 135:
 
}</source>
 
}</source>
 
The parameters article and isNew should contain the following:
 
The parameters article and isNew should contain the following:
* article : A reference to the JTableContent object that is being saved which holds the article data.
+
* article : A reference to the JTableContent object that was saved which holds the article data.
* isNew : A boolean which is set to true if the content is about to be created.
+
* isNew : A boolean which is set to true if the content was created.
+
 
 
===onPrepareContent===
 
===onPrepareContent===
 
Use the following code:
 
Use the following code:

Revision as of 19:10, 19 June 2009

Replacement filing cabinet.png
This Namespace has been archived - Please Do Not Edit or Create Pages in this namespace. Pages contain information for a Joomla! version which is no longer supported. It exists only as a historical reference, will not be improved and its content may be incomplete.

Contents

Description

There are lots of abilities of the use of a Content Plugin. They all have to do with the display of your content and so your articles. You will need at least two files for this Plugin. An XML file and a PHP file. Because there are so many differences between two Content Plugins in the PHP file, two examples of them will be explained in this document. Also a part about internationalization (with INI files) is added. And last but not least: the Joomla! Core Content Plugin coding examples and the quick tips.

XML file

The XML file is named the same as the PHP file, and is one of the two required files. Always start off with the XML tag and define that it is written in a UTF-8 format.

<?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">

To define that the plugin has to be a content plugin, add this line:

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

The type will define it is a Plugin, the group defines the Plugin is in the group of Content Plugins.

After that, add some information about yourself and the Plugin, like this:

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

And now include your PHP file to the Content Plugin. The name of this file should be the same as the name of this XML file. Put this name also behind the plugin="" part.

You could also add more files for your plugin, for example an image. Just add another row between <files> and </files>, and then place the file between <filename> tags.

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

For the internationalization, we will use language files. This is not required, but people from other countries will love it they can easily translate your plugin to their own language. Plugin language files are always installed in administrator/languages/xx-XX/ where xx-XX is the code for a language already installed in Joomla. The language tags can be found here: [1] (use the ISO 639-1 column) and here: [2]

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

Optionally, you could add some parameters to the Plugin. These will look like this:

<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.

When you do not want to use parameters, add the following tag:

<params/>

And do not forget to end your XML file with the following tag:

</install>

PHP file

Start your PHP file with the general licensing and author information about your content plugin.

<?php
/**
 * @version             $Id: nameofplugin.php revision date lasteditedby $
 * @package             Joomla
 * @subpackage  Content
 * @copyright   Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license             GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

Next, always put the following code in any PHP file:

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

This prevents people from directly accessing this PHP file.

After that, you should import the general plugin file of Joomla!'s library

jimport( 'joomla.plugin.plugin' );

To indicate that you're writing a Content plugin, add the following code.

class plgContentNameofplugin extends JPlugin {

Please note the use of capital letters. You should replace Nameofplugin by the name of your own plugin.

Now, it's time to construct the plugin:

/**
 * Constructor
 *
 * For php4 compatability we must not use the __constructor as a constructor for plugins
 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
 * This causes problems with cross-referencing necessary for the observer design pattern.
 *
 * @param object $subject The object to observe
 * @param object $params  The object that holds the plugin parameters
 * @since 1.5
 */
        function plgContentNameofplugin( &$subject, $params )
        {
                parent::__construct( $subject, $params );
        }

You should choose now at which moment the plugin should be rendered. You can choose from the following:

  • onBeforeContentSave : This is an event that is called right before the content is saved into the database.
  • onAfterContentSave : This is an event that is called after the content is saved into the database.
  • onPrepareContent : This is the first stage in preparing content for output and is the most common point for content orientated plugins to do their work.
  • onAfterDisplayTitle : This is a request for information that should be placed between the content title and the content body.
  • onBeforeDisplayContent : This is a request for information that should be placed immediately before the generated content.
  • onAfterDisplayContent : This is a request for information that should be placed immediately after the generated content.

More information on which type you should use for your plugin, including several examples, can be found here: Reference:Content_Events_for_Plugin_System

onBeforeContentSave

Use the following code:

        function onBeforeContentSave( &$article, $isNew )
        {
                global $mainframe;
                //add your plugin codes here
                return true;
        }

The parameters article and isNew should contain the following:

  • article : A reference to the JTableContent object that is being saved which holds the article data.
  • isNew : A boolean which is set to true if the content is about to be created.

onAfterContentSave

Use the following code:

        function onAfterContentSave( &$article, $isNew )
        {
                global $mainframe;
                //add your plugin codes here
                return true;
        }

The parameters article and isNew should contain the following:

  • article : A reference to the JTableContent object that was saved which holds the article data.
  • isNew : A boolean which is set to true if the content was created.

onPrepareContent

Use the following code:

        function onPrepareContent( &$article, &$params, $limitstart )
        {
                global $mainframe;
                //add your plugin codes here
                //no return value
        }

The parameters article, params and limitstart should contain the following:

  • article : A reference to the article that is being rendered by the view.
  • params : A reference to an associative array of relevant parameters. The view determines what it considers to be relevant and passes that information along.
  • limitstart : An integer that determines the "page" of the content that is to be generated. Note that in the context of views that might not generate HTML output, a page is a reasonably abstract concept that depends on the context.

onAfterDisplayTitle

Use the following code:

        function onAfterDisplayTitle( &$article, &$params, $limitstart )
        {
                global $mainframe;
                //add your plugin codes here
                return '';
                //return a string value. Returned value from this event will be displayed in a placeholder. 
                // Most templates display this placeholder after the article separator.
        }

The parameters article, params and limitstart should contain the following:

  • article : A reference to the article that is being rendered by the view.
  • params : A reference to an associative array of relevant parameters. The view determines what it considers to be relevant and passes that information along.
  • limitstart : An integer that determines the "page" of the content that is to be generated. Note that in the context of views that might not generate HTML output, a page is a reasonably abstract concept that depends on the context.

onBeforeDisplayContent

Use the following code:

        function onBeforeDisplayContent( &$article, &$params, $limitstart )
        {
                global $mainframe;
                //add your plugin codes here
                return '';
                //return a string value. Returned value from this event will be displayed in a placeholder. 
                // Most templates display this placeholder after the article separator. 
        }

The parameters article, params and limitstart should contain the following:

  • article : A reference to the article that is being rendered by the view.
  • params : A reference to an associative array of relevant parameters. The view determines what it considers to be relevant and passes that information along.
  • limitstart : An integer that determines the "page" of the content that is to be generated. Note that in the context of views that might not generate HTML output, a page is a reasonably abstract concept that depends on the context.

onAfterDisplayContent

Use the following code:

        function onAfterDisplayContent( &$article, &$params, $limitstart )
        {
                global $mainframe;
//add your plugin codes here
                return '';
                //return a string value. Returned value from this event will be displayed in a placeholder. 
                // Most templates display this placeholder after the article separator.
        }

The parameters article, params and limitstart should contain the following:

  • article : A reference to the article that is being rendered by the view.
  • params : A reference to an associative array of relevant parameters. The view determines what it considers to be relevant and passes that information along.
  • limitstart : An integer that determines the "page" of the content that is to be generated. Note that in the context of views that might not generate HTML output, a page is a reasonably abstract concept that depends on the context.

PHP file - Example

This example PHP file is about the Content Plugin load module. It is a plugin made for displaying modules within the articles. The commented PHP file used in this example is the file which will be included in Joomla! 1.6. This has been done because the content plugin files in Joomla! 1.5 are not refactored yet to the new standards.

<?php
// The general information at the top of each file
/**
* @version              $Id$
* @package              Joomla
* @copyright    Copyright (C) 2005 - 2009 Open Source Matters, Inc. All rights reserved.
* @license              GNU General Public License, see LICENSE.php
*/
 
// No direct access allowed to this file
defined( '_JEXEC' ) or die( 'Restricted access' );
 
// Import Joomla! Plugin library file
jimport('joomla.plugin.plugin');
 
//The Content plugin Loadmodule
class plgContentLoadmodule extends JPlugin
{
        /**
        * Plugin that loads module positions within content
        */
// onPrepareContent, meaning the plugin is rendered at the first stage in preparing content for output
        public function onPrepareContent( &$row, &$params, $page=0 )
        {
                // A database connection is created
                $db = JFactory::getDBO();
                // simple performance check to determine whether bot should process further
                if ( JString::strpos( $row->text, 'loadposition' ) === false ) {
                        return true;
                }
 
                // expression to search for
                $regex = '/{loadposition\s*.*?}/i';
 
                // check whether plugin has been unpublished
                if ( !$this->params->get( 'enabled', 1 ) ) {
                        $row->text = preg_replace( $regex, '', $row->text );
                        return true;
                }
 
                // find all instances of plugin and put in $matches
                preg_match_all( $regex, $row->text, $matches );
 
                // Number of plugins
                $count = count( $matches[0] );
 
                // plugin only processes if there are any instances of the plugin in the text
                if ( $count ) {
                        // Get plugin parameters
                        $style  = $this->params->def( 'style', -2 );
                        $this->_process( $row, $matches, $count, $regex, $style );
                }
                // No return value
        }
// The proccessing function
        protected function _process( &$row, &$matches, $count, $regex, $style )
        {
                for ( $i=0; $i < $count; $i++ )
                {
                        $load = str_replace( 'loadposition', '', $matches[0][$i] );
                        $load = str_replace( '{', '', $load );
                        $load = str_replace( '}', '', $load );
                        $load = trim( $load );
 
                        $modules        = $this->_load( $load, $style );
                        $row->text      = preg_replace( '{'. $matches[0][$i] .'}', $modules, $row->text );
                }
 
                // removes tags without matching module positions
                $row->text = preg_replace( $regex, '', $row->text );
        }
// The function who takes care for the 'completing' of the plugins' actions : loading the module(s)
        protected function _load( $position, $style=-2 )
        {
                $document       = &JFactory::getDocument();
                $renderer       = $document->loadRenderer('module');
                $params         = array('style'=>$style);
 
                $contents = '';
                foreach (JModuleHelper::getModules($position) as $mod)  {
                        $contents .= $renderer->render($mod, $params);
                }
                return $contents;
        }
}

INI file(s)

For internationalization it is good to use the INI files. You can add to the language file everyting which 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_content_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="mode" type="list" default="1" label="Mode" description="Select how the emails will be displayed">
   <option value="0">Nonlinkable Text</option>
   <option value="1">As linkable mailto address</option>
</param>

Will cause the following in the INI file:

MODE=Mode
SELECT HOW THE EMAILS WILL BE DISPLAYED=Select how the e-mails will be displayed
NONLINKABLE TEXT=Nonlinkable text
AS LINKABLE MAILTO ADDRESS=As linkable mailto address

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

When you want to make your Content Plugin available in more languages, first add them to the