<?php
if(!@session_id()){
	@session_start();
}


//print ("<pre>");
//print_r ($_SERVER);
//print ("</pre>");
//<//////////////////////////////////////////////////////////////
//                                                             //
//                                                             //
//                                                             //
//                                                             //
//                   Pickle Auto Playlist                      //
//                         v 1.1.3                             //
//                        12/1/2012                            //
//          Available at http://www.pickleplayer.com           //
//                 Copyright 2002-2012 plaino                  //
//                                                             //
//                                                             //
//                    USE AT YOUR OWN RISK                     //
//                                                             //
//                                                             //
/////////////////////////////////////////////////////////////////
//                                                             //
//                       INSTALLATION:                         //
//                                                             //
/////////////////////////////////////////////////////////////////
// 
// Upload autoplaylist.php to the folder that contains your media files.
// 
// USE AT YOUR OWN RISK.

$pickleVersion = "1.1.3";


// --- allowFolderNavigation
$allowFolderNavigation = true;

// --- playlistKind
// Playlists can be either "xml" or "txt". XML playlists allow for 
// cover art images and if the getid3 library is available, 
// Artist and Title extraction from MP3 ID3 information.
// ID3 extraction currently only works for MP3 files.
// $playlistKind = "xml";
// $playlistKind = "txt";
$playlistKind = "xml";

// --- defaultVisualExt
// The default poster (cover art) image extension to search for:
$defaultVisualExt = "jpg";

// --- media_types
// The kinds of files to search for:
$media_types = "mp4,m4a,m4p,m4v,aac,mp3";

// --- hide_keywords
// Files containing these keywords will be ignored.
$hide_keywords = "skin,pickle,config,customizer,source,plugin";

// --- httpOption
// Allows you to run pickle in "https" mode;
//$httpOption = "https";
$httpOption = "http";

// --- hide_folders
// A list of folder names to ignore.
$hide_folders = "_notes,skins,getid3,_private,_private,_vti_bin,_vti_cnf,_vti_pvt,_vti_txt,cgi-bin";

// --- hide_files
// A list of file names to ignore.
$hide_files = "";

// --- findAllMedia
// When set to "true", will recursively search through all subdirectoies. 
$findAllMedia = false;

// --- coverartBasename
// IGNORE. NOT IMPLIMENTED.
$coverartBasename = "coverart.jpg";

// --- getMyid3info
// Requires the getid3 library.
$getMyid3info = "no";

// --- quirksmode
// If not using gthe getID3 library, sets titles using the filename, but only shows text "between the dots"
// example: 01.MyTrack.mp3 would display as "MyTrack"
// This allows for files to be manually sorted within the folder.
$quirksmode = false;

// --- shuffle files
// Randomizes the file list order. (Does not randomize folder lists.)
$shuffle = false;

// --- sortOrder
// Sets the sort order for files.
// Ascending (A-Z);
$sortOrder = "asc"; 
// Descending (Z-A);
//$sortOrder = "dec";

// --- sortIndex
// Which field to sort on:
$sortIndex = "filename";
// Modification date of the file on the server:
//$sortIndex = "date";
// Only available if using the GetID3 option.
//$sortIndex = "artist";
// Generally the "base name" of the file. Or if using GetID3 option, the actual title in the ID3 tag.
// See also "Quirks mode" above as well.
//$sortIndex = "title";

// --- backText
// The text that appears at th top of each directory list.
// NOTE: You may include HTML, for example to display an image.
$backText = "< Back";




/////////////////////////////////////////////////////////////////
//                                                             //
//         Do not edit anything below here unless              //
//          you really know what you are doing!                //
//                                                             //
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////


define("newline", "\r\n");
define("slash", "/");

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//              security and request clean
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////


// prevent certain extensions from being downloaded
function secureFiles($fileName, $extCheck){
	$ext = explode('.',$fileName);
	$myExt = strtolower($ext[sizeof($ext)-1]);
	if(strtolower($myExt) != strtolower($extCheck)){
		return false;
	} else {
		return true;
	}
	if ((!ereg('\.\.', $fileName)) && (file_exists($fileName))) {
		return true;
	} else {
		return false;
	}
}


// strip hacker requests
function striphack($string){
	$retval = $string;
	//*
	$retval = strip_tags(stripslashes(rawurldecode(utf8_decode($retval))));
	$retval = strip_tags($retval);
	$retval = str_replace("sscanf", "x", $retval);
	$retval = str_replace("printf", "x", $retval);
	$retval = str_replace("base64_decode", "x", $retval);
	$retval = str_replace("rawurldecode", "x", $retval);
	$retval = str_replace("urldecode", "x", $retval);
	$retval = str_replace("0;", "x", $retval);
	$retval = str_replace("%5C", "x", $retval);
	$retval = str_replace("\n", "x", $retval);
	$retval = str_replace("\r", "x", $retval);
	$retval = str_replace("\t", "x", $retval);
	$retval = str_replace("\\", "x", $retval);
	$retval = str_replace("./", "x", $retval); 
	$retval = str_replace("..","x",$retval);
	if (function_exists('escapeshellcmd')) {
		//$retval = escapeshellarg($retval);
		$retval = escapeshellcmd ($retval);
	}
	//*/
	return $retval;
}


function secureArray($array_in){
	if(@is_array($array_in)){
		foreach ($array_in as $key => $value){
			$Atemp[striphack($key)] = striphack($value);
		}
	} else {
		$Atemp = $array_in;
	}
	return $array_in;
}




if ( @get_magic_quotes_gpc () ){
   function traverse ( &$arr ){
       if ( !is_array ( $arr ) ){
           return;
	   }
       foreach ( $arr as $key => $val ){
           is_array ( $arr[$key] ) ? traverse ( $arr[$key] ) : ( $arr[$key] = stripslashes ( $arr[$key] ) );
	   }
   }
   $gpc = array ( &$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
   traverse ( $gpc );
}


$_REQUEST = secureArray($_REQUEST);
$_GET = secureArray($_GET);
$_POST = secureArray($_POST);
$_COOKIE = secureArray($_COOKIE);

// these get set after default settings below because getid3 and coverartbasename should be over-written by request
//
// see: (below)
/*
foreach($_REQUEST as $key => $value){
	if(in_array($key, $AcheckRequests)){
		$$key = $value;
	} else {
		unset($$_REQUEST[$key]);
	}
}
*/
$AcheckRequests = array();
$AcheckRequests[] = "action";
$AcheckRequests[] = "kind";
$AcheckRequests[] = "dir";



/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                     FILE PATHS
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

/*
if(@ini_get('safe_mode')){
	print('<table width="46%" border="0" align="center" cellpadding="010" cellspacing="0" bgcolor="#FFFFCC">');
	print('  <tr>');
	print('    <td><p><b><font color="#CC0000" size="2" face="Arial, Helvetica, sans-serif">');
	print('ERROR</font></b><font size="2" face="Arial, Helvetica, sans-serif"><br>');
	print('    <br>');
	print('	PHP is running in <b>"Safe Mode"</b> which prevents');
	print('	pickle from performing <br>');
	print('	necessary functions such as');
	print('	automatically reading the contents of a directory." <br>');
	print('	<br>');
	print('	Check with your hosting provider to see if they can');
	print('	turn off <b>"Safe Mode"</b> for your account."</font></p></td>');
	print('  </tr>');
	print('</table>');
}
*/

if(@ini_get('safe_mode')){
	print('<?xml version="1.0"?>');
	print('<playlist>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>1. ERROR</title>');
	print('	</item>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>2. PHP is running in "Safe Mode".</title>');
	print('	</item>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>3. Contact Server Admin to Correct.</title>');
	print('	</item>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>4. ------------------</title>');
	print('	</item>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>5. You can still use Rave,</title>');
	print('	</item>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>6. however all URLs must be</title>');
	print('	</item>');
	print('	<item>');
	print('		<filename>ERROR</filename>');
	print('		<title>7. entered manually.</title>');
	print('	</item>');
	print('</playlist>');
	exit;
}


//strstr( PHP_OS, "WIN") ? $osType = "win" : $osType = "unix";


if(!@getcwd ()){
	$pickle_PATH['physical'] = str_replace("\\", "/", dirname(__FILE__));
} else {
	$pickle_PATH['physical'] = str_replace("\\", "/", getcwd ());
}


/*
if(!@getcwd ()){
	$pickle_PATH['physical'] = dirname(__FILE__);
} else {
	$pickle_PATH['physical'] = getcwd ();
}
*/

if(!isset($_SERVER['SCRIPT_NAME'])){
	$_REQUEST = get_defined_vars();
	$_SERVER = $HTTP_SERVER_VARS;
}




$Apathtome = explode("/", $_SERVER['PHP_SELF']);
$picklePhp = array_pop($Apathtome);
//$pathtome = implode("/", $Apathtome);
$pickle_PATH['wwwroot'] = $httpOption."://".$_SERVER['HTTP_HOST'];
$pickle_PATH['www'] = $pickle_PATH['wwwroot'].(implode("/", $Apathtome));
$pickle_PATH['wwwself'] = $_SERVER['PHP_SELF'];


/*
print ("<pre>");
print_r ($Apathtome);
print ("</pre>");
print ("<br>");
print $picklePhp;
print ("<br>");
exit;
*/



/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                DEFAULT SETTINGS / SET CONFIGS
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////



foreach($_REQUEST as $key => $value){
	if(in_array($key, $AcheckRequests)){
		$$key = $value;
	} else {
		unset($$_REQUEST[$key]);
	}
}


if(isset($kind)){
	$playlistKind = $kind;
	$kind = null;
}


// Vars that should not be over-written by an external pickleConfigs.xml file:
$hiderVars = Array("hide_folders", "hide_files");

$AdefaultVisual = explode(".", $coverartBasename);
$defaultVisualBaseName = $AdefaultVisual[0];
//$defaultVisualExt = $AdefaultVisual[1];

function setCoverartBasenameData(){
	global $AdefaultVisual, $defaultVisualBaseName, $defaultVisualExt, $coverartBasename;
	$AdefaultVisual = explode(".", $coverartBasename);
	$defaultVisualBaseName = $AdefaultVisual[0];
	$defaultVisualExt = $AdefaultVisual[1];
}


function file_get_as_string($file){
	$file = @file("$file");
	return !$file ? false : implode('', $file);
}



// Thse vars need to be set after reading the config file.
if(isset($coverartBasename) && $coverartBasename != ""){
	setCoverartBasenameData();
}


$pickle_PATH['physical'] = str_replace("\\", "/", $pickle_PATH['physical']);
$pickle_PATH['physical'] = str_replace("//", "/", $pickle_PATH['physical']);




/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                DIRECTORY READING
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

$Ahide_files = explode(",",$hide_files);
$Ahide_folders = explode(",",$hide_folders);
$Amedia_types = explode(",",$media_types);
$Akeywords = explode(",",$hide_keywords);


function checkKeyWords($Ahaystack, $needle){
	foreach($Ahaystack as $value){
		if(@stristr(strtolower($needle), strtolower($value))){
			return true;
		}
	}
	return false;
}

function GetDirArrayRecursive($dir, $filter=false) {
	global $Amedia_types, $Ahide_files, $Ahide_folders, $Akeywords;
	if($filter){
		$Afilter = $filter;
	} else {
		$Afilter = $Amedia_types;
	}
	$Afiles = array ();
	if(!$dir || $dir == ""){
		$dir = ".";
	}
	$handle=@opendir($dir);
	//$d = dir($dir);
	if($dir){
		while (false !== ($entry = @readdir($handle))){
		//while (false !== ($entry = $d->read())) {
			if($entry!='.' && $entry!='..') {
				$entry = $dir.'/'.str_replace("\\", "/", $entry);
				$pathinfo = path_parts($entry);
				if(is_dir($entry)) {
					if(!checkKeyWords($Ahide_folders, $pathinfo['filename']) && !checkKeyWords($Akeywords, $pathinfo['filename'])){
						$Afiles = array_merge($Afiles, GetDirArrayRecursive($entry, $Afilter));
					}
				} else {
					if(in_array(strtolower($pathinfo['ext']), $Afilter)){
						if(!checkKeyWords($Ahide_files, $pathinfo['filename']) && !checkKeyWords($Akeywords, $pathinfo['filename'])){
							$Afiles[] = $entry;
						}
					}
				}
			}
		}
		@closedir($handle);
		//$d->close();
	}
	return $Afiles;
}


function GetDirArray($dir){

	global $allowFolderNavigation, $Amedia_types, $Ahide_files, $Ahide_folders, $Akeywords;
	$Asee = array();
	$Aitems = array ();
	$Adirs = array ();
	$Afiles = array ();
	$handle=@opendir($dir);
	//$d = dir(utf8_encode($dir));
	if($dir){
		while (false !== ($entry = @readdir($handle))){
		//while (false !== ($entry = $d->read())) {
			if($entry != '.' && $entry != '..' && substr ($entry, 0, 1 ) != "..") {
				$entry = $dir.'/'.str_replace("\\", "/", $entry);
				$pathinfo = path_parts($entry);
				if(is_dir($entry) && $allowFolderNavigation == true) {
					if(!checkKeyWords($Ahide_folders, $pathinfo['filename']) && !checkKeyWords($Akeywords, $pathinfo['filename'])){
						$Adirs[] = $entry;
					}
				} else {
					if(in_array(strtolower($pathinfo['ext']), $Amedia_types)){
						if(!checkKeyWords($Ahide_files, $pathinfo['filename']) && !checkKeyWords($Akeywords, $pathinfo['filename'])){
							$Afiles[] = $entry;
						}
					}
				}
			}
		}
		@closedir($handle);
		//$d->close();
	}
	$Aitems['dirs'] = $Adirs;
	$Aitems['files'] = $Afiles;
	return $Aitems;
}

function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
	
	// Check that user array is a proper array
	if(is_array($array) && count($array)>0) {
		
		// Create temp array identical to user array.
		foreach(array_keys($array) as $key) {
			$temp[$key]=$array[$key][$index];
		}
		
		// Not using natural sorting, do traditional sort.
		if(!$natsort) {
			
			// Set sort order (asc: A-Z, dec: Z-A)
			if ($order == 'asc'){
				asort($temp);
			} else {   
				arsort($temp);
			}
		
		} else {
			
			// Using case sensativity.
			if ($case_sensitive === true) {
				natsort($temp);
			
			// Ignore case-sensativity.
			} else {
				natcasesort($temp);
			}
			
			// Set sort order (asc: A-Z, dec: Z-A)
			if($order != 'asc') {
				$temp=array_reverse($temp,TRUE);
			}
			
		}
		
		// Build out
		foreach(array_keys($temp) as $key) {

			// If numbers, just auto-increment array indexes
			if (is_numeric($key)) {
				$sorted[]=$array[$key];

			// Otherwise, set index to key
			} else {
				$sorted[$key]=$array[$key];
			}
			
		}
		
		return $sorted;
		
	} else {
		
		// User didn't send a proper array, 
		// so just send back the original array.
		return $array;
		
	}
	
}



function printArray($theArray, $exit=false){
	print "<pre>";
	print_r($theArray);
	print "</pre>";
	if($exit){
		exit;
	}
}


/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                CONVERSION
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////


function cleanForXML($theString){

	$retval = str_replace("&", "&amp;", $theString);
	$retval = str_replace("<", "&lt;", $retval);
	$retval = str_replace(">", "&gt;", $retval);
	$retval = str_replace("'", "&apos;", $retval);
	$retval = str_replace('"', "&quot;", $retval);

	return $retval;
}


/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                XML Playlist
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

function returnXMLkeys($AitemInfo){
	$retval = "";
	foreach($AitemInfo as $key => $val){
		$retval .= "<".$key.">".cleanForXML(trim($val))."</".$key.">".newline;
	}
	return $retval;
}



function makePlaylist($theDir, $recursive=false, $doBack=false){
	global $allowFolderNavigation, $backText, $pickle_PATH, $pickleApp, $defaultVisualBaseName, $defaultVisualExt, $playlistKind, $sortOrder, $sortIndex, $quirksmode, $shuffle;

	$sPath = utf8_decode(rawurldecode($theDir));
	if($recursive){
		$AdirList['files'] = GetDirArrayRecursive($sPath);
		$AdirList['dirs'] = array();
	} else {
		$AdirList = GetDirArray($sPath);
	}


	//////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////


	// Files
	$Adirs = array();
	$Afiles = array();
	
	$backObj = array();
	
	
	
	if($doBack == true && $allowFolderNavigation == true){
		$tempName = $sPath."/";
		$path_info = path_parts($tempName);
	
		// File URL
		$backpath = path_parts($path_info['basepath']);
		$myFileURL = filepath2url($backpath['basepath']);
//print($sPath);
//exit;
	
	
		$backObj['filename'] = $pickle_PATH['wwwself']."?action=dir&dir=".rawurlencode($myFileURL);
		$backObj['image'] = lookForVisual($tempName.slash."coverart".".".$defaultVisualExt);
		$backObj['filekind'] = "dir";
		if($quirksmode){
			$Aquirk = explode(".", $path_info['filename']);
			array_shift($Aquirk);
			$path_info['filename'] = implode($Aquirk);
		}

		$backObj['title'] = $backText;
	}
	
	if(sizeof($AdirList['dirs']) > 0){
		
		$tempName = $AdirList['dirs'][0];
		$path_info = path_parts($tempName);
		
		// File URL
		$backpath = path_parts($path_info['basepath']);
		$myFileURL = filepath2url($backpath['basepath']);

		/*
		if($doBack == true){
			$backObj['filename'] = $pickle_PATH['wwwself']."?action=dir&dir=".rawurlencode($myFileURL);
			$backObj['image'] = lookForVisual($tempName.slash."coverart".".".$defaultVisualExt);
			$backObj['filekind'] = "dir";
			if($quirksmode){
				$Aquirk = explode(".", $path_info['filename']);
				array_shift($Aquirk);
				$path_info['filename'] = implode($Aquirk);
			}

			$backObj['title'] = "< Back";
		}
		*/

		//$Adirs[] = $Aitem;
		
		for($i = 0; $i < sizeof($AdirList['dirs']); $i++){

			$tempName = $AdirList['dirs'][$i];
			$path_info = path_parts($tempName);
			
			// File URL
			$myFileURL = filepath2url($tempName);

			$Aitem = array();

			$Aitem['date'] = filemtime($tempName);
			$Aitem['filename'] = $pickle_PATH['wwwself']."?action=dir&dir=".rawurlencode($myFileURL);
			$Aitem['image'] = lookForVisual($tempName.slash."coverart".".".$defaultVisualExt);
			$Aitem['filekind'] = "dir";
			if($quirksmode){
				$Aquirk = explode(".", $path_info['filename']);
				array_shift($Aquirk);
				$path_info['filename'] = implode($Aquirk);
			}

			$Aitem['title'] = $path_info['filename'];

			$Adirs[] = $Aitem;
			
		}
	}

	if(sizeof($AdirList['files']) > 0){
		for($i = 0; $i < sizeof($AdirList['files']); $i++){

			$tempName = $AdirList['files'][$i];
			$path_info = path_parts($tempName);
			
			// File URL
			$myFileURL = filepath2url($tempName);

			$Aitem = array();

			$Aitem['date'] = filemtime($tempName);
			$Aitem['filename'] = $myFileURL;
			$Aitem['image'] = lookForVisual($path_info['basepath'].slash.$path_info['basename'].".".$defaultVisualExt);

			if(strtolower($path_info['ext']) == "mp3"){
				$Aid3 = getID3info4me($tempName);
			} else {
				$Aid3 = array();
			}

			if($quirksmode){
				$Aquirk = explode(".", $path_info['basename']);
				array_shift($Aquirk);
				$path_info['basename'] = implode($Aquirk);
			}

			$Aitem['artist'] = @$Aid3['artist'];
			$Aitem['title'] = (@$Aid3['title'])? @$Aid3['title'] : $path_info['basename'];

			$Afiles[] = $Aitem;
			
		}
	}
	
	//sortmulti ($theArray, $index, $order, $natsort=FALSE, $case_sensitive=FALSE);
	$sortIndex = strtolower($sortIndex);
	$sortOrder = strtolower($sortOrder);
	$Afiles = sortmulti ($Afiles, $sortIndex, $sortOrder, true, FALSE);
	$Adirs = sortmulti ($Adirs, $sortIndex, $sortOrder, true, FALSE);

	//printArray($Afiles, true);

	$retval = "";

	if($playlistKind == "xml"){
		$playlistCoverart = cleanForXML(lookForVisual($sPath.slash.$defaultVisualBaseName.".".$defaultVisualExt));
		$tackImage = "";
		if($playlistCoverart){
			$tackImage =  ' image="'.$playlistCoverart;
		}
		$retval = "<playlist$tackImage>".newline;
	} else {
		$retval = "";
	}
	
	if($doBack == true){
		if($playlistKind == "xml"){
			$retval .= '<item>'.newline;
			$retval .= returnXMLkeys($backObj);
			$retval .= "</item>".newline;
		} else {
			$retval .= $backObj['filename'].newline;
		}
	}
	
	for($i = 0; $i < sizeof($Adirs); $i++){
		if($playlistKind == "xml"){
			$retval .= '<item>'.newline;
			$retval .= returnXMLkeys($Adirs[$i]);
			$retval .= "</item>".newline;
		} else {
			$retval .= $Adirs[$i]['filename'].newline;
		}
	}
	
	if($shuffle == true){
		shuffle($Afiles); 
	}
	
	for($i = 0; $i < sizeof($Afiles); $i++){
		if($playlistKind == "xml"){
			$retval .= '<item>'.newline;
			$retval .= returnXMLkeys($Afiles[$i]);
			$retval .= "</item>".newline;
		} else {
			$retval .= $Afiles[$i]['filename'].newline;
		}
	}
	if($playlistKind == "xml"){
		$retval .= "</playlist>";
	}

	$retval = fromTheRoot($retval);
	
	@clearstatcache();
	return $retval;

}

function path_parts($thePath) {
	$thePath = str_replace("\\", "/", $thePath);
	$filepathA = explode("/", $thePath);
	$filename = array_pop($filepathA);
	$filepathB = explode(".", $filename);
	$extension = array_pop($filepathB);
	$basename = implode(".", $filepathB);
	$basePath = join("/", $filepathA);
	$Aret = array();
	$Aret['filename'] = $filename;
	$Aret['ext'] = $extension;
	$Aret['basename'] = $basename;
	$Aret['basepath'] = $basePath;
	return $Aret;
}

function getID3info4me($theFile_in){
	global $getMyid3info, $getID3;
	if($getMyid3info == "yes"){
		$info = $getID3->analyze(urldecode($theFile_in));
		getid3_lib::CopyTagsToComments($info);
	} else {
		$info = array();
	}
	$retval = array();
	if(sizeof($info)>0){
		if(isset($info['comments_html'])){
			$Atemp = @$info['comments_html'];
			foreach($Atemp as $key => $val){
				$retval[$key] = $val[0];
			}
			$retval['seconds']=(@$info['playtime_seconds']);
		}
	}
	return $retval;
}

function lookForVisual($theFile){
	global $pickleApp,$defaultVisualBaseName, $defaultVisualExt, $pickle_PATH;
	$visualFound = "";
	if (@is_file($theFile)){
		$visualFound = filepath2url($theFile);
	}
	return $visualFound;
}

function lookForInfo($theFile){
	global $pickleApp, $pickle_PATH;
	$retval = "";
	if(@is_file($theFile)){
		$retval = file_get_as_string($theFile);
	}
	return $retval;
}


function url2filepath($theURL){
	global $pickle_PATH;
	$pubPath = str_replace($pickle_PATH['www'], "", $theURL);
	$theFilepath = $pickle_PATH['physical'].$pubPath;
	$theFilepath = str_replace("//", "/", $theFilepath);
	return $theFilepath;
}


function filepath2url($theFilepath){
	global $pickle_PATH;
	$pubPath = str_replace($pickle_PATH['physical'], "", $theFilepath);
	$theFilepath = $pickle_PATH['www'].$pubPath;
	$theFilepath = str_replace("://", "__:__", $theFilepath);
	$theFilepath = str_replace("//", "/", $theFilepath);
	$theFilepath = str_replace("__:__", "://", $theFilepath);

	return $theFilepath;
}

function fromTheRoot($theURL){
	global $pickle_PATH;
	$theFilepath = str_replace($pickle_PATH['wwwroot'], "", $theURL);
	return $theFilepath;
}

	

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                    WRITE X-HTML
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////


function printXML($theXML){
	$XMLlead = '<'.urldecode("%3F").'xml version="1.0"  encoding="UTF-8" '.urldecode("%3F").'>';
	//*
	header("Pragma: public", false);
	header("Expires: Thu, 19 Nov 1981 08:52:00 GMT", false);
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0", false);
	header("Cache-Control: no-store, no-cache, must-revalidate", false);
	header("Content-Type: text/xml");
	//*/
	print (utf8_encode($XMLlead.$theXML));
	exit;
}

function printTEXT($theList){

	header("Pragma: public", false);
	header("Expires: Thu, 19 Nov 1981 08:52:00 GMT", false);
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0", false);
	header("Cache-Control: no-store, no-cache, must-revalidate", false);
	header("Content-Type: text/plain");

	print (utf8_encode($theList));
	exit;
}



/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
//                    ACTIONS
//
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

if(!isset($action)){
	$action = "";
}

if($action == "getVersion"){
	print "Pickle Auto Playlist Version: $pickleVersion";
	exit;
} else if ($action == "dir"){

	if($getMyid3info == "yes"){
		if(is_file('getid3.php')){
			require ('getid3.php');
			$getID3 = new getID3;
		} else if (is_file('getid3'.slash.'getid3.php')){
			require ('getid3'.slash.'getid3.php');
			$getID3 = new getID3;
		} else if (is_file(@$getid3libPath)){
			require (@$getid3libPath);
			$getID3 = new getID3;
		} else {
			$getMyid3info = "no";
		}
	}

	$setDir = @$_REQUEST['dir'];
	
	//if(!$setDir || substr ($setDir, 0, 2 ) == ".." || $setDir.substr(0,1) == "/" || $setDir.substr(0,1) == "\\"){
	//if(!$setDir || substr ($setDir, 0, 2 ) == ".." || substr($setDir, 0, 1) == "/" || substr($setDir, 0, 1) == "\\"){
	if(!substr($setDir, 0, 1) == "/"){
		 $setDir = "";
	}
	
	$setDir = rawurldecode($setDir);
	
		//print($setDir);
		//exit;
		
	if($setDir == $pickle_PATH['www']){
		$doBack = false;
	} else {
		$doBack = true;
	}
	
	if($playlistKind == "xml"){
		header("Content-Type: text/xml; charset=utf-8", false);
		printXML(makePlaylist(url2filepath($setDir), false, $doBack));
	} else {
		header("Content-Type: text/plain; charset=utf-8", false);
		printTEXT(makePlaylist(url2filepath($setDir), false, $doBack));
	}

} else {

	if($getMyid3info == "yes"){
		if(is_file('getid3.php')){
			require ('getid3.php');
			$getID3 = new getID3;
		} else if (is_file('getid3'.slash.'getid3.php')){
			require ('getid3'.slash.'getid3.php');
			$getID3 = new getID3;
		} else if (is_file(@$getid3libPath)){
			require (@$getid3libPath);
			$getID3 = new getID3;
		} else {
			$getMyid3info = "no";
		}
	}

	$getall = false;

	if($findAllMedia == "yes"){
		$getall = true;
	}

	if($playlistKind == "xml"){
		header("Content-Type: text/xml; charset=utf-8", false);
		printXML(makePlaylist($pickle_PATH['physical'], $getall, false));
	} else {
		header("Content-Type: text/plain; charset=utf-8", false);
		printTEXT(makePlaylist($pickle_PATH['physical'], $getall, false));
	}
}
?>