Increase the number of visible users per page on group creation and user selection screen in Moodle 2.2

So we had a query come through our Help Desk recently to ask if we can increase the users in the user selection box as staff members were having difficulty managing their classes and creating groups as they couldn’t CTRL click and had to type in the names of their students. So I started having a dig around the code in Moodle to find out if we can change the default value.

After poking around the source code and looking at some search results on Google, I found the file that was needed and it can be found in user/selector/lib.php – Line: 740

So we want to go to line and change MAX_USERS_PER_PAGE to equal what we want (a higher value, and in this case we gave it 500). The following is an extract of what we are changing.

 * User selector subclass for the list of users who are not in a certain group.
 * Used on the add group members page.
class group_non_members_selector extends groups_user_selector_base {
    const MAX_USERS_PER_PAGE = 500;

Save the file and now reload your group creation page and you should now be able to select multiple users in a large user base list. Also, it is important to note that the MAX_USERS_PER_PAGE variable is in multiple places and affects different user selection boxes depending on where you edit it.

How to convert Hex Colour Codes into RGB Colour Codes using PHP

I was recently working on a web based piece of software that had some colour settings stored in a database table which were stored as hexadecimal colour code values. I needed a quick way to convert them into RGB (Red, Green, Blue) values so that I could use them in creating an image using PHPs builtin GD so after a quick search on Google found nothing that I was really after I decided to write my own. The difficulty was that colours were inputted by both other developers and a jQuery colour picker which meant that there was a mix of both shorthand and standard hexadecimal colour codes. I get past this little hiccup by simply counting the length of the hex string and running either a bitwise operation or a hexadecimal conversion. Anyway onto the function.

Firstly, we need to define the function.  We will have two variables, one being the actual hexadecimal colour code and the other whether we wish to return as a String or Array.

function hex2RGB($hexStr, $returnAsString = false) {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr);
    $rgbArray = array();

After this we simply grab the variable of the function which should be our Hex colour code and check the length.  If the length is 6 then we are able to use PHPs bitwise operators to quickly convert the colour codes into the RGB values we are after. Using bitwise operators results in lower overhead and therefore leads to a faster output.

    if (strlen($hexStr) == 6) { // Proper Hex convert using bitwise operation
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;

Or if it is a shorthand hex colour code (ie: #FFF) then we can perform manipulation on the string to first extend it and then perform a conversion.

elseif (strlen($hexStr) == 3) { // If shorthand perform string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));

or else if our string matches neither of the above then return nothing (false).

else {
        return false; // Invalid hex color code

Now that we have our converted code, we need to return it back to what called for the code with the following in either an array or as a string.

    // Returns the rgb string or the associative array as specified
    return $returnAsString ? implode(",", $rgbArray) : $rgbArray;

We can call the above function in two ways

hex2RGB(“#FF0”) would output array( red =>255, green => 255, blue => 0)
hex2RGB(“#FF0”, true) would output 255,255,0

So there we have a completed function to convert hex colour values into RGB.

Using the Google Maps API with PHP to display a Map and place a Marker on the map using Geocoding

So I was recently developing a new feature for a client’s website where we wanted to display an interactive Google Map with the address of a particular item (in this case a customer) along with a marker to show where it was on the map. So I set about looking around on the Internet for some information, not coming up with a lot apart from Google’s own API Documentation. So I decided to piece a few things together with what I already knew and make my own little script to do what I wanted.

The following code is quite crude, but should get you started on the right foot. I will eventually update this stuff to use the v3 of the API but since Google is still supporting v2, why bother. So first off is building the address we are going to use to query Google, which is the following code:

define("MAPS_HOST", "");
define("KEY", "abcdefg"); // Place your API Key here...
// Get our address (from a database query or POST
$address = "100+Flinders+Street+Melbourne+VIC+3000";
// Build our URL from the above...
$base_url = "http://" . MAPS_HOST . "/maps/geo?q=" . $address . "&output=csv" . "&key=" . KEY;

So we now have the URL to query google and you can actually paste that into your web browser and you will get an output similar to:


So now lets move on to getting PHP to actually process the URL and get us some location data. I decided to use CURL simply because it is quick and simple (was rushing to get this together). So the following code basically initialises CURL and will retrieve the data from URL and save into our $csvPosition.

// Initalise CURL
$c = curl_init();
// Get the URL and save the Data
curl_setopt($c, CURLOPT_URL, $base_url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
// Save location data
$csvPosition = trim(curl_exec($c));
// Close the connection

You will probably want to add some error checking here just in-case your server can’t reach the URL.

The final piece of PHP will spilt the result, which was requested and returned in CSV format into a variables as defined by the following line of code:

// Split pieces of data by the comma that separates them
list($httpcode,$elev, $lat, $long) = split(",", $csvPosition);

Now that we have performed the Geocoding of the address and have it split up and ready, we can create our map.  So firstly we need to include the Google Maps API with the following HTML:

<script type="text/javascript"

With the API included we can now build the map, with PHP giving us our Latitude and Longitude values by querying the Geocoding Web Service previously with CURL which we have done previously. So we initalise the API, build our Map with some basic settings like Zoom and Drop in a marker with the Latitude and Longitude provided by the Geocoding.

  function initialize() {
    var latlng = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $long; ?>);
    var addressMarker = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $long; ?>);
    var myOptions = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    var map = new google.maps.Map(document.getElementById("map_canvas"),

	marker = new google.maps.Marker({ map:map, position: addressMarker });

We are placing the Latitude and Longitude we retrieved with CURL from the Google Maps Geocoding service into the JavaScript function above with the variables $lat and $long. Now we have those functions in place, we can create a div in the body of the page to display our map. In this case called map_canvas. I have already defined a style to limit the width and height to 512 pixels. So we want to insert a body onload event with the following line of code, so insert this into your body tag.


and as well we need to insert our div map_canvas so the previously defined JavaScript can actually draw a map. So create a Div layer with id map_canvas.

And that is about it. You should now be able to see a map with a red marker in the center with the address we specified being marked.  It’s location being determined by Google’s Geocoding and Google Maps API and sorted with the help of PHP. This could easily be improved by making the marker click-able and storing data on it. Adding multiple markers, animations and customising the map view itself.

To view a demo of the completed script, click here.

Update: You can also Download the complete sample by clicking here.

Server Side E-Mail Validation with PHP

Validation is one of the most important things which can be done on a public-facing website. It prevents users from entering required information incorrectly or even worse attempting to damage your site via some form of script or SQL Injection attack.

Recently I was developing a website for a Real Estate firm, as a legal requirement they need to have valid e-mail addresses to link up to views of listings. Client Side e-mail validation is fairly simple, but what if the user is malicious and removes the JavaScript or just has JavaScript disabled. So I added both client and server side e-mail validation.

One important thing to remember is to always sanitise your inputs whenever something is going into a database, but that’s for another article. There are several ways to tackle e-mail validation, I let the Client Side handle the format and let the server do some heavier work. Firstly, it required making the function. I’ve called it checkEmail, we also need to pass it an e-mail address via $email.

function checkEmail($email)

We then move on to setting things up, creating our error variable and getting our e-mail argument and ensuring it is safe.

    $email_error = false;
    $Email = htmlspecialchars(stripslashes(strip_tags(trim($email))));

After getting the address from our function call, perform a simple test to see if there is anything and if there is begin validating. If not pass our error and tell the user.

	if ($Email == '') { $email_error = true; }
	elseif (!preg_match('^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])^', $Email)) { $email_error = true; }

There is a piece of nifty REGEX which simply validates if we have a valid e-mail address in a specific format of an e-mail address of [email protected] with only alphanumeric and – . _ being accepted. If our REGEX passes we then begin to do some checking, which is where the server side validation comes in. We explode our e-mail address to extract the domain and using PHP’s inbuilt checkdnsrr function we can perform an MX Lookup of the supplied domain.

	else {
	list($Email, $domain) = explode('@', $Email, 2);
		if (! checkdnsrr($domain, 'MX')) { $email_error = true; }
		else {
		$array = array($Email, $domain);
		$Email = implode('@', $array);
	if ($email_error) { return false; } else{return true;}

If the checks all pass then we return FALSE and allow the form to submit with code embedded on the calling page. If we do get an error then we return TRUE with code again embedded on the calling page to notify the user.

And there you have it,  server side e-mail validation. Of course you could improve on what I’ve done by actually checking for an alias on the particular domain or by sending out an e-mail validation to the address before the user can continue, but that is all beyond the scope of this function and article. If you do end up using this function, I’d love to hear where you are using it, so feel free to let me know.