Skip to content

Dailyinvention Posts

Changing Your WordPress Theme Using XML-RPC, Part I

I’ve had a project in mind for a little while that involves changing WordPress Themes using a mobile device. When Christmas comes, wouldn’t it be nice to switch your site over to a Christmassy theme with the push of a button? Or maybe use it to give your client the ability to quickly change themes when they want to. The nice thing about WordPress is that something like this is possible! And it can all be accomplished using XML-RPC calls.

XML-RPC (Remote Procedure Call) is a protocol used to communicate with web services, which is sent and received in XML form. You may have come into contact with desktop or mobile applications like Windows Live Writer that allow you to update WordPress. These applications use XML-RPC to add, edit and delete blog posts. In fact, WordPress has a number of methods you can access right out of the box. When I looked at the API, I was disappointed to not see any of the theme get and set functions available to execute remote procedures on. Looking a little deeper, I discovered that you can make the WordPress’s theme functions available.

I’m extending WordPress’s XML-RPC functions to include themes using a plugin, which if you’re not used to building plugins could sound daunting, but it really isn’t. I’m starting this out by extending WordPress’s wp_get_themes function to a method, so I can retrieve the list of themes in WordPress using my phone.

You always start each plugin with a header so it can be identified and displayed within WordPress:

<?php
/*
Plugin Name: XML-RPC Theme Changer
Plugin URI: https://github.com/dailyinvention/xml-rpc-theme-changer
Description: Allows the ability to get and switch themes using XML-RPC.
Author: Stefan Holodnick
Author URI: http://blog.dailyinvention.com
Version: 1.0
*/

?>

Now I’m going to add a function that runs the wp_get_themes function:

<?php
/*
Plugin Name: XML-RPC Theme Changer
Plugin URI: https://github.com/dailyinvention/xml-rpc-theme-changer
Description: Allows the ability to get and switch themes using XML-RPC.
Author: Stefan Holodnick
Author URI: http://blog.dailyinvention.com
Version: 1.0
*/
  
function theme_get_themes($params) {
  global $wp_xmlrpc_server;
  $wp_xmlrpc_server->escape( $params );
  
  $username = $params[0];
  $password = $params[1];
  
  if ( ! $user = $wp_xmlrpc_server->login( $username, $password ) ) {
    return $wp_xmlrpc_server->error;
  }
  else {
    return wp_get_themes(false, true);
  }
}

?>

WordPress has a built-in class for handling XML-RPC security called $wp_xmlrpc_server. It is being made accessible in the function by assigning it as global. Below that the $parameters value being sent to WordPress is sanitized using the escape method. We are sending an array of values to WordPress that include a username and password. If WordPress does not find the username and password to be true, it returns an error. Otherwise it executes wp_get_themes. You’ll see that I have defined “false” and “true” as arguments in the wp_get_themes function. With these values it will return an array of theme names from WordPress that don’t have errors and are allowed to be used.

Now we assign that function to a method that we can call:

<?php
/*
Plugin Name: XML-RPC Theme Changer
Plugin URI: https://github.com/dailyinvention/xml-rpc-theme-changer
Description: Allows the ability to get and switch themes using XML-RPC.
Author: Stefan Holodnick
Author URI: http://blog.dailyinvention.com
Version: 1.0
*/
  
function theme_get_themes($params) {
  global $wp_xmlrpc_server;
  $wp_xmlrpc_server->escape( $params );
  
  $username = $params[0];
  $password = $params[1];
  
  if ( ! $user = $wp_xmlrpc_server->login( $username, $password ) ) {
    return $wp_xmlrpc_server->error;
  }
  else {
    return wp_get_themes(false, true);
  }
}
  
function theme_methods($methods) {
  $methods['themes.getThemes'] = 'theme_get_themes';
  return $methods;
}

?>

You’ll see “themes.getThemes”. This is the method name that you reference when you do a remote call. And now the finishing touches:

<?php
/*
Plugin Name: XML-RPC Theme Changer
Plugin URI: https://github.com/dailyinvention/xml-rpc-theme-changer
Description: Allows the ability to get and switch themes using XML-RPC.
Author: Stefan Holodnick
Author URI: http://blog.dailyinvention.com
Version: 1.0
*/
  
function theme_get_themes($params) {
  global $wp_xmlrpc_server;
  $wp_xmlrpc_server->escape( $params );
  
  $username = $params[0];
  $password = $params[1];
  
  if ( ! $user = $wp_xmlrpc_server->login( $username, $password ) ) {
    return $wp_xmlrpc_server->error;
  }
  else {
    return wp_get_themes(false, true);
  }
}
  
function theme_methods($methods) {
  $methods['themes.getThemes'] = 'theme_get_themes';
  return $methods;
}
  
add_filter('xmlrpc_methods', 'theme_methods');
?>

Now that we have a method, we need to include it within WordPress’s XML-RPC methods. This “add_filter” function does just that.

Not too bad, was it? Now that WordPress is set up to retrieve the theme names, we probably want our mobile app or web client to be able to switch the current theme when it is selected. The next part of this tutorial I’ll cover the process of enabling WordPress to switch themes over XML-RPC.

Leave a Comment

Handling Large KML Files Without Google Maps

In the four weeks or so, I’ve become quite familiar with the Google Maps API, pitfalls included. I’ve been contracted to work on an interactive map for the RAIN Group, a not-for-profit out of Pennsylvania that is focused on water quality. Especially in areas where hydraulic fracturing (fracking) for natural gas is taking place.

Google’s API, to say the least, is easy to customize with some javascript experience. The requirements of the project required overlays gathered from USGS, EPA and other entities. It was fairly straight forward to incorporate the KML layers that we procured, but some of these files ran rather large in size. After the heartbreak of having to admit that Google was telling the truth about the size limitations on KML files, it was back to the drawing board.

Luckily, after a lot of hunting, I found the GeoXML library. Rather than using Google’s servers to render these layers, GeoXML provided a client-side alternative. This means that the size limitations that we faced were no longer an obstacle in displaying our layers.

Everything came together and the world was at peace again. If you are considering building your own map elements from complex datasets, I would not overlook this library. It will save your life… or at least a little headache.

Leave a Comment

Utilizing CAP (Common Alert Protocol)

Rave Alert has been a major project that I have have been assigned to implement. This system provides an easy way of contacting students and staff in case of emergency via email, text message, voice call, Facebook and Twitter. We also use it for snow days and class cancellations. Not too long ago the helpful staff at Rave introduced me to the CAP XML standard. CAP is a standard not just specific to Rave, but many emergency alert systems. It is also used by various government agencies for sharing emergency information over multiple systems.

PHP CAP Alert Function

Once I heard of CAP, I knew we could use this XML standard in various ways to extend the reach of our own emergency alerts. One being the school web page. Here is a small function I put together using PHP that will display an emergency message on a web page:

Just include this code on your PHP page and then call it with the CAP URL location you want to pull from:

cap_parse("http://example.com/cap.xml");

CAP Desktop Alerting Software

Taking this a step further, I decided to get a little more familiar with .NET. It was brought to my attention that we were missing a desktop alert component. There are server-based systems out there that require some setup and a good deal of money. After a little thought, I concluded we could meet these same goals with a simple desktop client that used the CAP XML feed to trigger an emergency message. And in a couple days I had something built.

I thought this project warranted creating a Github repository. It’s still a little rough, but by bringing it to git, I’m hoping to get some more interest and input in this project. I’ve made the source code available, so maybe someone will find this code useful to bolster their own emergency alerting using CAP. Please visit my CAP Alerting Desktop repository if you are interested. Any contributions to the code are welcome.

Mentioned Resources:

PHP CAP Alert Function
CAP Desktop Alerting Software

4 Comments

The Power in Powershell: Creating AD Users From a SQL Database

Part of my current job has become building automation processes for online student services. One of our goals was to get our Active Directory services populated with student data from our student information system, which uses a Microsoft SQL database. After talking with contacts from other schools that use the same system, I was introduced to Powershell.

At a recent conference I attended a presenter referred to Powershell as “Microsoft’s version of Linux bash scripting”. I would wholeheartedly agree with this description. It takes the power of .Net and brings it to the Windows command prompt.

Another nice thing about Powershell is that people have already developed Powershell scripts to interact with AD and SQL that are free to use. The script I am going to demonstrate uses Idera’s Powershell Scripts to do some of the heavy lifting.

I’ve searched the net for examples of scripts that already do this, but didn’t find anything complete enough for my particular situation, so I thought I would include my own solution.

Here is a breakdown of the script:

."C:\path to script\New-IADUser.ps1"

This is an include statement pointing to Idera’s New-IADUser script. This will allow you to later on call the function that creates a user in Active Directory.

$connString = "data source=database location;Initial catalog=database name;uid=user name;pwd=password;"
$QueryText = "SELECT * FROM user table name WHERE this='that'"

Then I’ve defined the strings for connecting to the database. The first string defines the database to connect to and the login information. The second Querytext string contains your query for selecting the desired user information from the database.

$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = $QueryText

This section creates a connection to the database and queries using the strings defined from the last example.

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
$DataAdapter.Fill($dataset)
$data = $dataset.Tables[0]

Then we create a data table object and fill it with information returned from the database. Lastly, I assigned the table data information to a value.

foreach ($data_item in $data.Rows) {
  $name = $data_item[2] + " " + $data_item[3]
  $response = [ADSI]::Exists("LDAP://CN=" + $name + ",OU=user organizational unit,DC=mydomain,DC=com")
  if($response -ne "false") {
    New-IADUser -Name $name -sAMAccountname $data_item[0] -ParentContainer 'OU=user organizational unit,DC=mydomain,DC=com' -Password $data_item[1] -Mail $data_item[4] -EnableAccount -UserMustChangePassword
  }
}

This foreach statement loops through the various rows in the table object that we created. The $data_item values returned are assuming that the table rows look like this: id number | password | first name | last name | email. The values may vary depending on how you query your database. The third line uses ADSI to check if the user with the name in the row is the same. The next line is a conditional statement that will run the New-IADUser function if the user is not already in Active Directory.

Leave a Comment

Rewarding Those That Like You (on Facebook)

Facebook Like Button

A client that I have been working for had an interesting request for me a couple weeks ago. He wanted to create a campaign for his Facebook page where an individual would get rewarded with a free music download for liking the page. This was already accomplished from the Facebook page, but I was curious if such a thing could be done directly from a web site, since Facebook’s button is generated through Javascript code.  What I really wanted to do was create a page redirect to this free music download page once the Like button was clicked.  Here are the steps I’ve done to make this work:

    1. Create an new application and get an app id by going here. Get started and follow the steps after clicking “Create New App”.

 

    1. Generate the Facebook button code by going here. After you’ve entered in the page you are putting the like button on, click on the “Get Code” button.

 

    1. When the box pops up, I selected “XFBML”. Also make sure to select the application you created in step one next to “This script uses the app ID of your app:”. Follow the steps that Facebook provides. You will need to add “xmlns:fb=”http://ogp.me/ns/fb#” to your <html> tag.

 

  1. After the first body tag, place the code that Facebook suggests. This is what I placed:
    <body>
    <div id="fb-root"></div>
    <script>
       (function(d, s, id) {
          var js, fjs = d.getElementsByTagName(s)[0];
          if (d.getElementById(id)) return;
          js = d.createElement(s); js.id = id;
          js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=Application ID that was created in the first step";
          fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
    </script>

  2. Don’t forget to add the Like button where you want it on the page. This code can be placed anywhere you want to appear on the page:
    <fb:like href="The address of the page the button sits on" send="true" width="450" show_faces="true"></fb:like>
  3. Now that all the Facebook code has been added to the page, you’ll need to add a little bit of code for the redirect. Looking at the script that was placed right before the body tag add these lines as shown in bold:
    <body>
    <div id="fb-root"></div>
    <script>
    window.fbAsyncInit = function() {
       FB.init({appId: 'Application ID that was created in the first step', status: true, cookie: true,xfbml: true});
       FB.Event.subscribe("edge.create", function(targetUrl) {
         window.location.href = "The address of the page you want to redirect to.";
       });
       FB.Event.subscribe("edge.remove", function(targetUrl) {
         console.log('edge.remove');
       });
    };

    (function(d, s, id) {
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) return;
          js = d.createElement(s); js.id = id;
          js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=Application ID that was created in the first step";
          fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    </script>
     
Leave a Comment