Thursday, March 3, 2011

Drupal RSS 2 with imagecache images in media enclosures

I got a new project to do. It involved publishing news clips to various sites via valid rss 2.0. The feed includes a headline, a link, a short text and an image. But, the image has to go in an enclosure like the following

<enclosure url="http://domain.com/file.jpg" 
length="3737" 
type="image/jpeg"/>

The way I chose to do this was by setting up a view to handle the listings and then doing a custom template based on the dead simple Basic. I removed all trim and just added the outline of a valid rss 2.0 feed structure by creating my page.tpl.php, node-view-viewname.tpl.php and views-view.tpl.php where node-view-viewname is the template file that will print the actual item. Easy.

Now here comes a problem... To make up for the never-ending creativity of our dear editors, we use ImageCache. Without it we would be lost in a world of image sizes and formats. If you are at all familiar with ImageCache you know that it's lazy and only generates an image if a request for an image fires a 404 error. This is fine for most purposes but since rss media enclosures require certain metadata about the file and it doesn't exist yet we need to force ImageCache to generate the image before we can fill the enclosure tag with the correct values.
We can do this in template.php by adding the following function:

/*
* This function pregenerates ImageCache images
* to give access to the file metadata
* @param $vars
*/
function basic_attach_ic_metadata(&$vars) {
$presetname = "100x100";
$filepath = $vars['field_bild'][0]['filepath'];
$preset = imagecache_preset_by_name($presetname);
$dst = imagecache_create_path($presetname, $filepath);
if (!file_exists($dst)) {
imagecache_build_derivative($preset['actions'], $filepath, $dst);
}
$vars['genimage'] = $dst;
} 

Which in it's turn gets called from template.php like so:

<?php function basic_preprocess_node(&$vars, $hook) {
  basic_attach_ic_metadata(&$vars);
...
}>
Now, when the node is prepared for display the variable $genimage will be set with the path to a generated image. This now available for your node template to consume and we can print the enclosure tag.

<enclosure url="http://domain.com/<?php echo $genimage;?>"
length="<?php echo filesize($genimage);?>" 
type="image/jpeg"/>

All done!

No comments:

Post a Comment