<?php
#CMS Made Simple
#Plugin: {random_image_url}
#(c)2011 by Oliver Seddon <oliverseddon@me.com>
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; version 2 of the License
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#DEFAULT VALUE. EDIT HERE ONLY
function _config_random_image_url( ) {
	$value['folder'] = 'uploads/images/';
	$value['number'] = 1;
	$value['maxdepth'] = 0;
	$value['allowextension'] = 'jpg,jpeg,gif,png';
	$value['includeprefix'] = '';
	$value['excludeprefix'] = 'thumb';
	$value['separator'] = '';
	return $value;
}



function _random_image_url( $path, $url, $maxdepth=0, $allowextension='', $includeprefix='', $excludeprefix='', $d=0 )
{
	$len = strlen(DIRECTORY_SEPARATOR);
	if(substr($path, strlen($path)-$len) != DIRECTORY_SEPARATOR) $path .= DIRECTORY_SEPARATOR;
	if(substr($url, strlen($url)-1) != '/') $url .= '/';
	$dirlist=array();

	if($handle = opendir($path))
	{
		while(false !== ($file=readdir($handle)))
		{
			if($file != '.' && $file != '..')
			{
				$fullpath = $path.$file;
				$fullurl = str_replace('/ /', '%2F', $url.$file);
				if(! is_dir($fullpath))
				{
					$entry = pathinfo($fullpath);
					$basename = $entry['basename'];
					$extension = $entry['extension'];
					$allowit=1;
					$includeit=1;
					$excludeit=0;

					if($allowextension != '')
					{
						$allowit=0;
						$prefixes = explode(',', $allowextension);
						foreach($prefixes as $oneprefix)
						{
							if(strpos($extension, trim($oneprefix)) !== FALSE)
							{
								$allowit = 1;
								break;
							}
						}
					}
					if($includeprefix != '')
					{
						$includeit=0;
						$prefixes = explode(',', $includeprefix);
						foreach($prefixes as $oneprefix)
						{
							if(strpos($basename, trim($oneprefix)) !== FALSE)
							{
								$includeit = 1;
								break;
							}
						}
					}
					if($excludeprefix != '')
					{
						$prefixes = explode(',', $excludeprefix);
						foreach($prefixes as $oneprefix)
						{
							if(strpos($basename, trim($oneprefix)) !== FALSE)
							{
								$excludeit = 1;
								break;
							}
						}
					}

					if($allowit && $includeit && !$excludeit) $dirlist[] = $fullurl;
				}
				elseif($d >= 0 && ($d < $maxdepth || $maxdepth < 0))
				{
					$result = _random_image_url($fullpath, $fullurl, $maxdepth, $allowextension, $includeprefix, $excludeprefix, $d+1);
					$dirlist = array_merge($dirlist, $result);
				}
			}
		}
		closedir($handle);
	}
	return $dirlist;
}

function _check_random_image_url( $n, $max, $min=0 )
{
	$value=array();
	if ($max <= $min) return $value;
	for ($i=0; $i<$n; $i++) {
		do {$num = rand($min,$max-1);} while (in_array($num,$value) && count($value)<$max-$min);
		$value[$i] = $num;
	}
	return $value;
}

function smarty_cms_function_random_image_url($params, &$smarty)
{
	#Get mandatory defaults value
	$value = _config_random_image_url();

	#Check if user has specified an image folder
	$folder = $value['folder'];
	if(isset($params['folder']))
	{
		if(substr($params['folder'],-1) != '/')
		{
			$params['folder'] .= '/';
		}
		$folder = $params['folder'];
	}
	$folder_path = realpath($folder);

	#Check if user has specified an maximum display file number
	$number = $value['number'];
	if(isset($params['number'])) $number = intval(trim($params['number']));

	#Check if user has specified an recursive maximum depth
	$maxdepth = $value['maxdepth'];
	if(isset($params['maxdepth'])) $maxdepth = intval(trim($params['maxdepth']));

	#Check if user has specified an allow extensions, include/exclude prefix for files
	$allowextension = $value['allowextension'];
	if(isset($params['allowextension'])) $allowextension = strtolower(trim($params['allowextension']));
	$includeprefix = $value['includeprefix'];
	if(isset($params['includeprefix'])) $includeprefix = trim($params['includeprefix']);
	$excludeprefix = $value['excludeprefix'];
	if(isset($params['excludeprefix'])) $excludeprefix = trim($params['excludeprefix']);

	#Check if user has specified separator tags
	$separator = $value['separator'];
	if(isset($params['separator'])) $separator = $params['separator'];


	


	#Check directory
	if(is_dir($folder_path))
	{
		$fileList = _random_image_url($folder_path, $folder, $maxdepth, $allowextension, $includeprefix, $excludeprefix);
		$countfileList = count($fileList);

		if(isset($params['debug']))
		{
			$_out  = "<!-- MULTIPLE RANDOM IMAGE DEBUG:\n";
			$_out .= "Relative folder path: $folder\n";
			$_out .= "Absolute folder path: $folder_path\n";
			$_out .= "$countfileList images found in folder (display image number is $number)";
			if($countfileList > 0) $_out .= ":\n" . implode(', ', $fileList);
			return $_out . "\n -->";
		}

		if($countfileList > 0)
		{
			shuffle($fileList);
			if(! empty($number)) $fileList = array_slice($fileList, 0, $number);

			$img=array();
			foreach($fileList as $imgList)
			{
				$base = basename($imgList);

				$_out = "". $imgList .""; //SHOW THE RANDOM IMAGE URL
				$img[] = $_out;
			}
			return implode($separator, $img);
		}
	}
	if(isset($params['debug'])) return "<!-- Trouble folder or no images in: $folder - Absolute folder is: $folder_path -->";
	return '';
}

function smarty_cms_help_function_random_image_url( )
{
?>
<h3>What does this do?</h3>
<p>Shows random URLs of your directory (default uploads/images).
You can set the number of URL's to show simultaneously.
</p>
<h3>How do I use it?</h3>
<p>Just insert the tag into your template/page like: <code>{random_image_url}</code></p>
<h3>What parameters does it take?</h3>
<p>
<ul>
<li><em>(optional)</em> <tt>folder</tt> - RELATIVE URL folder to pick images from. Default is 'uploads/images/'</li>
<li><em>(optional)</em> <tt>debug</tt> - Print a html COMMENT with folder info</li>
<li><em>(optional)</em> <tt>number</tt> - Maximum display image number. Default is 1</li>
<li><em>(optional)</em> <tt>maxdepth</tt> - Recursive folder maximum depth (-1=unlimited). Default is 0 ('folder' only)</li>
<li><em>(optional)</em> <tt>allowextension</tt> - Allow extensions of files (default are 'jpg,jpeg,gif,png')</li>
<li><em>(optional)</em> <tt>includeprefix</tt> - Explicitly include this file only. For 'thumb' you must set empty excludeprefix. Default is unspecified</li>
<li><em>(optional)</em> <tt>excludeprefix</tt> - Explicitly exclude this file only. Default is 'thumb'</li>
<li><em>(optional)</em> <tt>separator</tt> - Separator between file ex: &lt;br /&gt;. Default is unspecified</li>
</ul>
</p>
<?php
}

function smarty_cms_about_function_random_image_url( )
{
?>
<p>Modify version from function.multiple_random_image by Alberto Benati (alby) &lt;<a href="mailto:cms@xme.it">cms@xme.it</a>&gt;</p>
<p>Author: Oliver Seddon &lt;oliverseddon@me.com&gt;</p>
<p>Version: 1.0</p>
<?php
}
?>
