<?php
#find_content function
#
#Copyright (C) 2011 by Martijn W. van der Lee
#
#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.

function smarty_cms_function_find_content__find($node, $block) {
	if ($content = $node->getContent())
	{
		if ($value = $content->GetPropertyValue($block))
		{
			return $value;
		}
		
		return smarty_cms_function_find_content__find($node->getParent(), $block);
	}
}

function smarty_cms_function_find_content($params, &$smarty)
{
	$cmsms = cmsms();

	$value = smarty_cms_function_find_content__find($cmsms->GetHierarchyManager()->sureGetNodeByAlias($cmsms->get_variable('page_name')), $params['block']);

	if (empty($value) && $params['default'])
	{
		$value = $params['default'];
	}

	if ($params['assign'])
	{
		$smarty->assign($params['assign'], $value);
	}
	else
	{
		return $value;
	}
}

function smarty_cms_help_function_find_content()
{
	?>
	<h3>What does this do?</h3>
	<p>Find the first non-empty content block in the tree starting from current page and going up to the root page.</p>
	<h3>How do I use it?</h3>
	<p>Insert the tag into your template/page like: <code>{find_content block=&quot;text&quot; default=&quot;default value&quot; assign=&quot;variable&quot;}</code></p>
	<h3>What parameters does it take?</h3>
	<ul>
		<li><em>(required)</em> block - the name of the content block to find.</li>
		<li><em>(optional)</em> default - if no filled content block is found, the default value is returned. If no default specified, an empty string is returned.</li>
		<li><em>(optional)</em> assign - name of a Smarty variable to which the result is assigned.</li>
	</ul>
	<?php
}


function smarty_cms_about_function_find_content() 
{
?>
  <p>Author:  Martijn W. van der Lee (www.vanderlee.com),</p>
  <p>Version 1.0</p>
  <p>Change History<br/>
     1.0 - Initial release<br/>
  </p>
<?php
}

?>