PHP Code Samples

Exporting Announcements from WHMCS

Doing some integration work with WHMCS, I found the need to export some of the announcements into WordPress. Since there isn’t any native implementation of this, I found the best way is to export it directly from the database. The PHP code to do this is fairly easy:

1
2
3
4
5
6
7
8
9
10
11
12
include("/path/to/whmcs/configuration.php");
$link = mysql_connect($db_host,$db_username,$db_password);
mysql_select_db($db_name);
$query = "SELECT * FROM tblannouncements WHERE published='on' ORDER BY date DESC LIMIT 0,3";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)) {
  $id = $data["id"];
  $date = $data["date"];
  $title = $data["title"];
  $announcement = $data["announcement"];
  echo("<a href=\"/support/announcements.php?id=$id\">$title</a>");
}

If you wanted to make it more than 3 posts, just change the limit to 5 or 10 or whatever you wish. You can also change the ordering and add additional filters via more SQL statements. If you wanted to do a list, encapulate the code with <ul> and just make them <li> entries.

I’m using this code in a WordPress template but it would work equally as well in any other PHP based application.

Adding Random Quotes to the Bash Login Screen

shakespeare

According to “official” system administrator rules and guidelines you shouldn’t be adding so-called vain scripts to the login prompt – only utilities that will add something useful to the system (for example, current system load, memory and disk usage, etc). However I have some systems that I frequently connect to and thought it would be neat to add a random quote script to my bash login. That being said, this should only be done on ‘non-production’ systems and adds a security vector so please be careful where you use this.

The goal of this is to add a little quote, at random, every time you log into your system. My thoughts were to do it not only as a little source of inspiration but also to add perspective to what I’m doing sitting in front of the computer all of the time.

Originally I was going to try to write the script solely in bash since it is so flexible (and just as a proof of concept) but dealing with RSS in bash isn’t exactly pretty and I just wanted to get this together as quick as possible. PHP makes parsing XML easy, there are a number of ways to accomplish it. I chose to use the ready-made script at rssphp.net to do this, if you are curious about how you can handle this yourself using SimpleXML check out this tutorial over at Pixel2Life. The end result of my solution is a bash script calling a php script to grab the quote.

The Code

First create a file named /etc/update-motd.d/10-quote. The name does not matter much – the number will decide what order the script is called in of all the scripts in /etc/update-motd.d. Do an ls on that directory to see what all is being called when you log in. Add the following lines to this file, assuming you are placing your scripts in /etc/scripts/:

1
2
3
4
#!/bin/sh
echo ""
/usr/bin/php /etc/scripts/getquote.php
echo ""

Download v1 of rssphp and extract it to the /etc/scripts/ directory. We will require that file in our php code.

Create the file /etc/scripts/getquote.php and add the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
require_once 'rss_php.php';    

        $rss = new rss_php;
        $rss->load('http://www.quotedb.com/quote/quote.php?action=random_quote_rss');
        $rssitems = $rss->getItems();

        if ($rssitems) {
                // print_r($rssitems);
                echo $rssitems[0]['description'].' :: '.$rssitems[0]['title']."\n";
        }
   
?>

I am using the RSS source from QuoteDB as the source of my quotes. Of all the places I checked (and I checked a lot) they seemed to have the most appropriate ones for this use. Feel free to use any source you wish – as long as the XML fields title/description hold the quote you will be able to use it. The RSS url was not obvious from the site and I had to do some digging to find it, in the end I am using http://www.quotedb.com/quote/quote.php?action=random_quote_rss.

We also add the if statement to allow it to degrade nicely in case you have no network connectivity to the server. After a short period – a second or two – it will time out and let you log in.

The end result is a pretty quote in our motd:

1
2
3
4
5
6
Linux vps01.[redacted].com 2.6.18-2-pve #1 SMP Mon Feb 1 10:45:26 CET 2010 x86_64 GNU/Linux
Ubuntu 10.04.1 LTS

"The absence of alternatives clears the mind marvelously." :: Henry Kissinger

root@vps01:~#

It should be pretty strait forward; let me know if you run into any problems!

Find Out If A Twitter Username Exists Using PHP/JSON

I’ve been trying to grab a Twitter screenname that people continually register and do not use. Twitter eventually deletes it, but I suppose it is in high enough demand that someone else registers it right away (and then continues to never use it). Wrote up a quick and dirty php script to check the Twitter API to see if a screenname exists and if it doesn’t, shoot a short an email. I’ve been using changedetection to roughly do the same thing but it has fallen short on two counts: the first is that it reports follower count changes, and second it only runs once a day and this hasn’t been fast enough for me to grab my desired screen name.

You can set this script to run via cron at any desired interval, I’ve set it to run every 30 minutes for me. Test with sample information to make sure it works under your setup. I’m using the default mail() function, and I also included some json decoding in there so you could also use this script to play around with decoding a user’s information in PHP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
/* Copyright (c) 2010 Dave Drager
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */


/* README
 * This is a simple script to check a username on Twitter and send a short email
 * if it is not found. It's the simplest way I found to do this. Using the
 * sample code you could also modify it simply to do something with a
 * found username as well. Details are in the $json_output array. Enjoy
 */


// fill in these 2 variables below
$username = "someusername";
$notifyemail = "your_email@address";

// this is needed otherwise file_get_contents errors out
error_reporting(0);
$url="http://api.twitter.com/1/users/show.json?screen_name=".$username;
$json = file_get_contents($url,0,null,null);

if($http_response_header[0] == "HTTP/1.1 404 Not Found") {
        //echo "Screen name not taken!\n";
        $to      = $notifyemail;
        $subject = 'Screen name now available - '.$username;
        $message = 'The screen name '.$username.' is now available on Twitter.';
        $headers = 'From: '.$notifyemail . "\r\n";
        mail($to, $subject, $message, $headers, '-f '.$notifyemail);
}
else {
        // screen name exists - you can do something here if you want
        //$json_output = json_decode($json,true);
        //print_r($json_output);
}
?>

If you are running it from cron, add the sample entry:

1
0 * * * * /usr/bin/php /path/to/script.php

The above would run the script every hour on the hour.

Of course you can easily modify this sample code if you are looking to do any kind of similar checking in your web app. If you find this kind of script useful, please let me know!

A phpBB 3 iPhone Style Theme With Option to Disable

phpBB iPhone theme style

phpBB iPhone theme styleA forum that I am an adminstrator for has been clamoring for an iPhone theme (style) for a long time now. In the past, I hadn’t seen any usable iPhone template for phpBB3, until now.

The theme is hosted on Google code and is named phpbb-iphone-style. It is downloadable here and was last updated June 18th, as of today.

The theme works wonderfully on the iPhone. However, the issue that I ran into is automatically displaying it for mobile browsers, such as the iPhone, Android and other platforms.

Fortunately there is a modification you can make to the phpbb code which is effectively a theme switcher for mobile browsers. The how to is located within the download file for the theme above.

What if a user wants to turn off the mobile style?

I modified the code to allow a user to set an option on their profile to permentently disable the theme when logged in on a mobile browser.

First, install the style as described above. As part of the switcher, you need to find out the theme ID. You can do so, after installing the style, by hovering over the ‘Detail’ tab in the ACP (Administrator Control Panel) and looking for the ‘id’ variable. In the example below it is ‘6’.

Once the theme is installed, move over to the “Users and Groups” tab, and then the “Custom Profile Fields” area. At the bottom of this page there is a box to add a new profile field. Type ‘disable_mobile’ as the name, and Boolean (Yes/No) as the type and click add.

For the options, I selected:

  • Publicly display profile field: No
  • Display in user control panel: Checked
  • Display on registration screen: Unchecked
  • Display on viewtopic screen: Unchecked
  • Required field: Unchecked
  • Hide profile field: Unchecked
  • Field name/title presented to the user: Disable Mobile Browser
  • Field description: When viewing on a mobile device (iPhone, Android, etc), clicking ‘yes’ will disable the mobile browser.
  • Entries: First option: Yes, Second option: No

On the second screen select the following items:

  • Field type: Radio Buttons
  • Default value: no

Save your custom profile field.

It will end up looking like this in the profile control panel of the end user:

phpbb iphone style disabler

Now the fun part, adding the code to your install to select which mobile browser to use automatically.

Back up, then open install dir/includes/session.php

Around line 1468 in the function setup

1468
1469
1470
1471
1472
        /**
        * Setup basic user-specific items (style, language, ...)
        */
        function setup($lang_set = false, $style = false)
        {

Replace

1
global $db, $template, $config, $auth, $phpEx, $phpbb_root_path, $cache;

with

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
global $db, $template, $config, $auth, $phpEx, $phpbb_root_path, $cache, $user;


//-----Begin phone detection & redirection code-----

                $user->get_profile_fields( $user->data['user_id'] );
                $user_fields = $user->profile_fields;

                // if (!($user_fields['pf_disable_mobile'] == 1)) {  
                // Thanks to Chris Dembek for this code fix
                if (isset($user_fields['pf_disable_mobile']) && !($user_fields['pf_disable_mobile'] == 1))

                        //id of the iphone/mobile theme - SELECT THIS FROM YOUR STYLES
                        $mobilestyleid = 6;

                        //Fetch the users browser
                        $user_browser = strtolower($this->browser);

                        //List of mobile user-agent keywords
                        $browsers_array = array('240x320', '320x240','blackberry', 'iemobile', 'minimobile', 'mobile', 'opera mini', 'pda', 'phone', 'pocket', 'psp', 'symbian', 't-shark', 'wireless');

                        //Check for the user-agent in the list of mobile user-agents
                        foreach ($browsers_array as $ua_match) {
                                if (strpos($user_browser, $ua_match) !== false) {  //a match
                                        $style = $mobilestyleid;
                                        $this->data['is_mobile'] = true;
                                        break;
                                }
                        }

                }

                //-----End phone detection/redirection code-----

Make sure to replace $mobilestyleid = 6 with your style id number!

Save your file. Test out the modifications on your phone, you should be presented with the mobile version on reload (make sure to purge any cache if you don’t see it right away).

Finally go into your profile and select the ‘disable mobile browser’ option and make sure it reverts back to your regular default theme.

Let me know if you have any problems implementing this but it has worked great for this phpbb forum!

Adding a Module Position in a Joomla 1.5 Template

Adding a module position in a Joomla 1.5 template is not as easy as it was in the 1.0 templates. It is a two step process:

1. Add code to template PHP file.

For example, this would go in the index.php file in the template folder – or if you are adding it in an include file.


1
2
3
4
5
<?php if ($this->countModules('user6')) : ?>
    <div>
        <jdoc:include type="modules" name="user6" style="xhtml" />
    </div>
<?php endif; ?>

2. Add module name to templateDetails.xml

You then need to tell Joomla which module positions are available in this template. If you don’t do this step, then Joomla will not present the module position when giving you the option of where to place a module.

templateDetails.xml is in XML format. Within the

1
<install>

namespace, add this:


1
2
3
<positions>
      <position>user6</position>
</positions>

If you already have positions listed, just add the

1
<position>user6</position>

part along with the rest of them.

Last Modified Date or Time on WordPress Template Page

I couldn’t readily find an answer to this question via the google. So here it is: If you want to insert a ‘last updated’ or ‘last modified’ date on your wordpress page, then there is a simple bit of PHP code you can use for this:

1
<?php the_modified_time('F jS, Y');?>

And via Ardamis’s Blog, there is a great way to only display this information if it has been modified after the original post date. This is a good way to let people know if there have been updates since the original post:

1
2
3
4
5
6
7
8
<?php $u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
echo "and last modified on ";
the_modified_time('F jS, Y');
echo " at ";
the_modified_time();
echo ", "; } ?>

This will display the last modified date and time if it is more than 86400 seconds after the creation date – that is 24 hours.

Secure Drupal Admin Login Page

Drupal’s administration login area is not secure by default. Usually there is an option in the configuration area of content management systems to set a secure area for logins, otherwise your username and password are sent in plain text over the internet.

Luckily, there is a module which enforces secure login on a Drupal install.

Drupal Module: Securepages

Although it is still in development, the 6.x-1.x-dev version worked great with my Drupal 6.4 installation.