Joomla 1.5 and link rel canonical seo

I have several sites running on Joomla! but I have been suffering with the my search engine optimization ever since google released Panda.  I think the primary reason was due to duplicate content.    After researching on the issue I really could not find a  good solution that met my specific need.

What I wanted, was if I had several menus that pointed to the same article generate a <link rel=”canonical” href=””> meta tag.

Below is the code that I came up with to generate a meta tag on every page.   I will attached a text file with the code to the post also and you can download the joomla_code here.   Simply copy this code and put it in between the <HEAD></HEAD> tags if your /template/[TEMPLATE_NAME]/index.php file.

To see this code in action
<?php
$db =& JFactory::getDBO();
$menu = &JSite::getMenu();
$active = $menu->getActive()->id;
$query = "
SELECT m2.".$db->nameQuote('alias')."
FROM ".$db->nameQuote('#__menu')." m1
JOIN ".$db->nameQuote('#__menu')." m2
ON m1.".$db->nameQuote('link')." = m2.".$db->nameQuote('link')."
WHERE m1.".$db->nameQuote('id')." = ".$db->quote($active)."
AND m2.".$db->nameQuote('published')." = ".$db->quote('1')."
ORDER BY m2.".$db->nameQuote('ordering')."
LIMIT 1;
";
$db->setQuery($query);
$relLink = $db->loadResult();
printf("<link rel=\"canonical\" href=\"%s/%s\" />\n",JURI::base(),$relLink);
?>