Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

User Registration Plugin

For our next example, let’s add some validation to the override form we added in the previous chapter.

Update the Approval Override File

Recall that we added two check boxes to the user registration form, as shown in Figure 5.3.

Figure 5.3

Figure 5.3. Customized registration form

This was accomplished by adding the following code to the layout override file: templates/beez_20_copy/html/com_users/registration/approval.php:

<fieldset>
    <legend><?php echo JText::_( 'BEEZ_20_COPY_TERMS_OF_SERVICE')?></legend>
    <p><input type="checkbox" />
       <?php echo JText::_()?>  </p>
    <?php if ($this->params->get('show_age_checkbox')) : ?>
       <p><input type="checkbox" />
           <?php echo JText::_('BEEZ_20_COPY_AGE')?> </p>
    <?php endif; ?>
</fieldset>

We need to modify this code slightly before we write our plugin. Our plugin will check that both check boxes have been clicked by the user. If not, the plugin will return false, which will stop the registration process.

When we submit a PHP form with the post method, the values for the form are saved in the PHP super global variable called $_REQUEST. The values are saved in an associative array, where the key to the array is the name attribute of each input element. If an input element has no name attribute, it doesn’t get saved. Accordingly, we need to add name attributes to both of the check box fields. In the following code, we call the first check box tos_agree and the second one old_enough.

<fieldset>
    <legend><?php echo JText::_(
        'BEEZ_20_COPY_TERMS_OF_SERVICE')?></legend>
    <p><input type="checkbox" name="tos_agree" />
        <?php echo JText::_('BEEZ_20_COPY_AGREE')?>  </p>
    <?php if ($this->params->get('show_age_checkbox')) : ?>
        <p><input type="checkbox" name = "old_enough" />
           <?php echo JText::_('BEEZ_20_COPY_AGE')?> </p>
    <?php endif; ?>
</fieldset>

Add the XML File

Next, we create the plugin PHP and XML files. The name of the plugin is “myregistration,” and it is a user plugin. So we will create a folder called plugins/user/myregistration and create our two plugin files, myregistration.xml and myregistration.php, in that folder.

The myregistraion.xml file listing is shown in Listing 5.4.

Listing 5.4. myregistration.xml File

<?xml version="1.0" encoding="utf-8"?>
<extension version="2.5" type="plugin" group="user">
  <name>plg_user_myregistration</name>
  <author>Mark Dexter and Louis Landry</author>
  <creationDate>January 2012</creationDate>
  <copyright>(C) 2012 Mark Dexter and Louis Landry.</copyright>
  <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
 <authorEmail>admin@joomla.org</authorEmail>
 <authorUrl>www.joomla.org</authorUrl>
 <version>2.5.0</version>
 <description>PLG_USER_MYREGISTRATION_XML_DESCRIPTION</description>

 <files>
   <filename plugin="myregistration">myregistration.php</filename>
   <filename>index.html</filename>
   <folder>language</folder>
 </files>

 <config>
 </config>
</extension>

This is similar to the earlier example plugin. Note that we are defining a language subfolder for our plugin. We discuss this when we create our zip archive file.

Add the PHP Plugin File

The code for the myregistration.php file is shown in Listing 5.5.

Listing 5.5. myregistration.php File

<?php
/**
 * @copyright  Copyright (C) 2012 Mark Dexter & Louis Landry. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('JPATH_BASE') or die;
jimport('joomla.plugin.plugin');

/**
 * This is our custom registration plugin class.  It verifies that the user
 *  checked the boxes indicating that he/she agrees to the terms of service
 *  and is old enough to use the site.
 */
class plgUserMyRegistration extends JPlugin
{
    /**
     * Method to handle the "onUserBeforeSave" event and determine
     * whether we are happy with the input enough that we will allow
     * the save to happen.  Specifically we are checking to make sure that
     * this is saving a new user (user registration), and that the
     * user has checked the boxes that indicate agreement to the terms of
     * service and that he/she is old enough to use the site.
     *
     * @param   array  $previousData  The currently saved data for the user.
     * @param   bool   $isNew         True if the user to be saved is new.
     * @param   array  $futureData    The new data to save for the user.
     *
     * @return  bool   True to allow the save process to continue,
     *                   false to stop it.
     *
     * @since   1.0
     */

    function onUserBeforeSave($previousData, $isNew, $futureData)
    {
         // If we aren't saving a "new" user (registration), or if we are not
         // in the front end of the site, then let the
         //   save happen without interruption.
         if (!$isNew || !JFactory::getApplication()->isSite()) {
            return true;
         }

         // Load the language file for the plugin
         $this->loadLanguage();
         $result = true;

         // Verify that the "I agree to the terms of service for this site."
         //   checkbox was checked.
         if (!JRequest::getBool('tos_agree')) {
             JError::raiseWarning(1000,
                 JText::_('PLG_USER_MYREGISTRATION_TOS_AGREE_REQUIRED'));
            $result =  false;
         }

         // Verify that the "I am at least 18 years old." checkbox was checked.
         if (!JRequest::getBool('old_enough')) {
            JError::raiseWarning(1000,
                 JText::_('PLG_USER_MYREGISTRATION_OLD_ENOUGH_REQUIRED'));
            $result =  false;
         }

         return $result;
    }
}

The first two lines of code should be familiar. First we ensure that we are inside Joomla. Then we import the parent class for this plugin. (Note that, because of the autoloader, this line of code is no longer required as of version 2.5.) The class name follows the required naming convention of “plg” plus the type (“user”) plus the plugin name (“myregistration”). The class extends JPlugin.

The class has one method, which is named according to the event that will trigger it. In this case the method is onUserBeforeSave(). This event is triggered when we try to save a new user in the back end or register a new user in the front end.

The first thing we do is to make sure we are creating a new user in the front end. If not, we just return true and skip the rest of the processing.

The next thing we do is to load the language file. This loads the file administrator/ language/en-GB/en-GB.plg_user_myregistration.ini, which we discuss a bit later. Then we set our $result variable to true.

psn-dexter-padlock.jpg

The next section is an if block. We use the JRequest::getBool() method to get the tos_agree element from the PHP $_REQUEST variable. This method returns a boolean true or false. Since this is a check box, we expect it to either have the value “on” or it will not be defined. However, we are also mindful that a hacker can manipulate the $_REQUEST variable and put values in there that we don’t expect. By using the JRequestion::getBool() method, we know that we will always get a true or false value, no matter what a hacker might put in that field.

If the check box has been checked, the JRequest::getBool('tos_agree') will return a value of true and the expression (!JRequest::getBool('tos_agree')) will be false (recall that “!” means “not”). In this case, we don’t execute the code inside the block.

If the check box has not been checked, we enter the code block. Here we execute two lines of code. The first calls the JError::raiseWarning() method. The first argument is the error code, which we don’t use in this example (so it can be most anything). The second argument is the error text. Here we are using the JText::_() method to make the error text translatable. This means we will need to put the language key PLG_USER_MYREGISTRATION_TOS_AGREE_REQUIRED in our language file. The second line in the code block sets the $result variable to false. This means that the method will return a value of false, which will stop the save process.

The second if statement is identical to the first one, except that it checks that the second check box has been clicked and returns a different message to the user.

The last line of code just returns the $result variable, which will be true if both if code blocks were skipped. If the user forgot to check both check boxes, they will get both error messages, which is what we want.

Add the Language Files

The last step before we can try our plugin is to add the language files. Recall in our XML file we add the following lines:

<files>
    <filename plugin="myregistration">myregistration.php</filename>
    <filename>index.html</filename>
    <folder>language</folder>
</files>

The folder element indicates that there will be a subfolder called “language” in the folder for our plugin.

When we create a plugin, we can choose whether to have the language files in the plugins folder or in the adminstrator/languages folder. For extensions, it is normally recommended to keep all extension files separate from core files, so putting extension language files in the folder for the extension is normally preferred.

In our example, we will have two language files: en-GB.plg_user_myregistration.ini and en-GB.plg_user_myregistration.sys.ini. These files will go into the folder plugins/user/myregistration/language/en-GB/.

The first file is the primary language file and contains the language keys that will be used when the plugin code is executed and also when the plugin is opened for editing in the Plugin Manager. In this file we put any keys we will need for front-end display or for editing options. Listing 5.5 shows the listing for the main plugin language file.

Listing 5.5. en-GB.plg_user_myregistration.ini File

; Language file for myregistration plugin

PLG_USER_MYREGISTRATION_TOS_AGREE_REQUIRED="You must agree to the terms of service."
PLG_USER_MYREGISTRATION_OLD_ENOUGH_REQUIRED="You must be at least 18 years old."

The second file (with the .sys in the name) is used to translate the name of the plugin when it is listed in the Extension Manager or Plugin Manager. We also put the description of the plugin in the .sys file so that we can translate the description in the message that shows when the plugin has been installed. This convention is used for all extension types. Listing 5.6 shows the listing for the .sys language file.

Listing 5.6. en-GB.plg_user_myregistration.sys.ini File

; sys language file for myregistration plugin
; The .sys.ini files are used when listing the extensions in the extension
;   manager or plugin manager

PLG_USER_MYREGISTRATION="User - My Registration"
PLG_USER_MYREGISTRATION_XML_DESCRIPTION="Checks that terms and age boxes have been checked."
psn-dexter-padlock.jpg

As a last step, copy an index.html file from another Joomla folder into the plugins/user/myregistration folder and the language and language/en-GB subfolders. As discussed earlier, every folder we create in Joomla should have an index.html file to prevent users from browsing the folder directly.

Test the Plugin

At this point, we can test our plugin. Again, we navigate to Extensions → Extension Manager → Discover and click on the Discover icon in the toolbar. Our new plugin extension should be listed using the translated text “User – My Registration” that we used in the .sys language file.

Again, we click the check box to select the plugin and then click on the Install icon. When we have installed it, note that the plugin description from the .sys language file should show in the Extension Manager: Discover screen, as shown in Figure 5.4.

Figure 5.4

Figure 5.4. Plugin description from .sys language file

At this point, we can test the plugin. To test it, first enable it in Plugin Manager. Then try to register a new user with the approval.php override file without checking the two check boxes. You should see a message as shown in Figure 5.5.

Figure 5.5

Figure 5.5. User plugin error messages

You should also test the other cases to make sure they work as expected. These include the following:

  • Save with one check box checked (should get one error message).
  • Save with both check boxes checked (should work correctly).
  • Create a user from the administrative back end (Users → User Manager → Add New User should work correctly).

Package the Plugin

So far, we have used the Discover method to install our extensions. This works well during development. However, if we want to be able to install our extension on other Joomla sites, we need to package it in an installation archive file. This is very easy to do. We need a program that allows us to create archives in zip, tar.gz, or tar.bz2 format. For Windows, the free program “7-Zip” (http://www.7-zip.org/download.html) works well. For Linux and Mac OS X, programs to create a zip archive come installed with the operating system.

The steps to create an installable zip archive are as follows:

  1. Create a new folder on your disk system (for example, temp) and copy the three plugin files myregistration.xml, myregistration.php, and index.html, and the language folder (which contains the en-GB subfolder with the two language files) to this folder.
  2. Create a zip file that includes the three files and the language folder. The exact command for creating the archive will depend on your operating system and the software you use.

    For Windows with 7-Zip, you would highlight the three files and language folder in the Windows Explorer, right-click, and select 7-Zip → Add to Archive and then follow the instructions—for example, naming the zip file plg_user_myregistration.zip.

    For Mac OS X, you would do something very similar, except you would select “Create Archive” from the file menu after highlighting the files.

    In Linux, you could go to the command prompt in the temp folder and enter the command

    $ zip -r plg_user_myregistration.zip *

  3. After you create the zip archive, open it and check that it has the three files and one folder you expect.
  4. Now we want to check that the file installs correctly. Uninstall the plugin by navigating to Extensions → Extension Manager → Manage. Select the plugin and click on the Uninstall icon in the toolbar. You should see the message “Uninstalling plugin was successful.” Note that this step will delete the files from your Joomla folders. However, you should already have these files copied to the temp directory created in step 1.
  5. Navigate to Extension Manager → Install and click the Browse button. Browse to the zip archive file you created and click the Upload and Install button. You should get the message “Installing plugin was successful.”

At this point, we have a fully functioning plugin extension that can be installed on any site that runs Joomla version 1.6 or higher.

  • + Share This
  • 🔖 Save To Your Account