Home > Articles > Web Development

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020