Joomla 2.5/1.7: Automatically assign users to a group based on email

Access control advancements are the primary reason I moved many of my Joomla efforts beyond 1.5. One request that I hear repeatedly is to have access control automatically added when a user registers. In its most basic form, this is simple to accomplish in the administrative interface. Create a group, position it somewhere beneath 'Registered', and then generate an Access Level that is associated with only that group. Now under User Manager - Options, select the appropriate group under 'New User Registration Group'. Now when a new user registers, they are automatically added to that group, and given the corresponding Access Level.

Often this scenario is sufficient for the needs of a site. However, occasionally I get requests that some users are added to one group, while other users get added to a different group - often based on email. For example, anyone registering with an email ending in '*.edu' must be added to the education group, and anyone registering with an email ending in 'someDevCompany.com' must be added to the developer group. As I see it, there is not a great way to handle this scenario built in to the Joomla core. Also, most of the options where you would achieve this involve replicating or extending the core users component, which often adds confusion for your site administrators.

This solution is not elegant, and it requires some minimal PHP knowledge in order to expand, but it functions well, and stays out of your administrator's way. First make a couple groups and a couple corresponding access levels. We need to note the group ID values, we will use these in our code updates. In the User Manager, on the User Groups page, you can see the ID value in the far right column. If you are working with a fresh installation, the ID of your first new group is likely 10 or 13, depending on whether or not you elected to load the sample data. Note your group IDs and keep those handy, I will use IDs 13 and 14 to represent 'education' and 'developer' groups, respectively.

Now we need to add a few lines of code to the existing users component. The psuedo-code goes like this:

if the user's email ends in 'edu',
    then add them to the education group (with id 13)
else if the user's email ends in 'someDevCompany.com',
    then add them to the developer group (with id 14)
else add the user only to the Registered group

In order to have the least impact on existing code, we add this very close to the user saving event. Proceed to the JOOMLA_ROOT/components/com_users/models/registration.php file, and locate the 'register($temp)' function. You can also look for the 'bind' text, as we want to update the groups data immediately prior to the binding of form input to the user object. This is right around line 325 in Joomla 1.6 or greater. I am including the code before and after for reference, and we must add the following:

// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JUtility::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}

//*************BEGIN****************
// Convert the email to all lower case for safe alpha compare.
$lowerEmail = strtolower($data['email']);

// Add the appropriate group ID to the existing groups array.
if(strpos($lowerEmail,'.edu') !== false){
$data['groups'][] = 13;
}else if(strpos($lowerEmail,'someDevCompany.com') !== false){
$data['groups'][] = 14;
}
//**************END*****************

// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}

Notice that we are not replacing the '$data['groups']' array, just adding a value to the end of the existing array. This way, the user is added to both the 'Registered' group and the appropriate additional group. If you wanted to avoid setting multiple groups, you could instead create a new array, and add a single group id to the array based on your conditional checks. Then simply set '$data['groups'] = $yourNewArray;', and you are in business.

I hope this saves a few people some time. I will do my best to respond to any questions in the comments, and definitely feel free to post alternative solutions!

Posted in Joomla | 18 Comments

The PHP Switch Statement

The PHP switch statement is a good substitute for a lot of "if, "else", and "elseif" statements. The switch statement is much more efficient than the "if", "elseif" statements, however there are some quirks that you should be aware of in using switch. This article came when I wanted to do an "or" condition in one of the case tags. As usual, it took me awhile to find what I wanted. I thought it would help if I put all the quirks in one article.

First, lets look at the basic switch statement.

include "chk.php";
$var = 0;
new chk($var);
SwitchDemo($var);
function SwitchDemo($var)
{
  switch ($var)
  {
    case 0:
		echo "Hello";
		break;
    case 1:
	        echo " World!";
		break;
    case 2:
	        echo "The real McCoy";
	        break;
    case 3:
                echo "Went too far";
	        break;
    case 4 :
		if ($type == "string" ) {
                    $myarray = array_push($buildarr, $type);
                    break;
                }
		break;
    default:
	    echo "went way too far";
	    break;
	}
}

Here's the code we'll use initially to test things out. A word of explanation. Include "chk.php" is my free variable checking class that you can read about and download here. To use the class, I simply say "new chk($var);". The output is in the picture below. The output says $var is an integer set to "0" that was called in my test script file, "switch.php", on line 21. The output of the switch statement is "Hello".

This is a standard switch statement that we'll start with so you can quickly refer to the syntax when needed. The switch statement executes a different section of code depending on which case is true. The switch variable to be checked should be in parenthesis, and each case tag ends with a ":", a colon, although if you messed up and used a semicolon, I think you'll find that it still works. I'll let you test that out on your own. Note the brackets surrounding all the case and default tags. Also, notice in Case 4, you can have a fairly complex series of commands in the case block, not just one or two lines. We'll leave Case 4 out in the rest of this article just to keep things simple.

The first thing to know is the switch statement does a "loose" comparison between the value in the switch parenthesis and the case value, as opposed to a strict comparison. This would be like using a == in an if statement, instead of a ===. Let's just say that switch does a pretty good job, and if there's any doubt, re-do the variable to make sure there's no ambiguity, that can mean, just making the comparison all integers. If your using integers to compare, you do not need quotes around the integers as shown in our first example. With strings, put quotes around the string.

OK, lets move on. The default case is used, if none of the other case statements are true. A little known fact is the case statements, and the default statement, don't need to be in any sort of order. Let's move the default up, change the case statements around, and change our variable to 2 to better show this. Here's the code scrambled. I'll cut down the code to show just the switch statement. The other code is still running.

	switch ($var)
	{
	    case 3:
              echo "Went too far";
	      break;
	    default:
	      echo "went way too far";
	      break;
            case 1:
	      echo "World!";
              break;
	case 0:
   	      echo "Hello";
	      break;
    case 2:
	    echo "The real McCoy";
	    break;

And here's the output:

Next, we want to talk about "break" and "continue". "break;" breaks you out of the switch statement all together. You're done your filtering, and you're moving on. "continue;" means move to the next case block. Let's show this, we'll put the switch back in order and use a continue.


switch ($var)
{
    case 0:
		echo "Hello";
		continue;
    case 1:
	    echo "World!";
		break;
    case 2:
	    echo "The real McCoy";
	    break;
    case 3:
        echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
}

Here's the output:

I know you were expecting "Hello World", lol. No, even though we are "continuing" to match case blocks, we still have to match. Which brings me to why I wrote the article: How can I output "Hello World!" ?

We'll use a not well known feature of the switch, the "fall through" in the switch statement. If we take out the continue, and leave the break on case 1, we'll get close to our desired results. Here's the code:

switch ($var)
{
    case 0:
	    echo "Hello";
    case 1:
	    echo " World!";
		break;
    case 2:
	    echo "The real McCoy";
	    break;
    case 3:
            echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
}

Here's the output:

In this case, there was no break for Case 0, so when the $var was 0, it outputs "Hello World!" It fell through to Case 1. What happens if we set the $var to 1. Here's the output.

Here we did not match the "0", so "Hello" did not output, and because the HTML tags were not correct the CSS styling did not load, and make "World!" bigger. Let's fix this and make the switch statement really useful. Here's the code:

switch ($var)
{
    case 7:
    case 8:
    case 0:
    case 1:
	    echo "Hello World!";
		break;
    case 2:
	    echo "The real McCoy";
	    break;
    case 3:
        echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
	}

Here's the output:

Woo horsey! What's going on here? We put in a variable of 8 and we get "Hello World!" What happen is the case block matched the 8 and fell through to case 1 and out came "Hello World!". We then broke out of the switch statement. What this means to you is that you can use "OR" conditions with the switch statement.

Instead of:


if( $var == 7 || $var == 8 || $var == 0 || $var == 1) {

}

We can use our switch statement above, which seems a lot easier to me, and more important less prone to syntax errors when we have "OR" statements.

One last thing, we can use calculations in our matches. Let do a final example. Here we'll go back to all the code, and use more than one variable. Here's the code:


include "chk.php";
$var1 = 1;
$var4 = 4;
new chk($var1, $var4);

SwitchDemo($var1, $var4);
function SwitchDemo($var1, $var4)
{
switch ($var1 + $var4)
{
    case 7:
    case 8:
    case 0:
    case 1:
	    echo "Hello World!";
	    break;
    case (2 + 3):
	    echo "The real McCoy";
	    break;
    case 3:
            echo "Went too far";
	    break;
    default:
	    echo "went way too far";
	    break;
	}
}

Here's the output:

Here we used calculations, a simple add, in both the switch parameter statement and the case parameter, and we get "The real McCoy." This is equivalent to:

if( $var1 && $var2)  {

}

We've used switch to add variables, and check for an "AND" condition. You can use this to concatenate strings, if you like. You can see the versatility of the switch statement.

In conclusion, the switch statement is more efficient than the "elseif" type of statement. The interpreter makes a list of case comparisons, and then goes right to the case that matches instead of checking every comparison one at a time. Hopefully, you won't shy away from using the switch statement in the future now that you know all the ins and outs. Chow, until next time.

Posted in PHP | Leave a comment

A new site coming for PHP – a Preview

If you're a PHP Developer, you are familiar with the PHP web site, www.php.net.  This site has looked the same, for I don't know how long, but for at least, six or seven years, if not longer.  The old pastel purple and gray colors were instantly recognized when you went to the web site.

The old PHP site with the PHP 5.39 version annoucement

 

A side note, notice in the image above that PHP 5.3.9 has been released.  This is just a subtle way for me to announce a new release of PHP.

Back to talking about the web site, I have visited the old site a multitude of times, and it's usually my first click when I want to do a quick check for the correct syntax.  The site was OK, but quite frankly, I never cared for it much, and found myself always looking for another site to round out my knowledge of a particular code snippet.

The reason why I didn't like it was I always thought the examples weren't good, and the explanations were worse.  I wanted to see the syntax used in a code snippet, and a simple use, and explanation of the code in question.  Somehow you always ended up paging down the page, and not finding what you were looking for,   It was frustrating.  I also didn't end up reading the comments on the page, because I was in a hurry, and it was just easier to go to another web site, and find a better tutorial.  A lot of my articles on PHP stem from my frustration with the PHP site, and the fact that I needed to go some where else to find what I needed.

Well, this may be changing.  Apparently, I'm not the only one who didn't like the site.  The PHP Group has decided to gradually retire the old site, and is in the process of building a new site, more modern looking, and I, for one, am highly optimistic that this will be a one-stop site for my PHP questions.

The new sites main page

 

You can view a preview of the new site as it is coming together here: http://prototype.php.net/

The really good news, is that The PHP Group is asking for contributions to their documentation, and are not just going to paste the old documentation into the new site.  I have viewed some of the pages in their new documentation, and it seems improved.

A comment on the new design, I think it is a much cleaner looking, an easier-to-read site. At first, I thought the font was too small, but you can re-size the site with your ctrl-mouse wheel to your preferred size font.  You could do that with the old site too.

The font and the white background, not surrounded by gray sidebars, like the old site, is much easier to read.  It makes the site more wide open and not as cluttered.  A big improvement over the old site.  The gray sidebars of the old site were a downer to me, and made me want to move on to another site to get to a brighter and cleaner environment.  The gray of the old site was like a rainy day, gray, and gloomy, and the content was like baby food, bland.  Good reasons to upgrade the site.

Showing the Documentation sub-menu

 

On the new site, if you click on the documentation, community, or help top menu, for example, the site mimics the CodeIgniter documentation layout in using a table of contents as the intro page to that section.  This is a nice touch, and makes you want to look around more than if the option were stuck in the sidebar, like in the old site.  I found myself clicking various topics that provoked my interest, a big plus for the new site.

For a while it looks like you may have to visit both the old and new to get your information, or go to one of those "other" sites.  A lot of the pages on the old site are not available from time to time.  While I was writing this article both sites showed up with white space instead of the documentation.  If you would like to speed the new site along The PHP Group is looking for contributors.

Posted in Web Sites | Leave a comment

NetBeans 7.1 Review

One of outcomes of switching jobs is you lose some of your favorite tools.  For me that was Zend Studio.  Having done PHP development full time for many years, Zend Studio had become my IDE of choice.

Since Zend Studio costs money, as a newbie to my new company, I didn't see a lot of Zend Studio's installed.  In fact, I saw few IDE's.  Most of the edits were done on a Linux server running Vim. This seemed a little archaic to me.  I wanted to set up my beloved work environment, back to open-source.

Naturally, I downloaded Eclipse PDT based on the Helios release, on which Zend Studio is built.  I had used Eclipse before Zend Studio, and so this was pretty close to home.  All the menus and functionality, except for some of the Zend Studio features, are the same.

In the process of configuring Eclipse, I, of course, started messing with preferences.  Anyone who has used Eclipse understands what a nightmare the Eclipse preferences are.  It takes you quite a bit of time to initially configure preferences.  So you don't have to reconfigure then again, you export your preferences and import them to the new Eclipse environments.

I did an import of my Zend Studio preferences and then started changing some setting, and I had a hiccup.  The hiccup was Eclipse balked at some setting I set, and blew away my entire workspace.  I'm guessing Zend Studio preferences have problems with importing to Eclipse.  I had to reload everything including re-configuring my preferences.  What a nightmare.

When things like this happen, I get pissed, and go looking for new tools.  After a preliminary search showed that Netbeans had good reviews, I decided to give it a try.  I had tried Netbeans before, and found it wanting for PHP development, but that was four years ago.  It deserved another look.

NetBeans Initial Start Up Screen

 

Netbeans is a Java application and requires Java to run, which is probably already loaded on your computer.  The Netbeans license is owned by Oracle from its acquisition of Sun, but it is a free and open source IDE.

Since PHP is now an object-oriented language, like Java, NetBeans has incorporated PHP into its editor.  You have a choice to install NetBeans with just the PHP bundle, which is what I did, since I do not do a lot of Java work.

The Netbeans 7.1 download and install was seamless. The installer downloads 46.6 Mb, which grows to 152.5 Mb on install.  By the way, my Eclipse Helios folder checks in at 390 Mb. The installation took about 5 minutes and NetBeans came up quickly and easily.

NetBeans with various Windows open

 

If you do a feature by feature analysis of Eclipse and Netbeans, you'll find that both IDE's pretty much have the same features and functionality.  You'll find several good articles on the web about this, so I won't go into individual features here.

NetBeans main editor window with other windows closed

 

If your doing Java development, Netbeans should be your IDE of choice, since it was built with Java development in mind.  What surprised me was how far Netbeans has come as a PHP development environment.  If your a PHP Developer, NetBeans has integrated support for Git, Debugging, PHPUnit testing, PHPDoc, Smarty templates, Symfony Framework, and the Zend framework. Need I say more.

NetBeans PHP preference screen

 

If both IDE's pretty much have the same functionality, what is the difference between the two?  Well, it comes down to the feel of the IDE as your using them.

I thought about good analogies and similes for the two editors.   Here's my take.  Eclipse is like an old car that you keep fixing up, it's serviceable and runs good, but every once in a while, you get irritated, because something doesn't work right.  Netbeans seems like a new BMW sports car.  If Eclipse is a house built with a series of additions, Netbeans is a house built from the ground up by an architect.  Eclipse feels bloated.  Netbeans feels integrated, not like your bringing up a separate application every time you go to a new area of the IDE.

One major weakness in Eclipse is setting preferences on how you want the editor to work.  Each plugin added to Eclipse has its own preferences, every section of Eclipse has it own preferences.  What that means is setting preferences is a nightmare.  Not only that, if you set a preference in one area, it might not be set in another, and may collide with another preference, sometime throwing errors, or shutting down the editor.  I've had all of this happen.

In contrast, NetBeans preferences are a pleasure.  Colors and fonts are configured in one tab, PHP in another tab.  You can set all colors and fonts for all languages at once, not like Eclipse.

NetBeans Fonts and Colors Preference Screen

 

In all fairness to Eclipse, I'm comparing this to Eclipse Helios PDT.  I downloaded the Eclipse Indigo 64bit and added the PDT plugin, and I find this version quicker,  and much more stable.  I would recommend Eclipse PDT users uninstall Helios, download Indigo, and add PDT.  I think you'll like it  better, if you stay with Eclipse.

In conclusion, because of problems I've had configuring colors with Eclipse, even using the Eclipse Color Theme Plugin I wrote about in another post, I find myself using NetBeans to write my code.

I highly recommend you download and try NetBeans.  You can have both IDE's running at the same time without conflicts.  If you don't like NetBeans, you can stay with Eclipse, but in the process of using both, I think you'll find yourself gradually moving to NetBeans as your IDE of choice.

The NetBeans Icon

Posted in Development Tools, Software Reviews | 17 Comments

The Power of the Internet

Wow, I'm impressed. Yesterday, the Internet held its first protest. A passive resistance protest in the Gandhi tradition. There were no swear words, no violence, no harmful attacks, well maybe, if you count denial of service for overwhelming email submissions to Congress.  The Library of Congress reported a denial of service attack by people opposed to the legislation.

It was an Internet blackout.  Not all sites participated, but the fact that major sites, like Google, Reddit, Craigslist, and Wikipedia coordinated on one day to pull this blackout off, and make the public aware of the SOPA and PIPA legislation was a first, and amazing, considering the independent nature of web site owners. One estimate stated over 10,000 web sites participated in the protest. This is not confirmed, but given the Internet has over 100 Million active sites, the number does not seem that far off.

It is estimated that over 300,000 people sent emails, or called, their Congressman protesting SOPA and PIPA in the last 24 hour period, and over 4.5 Million people signed a Google petition protesting the Bills according to the protest organizers.

What is the aftermath of this one day shut-down-your-site protest, and send emails to Congress?

The Seatle Times reports that Florida Sen Marco Rubio, a bill sponsor, went on Facebook to renounce PIPA, and Texas Senator John Coryn used Facebook to urge colleagues to slow down and reconsider the Bills. South Carolina Senator and Tea Party member, Jim DiMint, used Twitter to announce his opposition.

Congressman are rapidly distancing themselves from the Bills as fast as they can. According to Ars Technica count and the Atlantic Wire 18 Senators, mostly Republican, have backed away from the PIPA and SOPA bills in the last 24 hours. Seven of them co-sponsored the Bill. The Seatle Times reports over 20 House members have reversed their positions. On Tuesday this group supported the Bill, on Wednesday they said that the SOPA and PIPA legislation was flawed and unsupportable.

Congress for the first time realized that the Internet is not just a bunch of web sites to be regulated like a bunch of unruly grade school kids, but that the Internet is a political force, and has considerable more power than the media and movie industry, a supporter of SOPA and PIPA. The end result was that Congress suddenly realized that the Internet can stand up and defend itself.

The Motion Picture industries, a sponsor of SOPA and PIPA, called the blackout "a gimmick" and "business interests are resorting to stunts to punish their users or turn them into corporate pawns."

Hollywood has a powerful lobby in Washington. They just found out that they have a very powerful opponent that they didn't know was there. Hollywood and Congress learned today that the Internet community has a say. Anyone who can get millions of people to take action is a political force that Congress will have to consider in the future.

The Internet and technical community have established that they have a say in the politics of our country. That was not quite as evident before yesterday. Let's hope Congress listens in the future, and that the big players in the Internet community realize, and take advantage, of their suddenly acquired power to push for legislation that helps, not hinders, the development of the Internet worldwide.

Posted in Editorials | Leave a comment