Playing with your blog's xml-rpc interface

Serendipity provides an xml-rpc interface which you can to edit/update/query your blog using either the MT or the Blogger APIs. Editors like perfomancing, ecto use the xml-rpc interface to post entries to your blog. This article explores the xml-rpc interface provided by Serendipity.

I wanted to post my blog entries through the command line and hence I started to play with the xml-rpc interface. To get started, you should check out the documentation of the programmatic interfaces for the Movable Type. The next thing you might like to check out is the serendipity_xmlrpc.inc.php source - especially the array $dispatches. Another resource to have handy is the documentation of the Pear's XML-RPC package.I have used pear's xml-rpc package since I found it easy to understand. You need to have that package installed to work through this example

Let us start by making a simple call to find out the titles of the recent post

#!/usr/bin/php
<?
require_once 'XML/RPC.php';
error_reporting(E_ALL);

$params = array(new XML_RPC_Value(1, 'string'),
		new XML_RPC_Value('s9admin', 'string'),
		new XML_RPC_Value('s9admin', 'string'),
		new XML_RPC_Value(10, 'int')
		);

$msg = new XML_RPC_Message('mt.getRecentPostTitles',$params);

$cli = new XML_RPC_Client('/serendipity_xmlrpc.php', 'cal.rajshekhar.net');

$resp = $cli->send($msg);

if (!$resp)
  {
    echo 'Communication error: ' . $cli->errstr ."\n";
    var_dump($resp);
    exit;
  }

if (!$resp->faultCode())
  {
    $val = $resp->value();
    $data = XML_RPC_decode($val);
    $n_entries = count($data);
    print "\nFound $n_entries entries \n";
    for ($i=0;$i<$n_entries;$i++)
      {
	print "\ntitle \t\t:". $data[$i]['title'];
	print "\npostid \t\t:" . $data[$i]['postid'];
	print "\n";
      }
    exit;

}
 else
   {
     /*
      * Display problems that have been gracefully caught and
      * reported by the xmlrpc.php script
      */
     echo 'Fault Code: ' . $resp->faultCode() . "\n";
     echo 'Fault Reason: ' . $resp->faultString() . "\n";
   }

?>

Save the above code in a file and chmod +x file . You should now be able to run the above code from the command line.

Check out the line $cli = new XML_RPC_Client('/serendipity_xmlrpc.php', 'cal.rajshekhar.net'); . In this case, change the cal.rakshekhar.net to point to your own blog url. If you have a blog like rajshekhar.net/blog/, you will have to do something like this $cli = new XML_RPC_Client('/blog/serendipity_xmlrpc.php', 'rajshekhar.net');.

The above code should print out the titles of your most recent 10 entries. If you check the documentation of the mt.getRecentPostTitles method, it says

Description: Returns a bandwidth-friendly list of the most recent posts in the system.
Parameters: String blogid, String username, String password, int numberOfPosts

In case of s9y, the parameter blogid does not make any sense and you can set it to any integer.

Now that we are satisfied that this actually works, let us move to making a post through the xml-rpc interface. We will be using the metaWeblog.newPost method to make our blog posting. Here is what the documentation says

Description: Creates a new post, and optionally publishes it.
Parameters: String blogid, String username, String password, struct content, boolean publish
Return value: on success, String postid of new post; on failure, fault
Notes: the struct content can contain the following standard keys: title, for the title of the entry; description, for the body of the entry; and dateCreated, to set the created-on date of the entry. In addition, Movable Type's implementation allows you to pass in values for five other keys: int mt_allow_comments, the value for the allow_comments field; int mt_allow_pings, the value for the allow_pings field; String mt_convert_breaks, the value for the convert_breaks field; String mt_text_more, the value for the additional entry text; String mt_excerpt, the value for the excerpt field; String mt_keywords, the value for the keywords field; and array mt_tb_ping_urls, the list of TrackBack ping URLs for this entry. If specified, dateCreated should be in ISO.8601 format.

Here is the actual code

#!/usr/bin/php
<?
require_once 'XML/RPC.php';
error_reporting(E_ALL);

$post   = "<p>Sed molestie. Phasellus pede purus, aliquam eu, eleifend nec,
aliquam at, ipsum. Morbi tortor lacus, pellentesque sit amet, mattis
at, fermentum non, ante. Cum sociis natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. Maecenas molestie nisi ut
pede. Nulla facilisi. Cras et augue quis quam rhoncus lacinia. Etiam
eget odio. Curabitur libero ligula, lacinia id, ornare eget, dapibus
vitae, turpis. Sed elementum risus. Sed commodo eleifend
erat. Pellentesque id tellus vel augue lobortis vehicula. Proin
pulvinar, ipsum non elementum tincidunt, odio libero posuere mi, sit
amet ultricies odio mauris et mauris. Nunc elit eros, tincidunt eget,
ultricies in, accumsan a, nulla. Donec id felis a elit rutrum
venenatis. Morbi vehicula pede vel lacus vestibulum ultrices. Nulla
facilisi.</p>";

$post_payload ['title'] = new XML_RPC_Value('Sed molestie. Phasellus pede purus','string');
$post_payload ['description'] = new XML_RPC_Value($post,'string');


$params = array(new XML_RPC_Value(1, 'string'),
		new XML_RPC_Value('s9admin', 'string'),
		new XML_RPC_Value('s9admin', 'string'),
		new XML_RPC_Value($post_payload, 'struct')
		);

$msg = new XML_RPC_Message('metaWeblog.newPost',$params);

$cli = new XML_RPC_Client('/serendipity_xmlrpc.php', 'cal.rajshekhar.net');

$resp = $cli->send($msg);

if (!$resp)
  {
    echo 'Communication error: ' . $cli->errstr ."\n";
    var_dump($resp);
    exit;
  }

if (!$resp->faultCode())
  {
    $val = $resp->value();
    $data = XML_RPC_decode($val);
    print "\nPosted the blog post successfully with postid $data\n";
    exit (0);
  }
 else
   {
    echo 'Fault Code: ' . $resp->faultCode() . "\n";
    echo 'Fault Reason: ' . $resp->faultString() . "\n";
    exit (1);
   }

?>

Save this code to a file and chmod +x file . Run it from the command line and the script should be able to post to your blog successfully.

I was quite impressed with the various functions available to me through the xml-rpc interface. Hopefully, I should have a command line program to post to my blog ready in sometime.

Additional information