<?php
/**
 * Smarty plugin
 * ----------------------------------------------------------------
 * Type:     modifier
 * Name:     proot
 * Purpose:  Wraps string in p tags
 * 			 accepts two extra args
 * 			 $rootElement = the root element without the brackets
 * 			
 *           $replace_br = default to true
 * 			 replaces br tags with root element blocks
 * 			
 * 			Usage: 
 * 				{$string|proot}
 * 				{$string|proot:"div"} - will use div instead of p
 * 				{$string|proot:"p",false} - don't replace br
 * 
 * Author:   Ken Griffith, kengriffith@gmail.com /
 *        http://dev.cmsmadesimple.org/users/kendo451/
 * ----------------------------------------------------------------
 **/
function smarty_cms_modifier_proot($string, $rootElement='p', $replace_br = true )
{
  
  	// trim whitespace
  	$string = trim($string);
	
	// remove multiple spaces, line returns, and tabs
	$string = preg_replace( '/\s+/', ' ', $string );
	
	// remove whitespace in empty tags
	$string = str_replace( '> <', '><', $string);
	 
	// setup search strings from possible allowed values
  
  	$rootElementUpper = strtoupper( $rootElement );
	$rootElementLower = strtolower( $rootElement );
  
	$tagOpen = array( 
				'<' . $rootElementLower . '>' ,
				'<' . $rootElementLower . ' ' ,
				'<' . $rootElementUpper . '>' ,
				'<' . $rootElementUpper . ' ' 
				);

	$tagClose = array( '</' . $rootElementLower . '>' , '</' . $rootElementUpper . '>' );
	
	// Set up tags for append / prepend / break replacement			
	$prependTag = '<' . $rootElementLower . '>';
	$appendTag = '</' . $rootElementLower . '>';
  
	// Test if string starts with root tag, ignoring attributes
	$hasRoot = false;
	foreach( $tagOpen as $tag ){
		
		$length = strlen($tag);
		if ( substr($string, 0, $length) === $tag ) $hasRoot = true;
	}
	
	if ( !$hasRoot ) $string = $prependTag . $string;
	

	
	// Test if string ends with p tag
	
	$hasRoot = false;
	
	foreach ( $tagClose as $tag ){
		
		$length = strlen($tag);
    	$start  = $length * -1; //negative
	
		if ( substr($string, $start) === $tag ) $hasRoot = true;
		
	}
	
	if ( !$hasRoot ) $string .= $appendTag;
	

	
	// If replace break flag is true then replace breaks
	if ($replace_br) {
		
		// setup replacement string
		$brReplace = $appendTag . $prependTag;		
		
		// setup search string
		$brsearch = array ( '<br/>','<br>','<BR/>','<BR>','<Br/>','<Br>','<bR/>','<bR>');
		
		foreach ( $brsearch as $term ) $string = str_replace( $term, $brReplace, $string);	
		
	}
	

	
	//clean up multiple line returns
	while ( strpos( $string , $brReplace . $brReplace ) ) {
		$string = str_replace( $brReplace . $brReplace , $brReplace, $string);
	}
	


  	return $string;    
}//end of function
?>
