<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org>               //
//  available at http://getid3.sourceforge.net                 //
//            or http://www.getid3.org                         //
/////////////////////////////////////////////////////////////////
//                                                             //
// /demo/demo.browse.php - part of getID3()                     //
// Sample script for browsing/scanning files and displaying    //
// information returned by getID3()                            //
// See readme.txt for more details                             //
//                                                            ///
/////////////////////////////////////////////////////////////////

// just for development & debugging
//$arr = array();
//$tfolder = '/pub/fokradioarchiv/';
//echo wikiplugin_mfolder($tfolder, $arr );

function wikiplugin_mfolder_help() {
        return tra('NO HELP - testing');
}

function wikiplugin_mfolder($folder, $params) {

extract ($params);
require_once('lib/getid3/getid3.php');
// Initialize getID3 engine
$getID3 = new getID3;
$asetup = '';
$debug  = '';
$writescriptfilename = 'wikiplugin_mfolder.php';

//$folder = 'pub/fokradioarchiv/';
//$asetup .=  '<html><head>';
//$asetup .=  '<title>browse folder for media</title>';
//$asetup .=  '</head><body>';

$_REQUEST['listdirectory'] = $_SERVER['DOCUMENT_ROOT'].$folder; 
$URLFolder = 'http://'.$_SERVER['HTTP_HOST'].$folder; 
$debug .= 'folder:'.$folder.'<br>';
$debug .= 'ls folder::'.$_REQUEST['listdirectory'].'<br>';
$debug .= 'URL folder:'.$URLFolder.'<br>';

if (isset($_REQUEST['filename'])) {
	if (!file_exists($_REQUEST['filename'])) {
		die($_REQUEST['filename'].' does not exist');
	}
	$AutoGetHashes = (bool) (filesize($_REQUEST['filename']) < 52428800); // auto-get md5_data, md5_file, sha1_data, sha1_file if filesize < 50MB
	$getID3->option_md5_data  = $AutoGetHashes;
	$getID3->option_sha1_data = $AutoGetHashes;
	$ThisFileInfo = $getID3->analyze($_REQUEST['filename']);
	if ($AutoGetHashes) {
		$ThisFileInfo['md5_file']  = getid3_lib::md5_file($_REQUEST['filename']);
		$ThisFileInfo['sha1_file'] = getid3_lib::sha1_file($_REQUEST['filename']);
	}


	getid3_lib::CopyTagsToComments($ThisFileInfo);

	$listdirectory = dirname(getid3_lib::SafeStripSlashes($_REQUEST['filename']));
	$listdirectory = realpath($listdirectory); // get rid of /../../ references

	if (GETID3_OS_ISWINDOWS) {
		// this mostly just gives a consistant look to Windows and *nix filesystems
		// (windows uses \ as directory seperator, *nix uses /)
		$listdirectory = str_replace('\\', '/', $listdirectory.'/');
	}

	if (strstr($_REQUEST['filename'], 'http://') || strstr($_REQUEST['filename'], 'ftp://')) {
		$asetup .=  '<i>Cannot browse remote filesystems</i><BR>';
	} else {
		$asetup .=  'Browse: <a href="'.$_SERVER['PHP_SELF'].'?listdirectory='.urlencode($listdirectory).'">'.$listdirectory.'</a><BR>';
	}

} else {

	$listdirectory = (isset($_REQUEST['listdirectory']) ? getid3_lib::SafeStripSlashes($_REQUEST['listdirectory']) : '.');
	$listdirectory = realpath($listdirectory); // get rid of /../../ references
	$currentfulldir = $listdirectory.'/';

	if (GETID3_OS_ISWINDOWS) {
		// this mostly just gives a consistant look to Windows and *nix filesystems
		// (windows uses \ as directory seperator, *nix uses /)
		$currentfulldir = str_replace('\\', '/', $listdirectory.'/');
	}

	if ($handle = @opendir($listdirectory)) {

		$TotalScannedUnknownFiles  = 0;
		$TotalScannedKnownFiles    = 0;
		$TotalScannedPlaytimeFiles = 0;
		$TotalScannedBitrateFiles  = 0;
		$TotalScannedFilesize      = 0;
		$TotalScannedPlaytime      = 0;
		$TotalScannedBitrate       = 0;
		$FilesWithWarnings         = 0;
		$FilesWithErrors           = 0;

		while ($file = readdir($handle)) {
			set_time_limit(30); // allocate another 30 seconds to process this file - should go much quicker than this unless intense processing (like bitrate histogram analysis) is enabled
			//flush();  // make sure the dot is shown, otherwise it's useless
			$currentfilename = $listdirectory.'/'.$file;

			switch ($file) {
				case '..':
					$ParentDir = realpath($file.'/..').'/';
					if (GETID3_OS_ISWINDOWS) {
						$ParentDir = str_replace('\\', '/', $ParentDir);
					}
					$DirectoryContents[$currentfulldir]['dir'][$file]['filename'] = $ParentDir;
					continue 2;
					break;

				case '.':
					// ignore
					continue 2;
					break;
			}

			// symbolic-link-resolution enhancements by davidbullockØtech-center*com
			$TargetObject     = realpath($currentfilename);  // Find actual file path, resolve if it's a symbolic link
			$TargetObjectType = filetype($TargetObject);     // Check file type without examining extension

			if ($TargetObjectType == 'dir') {

				$DirectoryContents[$currentfulldir]['dir'][$file]['filename'] = $file;

			} elseif ($TargetObjectType == 'file') {

				$getID3->option_md5_data = isset($_REQUEST['ShowMD5']);
				$fileinformation = $getID3->analyze($currentfilename);

				getid3_lib::CopyTagsToComments($fileinformation);

				$TotalScannedFilesize += @$fileinformation['filesize'];

				if (isset($_REQUEST['ShowMD5'])) {
					$fileinformation['md5_file'] = md5($currentfilename);
					$fileinformation['md5_file']  = getid3_lib::md5_file($currentfilename);
				}

				if (!empty($fileinformation['fileformat'])) {
					$DirectoryContents[$currentfulldir]['known'][$file] = $fileinformation;
					$TotalScannedPlaytime += @$fileinformation['playtime_seconds'];
					$TotalScannedBitrate  += @$fileinformation['bitrate'];
					$TotalScannedKnownFiles++;
				} else {
					$DirectoryContents[$currentfulldir]['other'][$file] = $fileinformation;
					$DirectoryContents[$currentfulldir]['other'][$file]['playtime_string'] = '-';
					$TotalScannedUnknownFiles++;
				}
				if (isset($fileinformation['playtime_seconds']) && ($fileinformation['playtime_seconds'] > 0)) {
					$TotalScannedPlaytimeFiles++;
				}
				if (isset($fileinformation['bitrate']) && ($fileinformation['bitrate'] > 0)) {
					$TotalScannedBitrateFiles++;
				}
			}
		}
		closedir($handle);

		$columnsintable = 14;
		$asetup .=  '<TABLE class="normal">';
		$rowcounter = 0;
		foreach ($DirectoryContents as $dirname => $val) {
			
			$asetup .=  '<tr>';
			$asetup .=  '<td class="heading" >Filename</td>';
			$asetup .=  '<td class="heading" >File Size</td>';
			$asetup .=  '<td class="heading" >Format</td>';
			$asetup .=  '<td class="heading" >Playtime</td>';
			$asetup .=  '<td class="heading" >Bitrate</td>';
			$asetup .=  '<td class="heading" >Artist</td>';
			$asetup .=  '<td class="heading" >Title</td>';
			$asetup .=  '</tr>';
			if (isset($DirectoryContents[$dirname]['known']) && is_array($DirectoryContents[$dirname]['known'])) {
				uksort($DirectoryContents[$dirname]['known'], 'MoreNaturalSort');
				foreach ($DirectoryContents[$dirname]['known'] as $filename => $fileinfo) {
					$asetup .=  '<tr>';
					$asetup .=  '<td '.(($rowcounter++ % 2) ? 'class="odd"' : 'class="even"').'><a class="wiki" href="'.$URLFolder.$filename.'" TITLE="download">'.FixTextFields(getid3_lib::SafeStripSlashes($filename)).'</a></td>';
					$asetup .=  '<td '.(($rowcounter % 2) ? 'class="even"' : 'class="odd"').' style="text-align:right">'.number_format($fileinfo['filesize']).'</td>';
					$asetup .=  '<td '.(($rowcounter % 2) ? 'class="even"' : 'class="odd"').' style="text-align:right">'.NiceDisplayFiletypeFormat($fileinfo).'</td>';
					$asetup .=  '<td '.(($rowcounter % 2) ? 'class="even"' : 'class="odd"').' style="text-align:right">'.(isset($fileinfo['playtime_string']) ? $fileinfo['playtime_string'] : '-').'</td>';
					$asetup .=  '<td '.(($rowcounter % 2) ? 'class="even"' : 'class="odd"').' style="text-align:right">'.(isset($fileinfo['bitrate']) ? BitrateText($fileinfo['bitrate'] / 1000, 0, ((@$fileinfo['audio']['bitrate_mode'] == 'vbr') ? true : false)) : '-').'</td>';
					$asetup .=  '<td '.(($rowcounter % 2) ? 'class="even"' : 'class="odd"').' align="left">'.(isset($fileinfo['comments_html']['artist']) ? implode('<BR>', $fileinfo['comments_html']['artist']) : '').'</td>';
					$asetup .=  '<td '.(($rowcounter % 2) ? 'class="even"' : 'class="odd"').' align="left">'.(isset($fileinfo['comments_html']['title']) ? implode('<BR>', $fileinfo['comments_html']['title']) : '').'</td>';
					$asetup .=  '</tr>';
				}
			}   
			
		}
		$asetup .=  '</TABLE>';
	} else {
		$asetup .=  '<b>ERROR: Could not open directory: <U>'.$currentfulldir.'</U></b><BR>';
	}
//$asetup .= '<br>debug:<br>'.$debug.'<br>';
	}
return $asetup;
}

function RemoveAccents($string) {
	// return strtr($string, 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');
	// Revised version by markstewardØhotmail*com
	return strtr(strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'), array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u'));
}

function BitrateColor($bitrate, $BitrateMaxScale=768) {
	// $BitrateMaxScale is bitrate of maximum-quality color (bright green)
	// below this is gradient, above is solid green

	$bitrate *= (256 / $BitrateMaxScale); // scale from 1-[768]kbps to 1-256
	$bitrate = round(min(max($bitrate, 1), 256));
	$bitrate--;    // scale from 1-256kbps to 0-255kbps

	$Rcomponent = max(255 - ($bitrate * 2), 0);
	$Gcomponent = max(($bitrate * 2) - 255, 0);
	if ($bitrate > 127) {
		$Bcomponent = max((255 - $bitrate) * 2, 0);
	} else {
		$Bcomponent = max($bitrate * 2, 0);
	}
	return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT);
}

function BitrateText($bitrate, $decimals=0, $vbr=false) {
	return number_format($bitrate, $decimals).' kbps';
}

function FixTextFields($text) {
	$text = getid3_lib::SafeStripSlashes($text);
	$text = htmlentities($text, ENT_QUOTES);
	return $text;
}


function string_var_dump($variable) {
	ob_start();
	var_dump($variable);
	$dumpedvariable = ob_get_contents();
	ob_end_clean();
	return $dumpedvariable;
}


function table_var_dump($variable) {
	$returnstring = '';
	switch (gettype($variable)) {
		case 'array':
			$returnstring .= '<TABLE BORDER="1" CELLSPACING="0" CELLPADDING="2">';
			foreach ($variable as $key => $value) {
				$returnstring .= '<TR><td VALIGN="TOP"><b>'.str_replace("\x00", ' ', $key).'</b></td>';
				$returnstring .= '<td VALIGN="TOP">'.gettype($value);
				if (is_array($value)) {
					$returnstring .= '&nbsp;('.count($value).')';
				} elseif (is_string($value)) {
					$returnstring .= '&nbsp;('.strlen($value).')';
				}
				if (($key == 'data') && isset($variable['image_mime']) && isset($variable['dataoffset'])) {
					$imagechunkcheck = getid3_lib::GetDataImageSize($value);
					$DumpedImageSRC = (!empty($_REQUEST['filename']) ? $_REQUEST['filename'] : '.getid3').'.'.$variable['dataoffset'].'.'.getid3_lib::ImageTypesLookup($imagechunkcheck[2]);
					if ($tempimagefile = fopen($DumpedImageSRC, 'wb')) {
						fwrite($tempimagefile, $value);
						fclose($tempimagefile);
					}
					$returnstring .= '</td><td><IMG SRC="'.$DumpedImageSRC.'" WIDTH="'.$imagechunkcheck[0].'" HEIGHT="'.$imagechunkcheck[1].'"></td></tr>';
				} else {
					$returnstring .= '</td><td>'.table_var_dump($value).'</td></tr>';
				}
			}
			$returnstring .= '</TABLE>';
			break;

		case 'boolean':
			$returnstring .= ($variable ? 'TRUE' : 'FALSE');
			break;

		case 'integer':
		case 'double':
		case 'float':
			$returnstring .= $variable;
			break;

		case 'object':
		case 'null':
			$returnstring .= string_var_dump($variable);
			break;

		case 'string':
			$variable = str_replace("\x00", ' ', $variable);
			$varlen = strlen($variable);
			for ($i = 0; $i < $varlen; $i++) {
				if (ereg('['."\x0A\x0D".' -;0-9A-Za-z]', $variable{$i})) {
					$returnstring .= $variable{$i};
				} else {
					$returnstring .= '&#'.str_pad(ord($variable{$i}), 3, '0', STR_PAD_LEFT).';';
				}
			}
			$returnstring = nl2br($returnstring);
			break;

		default:
			$imagechunkcheck = getid3_lib::GetDataImageSize($variable);
			if (($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) {
				$returnstring .= '<TABLE BORDER="1" CELLSPACING="0" CELLPADDING="2">';
				$returnstring .= '<TR><td><b>type</b></td><td>'.getid3_lib::ImageTypesLookup($imagechunkcheck[2]).'</td></tr>';
				$returnstring .= '<TR><td><b>width</b></td><td>'.number_format($imagechunkcheck[0]).' px</td></tr>';
				$returnstring .= '<TR><td><b>height</b></td><td>'.number_format($imagechunkcheck[1]).' px</td></tr>';
				$returnstring .= '<TR><td><b>size</b></td><td>'.number_format(strlen($variable)).' bytes</td></tr></TABLE>';
			} else {
				$returnstring .= nl2br(htmlspecialchars(str_replace("\x00", ' ', $variable)));
			}
			break;
	}
	return $returnstring;
}


function NiceDisplayFiletypeFormat(&$fileinfo) {

	if (empty($fileinfo['fileformat'])) {
		return '-';
	}

	$output  = $fileinfo['fileformat'];
	if (empty($fileinfo['video']['dataformat']) && empty($fileinfo['audio']['dataformat'])) {
		return $output;  // 'gif'
	}
	if (empty($fileinfo['video']['dataformat']) && !empty($fileinfo['audio']['dataformat'])) {
		if ($fileinfo['fileformat'] == $fileinfo['audio']['dataformat']) {
			return $output; // 'mp3'
		}
		$output .= '.'.$fileinfo['audio']['dataformat']; // 'ogg.flac'
		return $output;
	}
	if (!empty($fileinfo['video']['dataformat']) && empty($fileinfo['audio']['dataformat'])) {
		if ($fileinfo['fileformat'] == $fileinfo['video']['dataformat']) {
			return $output; // 'mpeg'
		}
		$output .= '.'.$fileinfo['video']['dataformat']; // 'riff.avi'
		return $output;
	}
	if ($fileinfo['video']['dataformat'] == $fileinfo['audio']['dataformat']) {
		if ($fileinfo['fileformat'] == $fileinfo['video']['dataformat']) {
			return $output; // 'real'
		}
		$output .= '.'.$fileinfo['video']['dataformat']; // any examples?
		return $output;
	}
	$output .= '.'.$fileinfo['video']['dataformat'];
	$output .= '.'.$fileinfo['audio']['dataformat']; // asf.wmv.wma
	return $output;

}

/* not needed Allan Hansen
function ListOfAssumeFormatExtensions() {
	// These values should almost never get used - the only use for them
	// is to possibly help getID3() correctly identify a file that has
	// garbage data at the beginning of the file, but a correct filename
	// extension.

	//$AssumeFormatExtensions[<filename extension>]  = <file format>;

	$AssumeFormatExtensions['aac']  = 'aac';
	$AssumeFormatExtensions['iff']  = 'aiff';
	$AssumeFormatExtensions['aif']  = 'aiff';
	$AssumeFormatExtensions['aifc'] = 'aiff';
	$AssumeFormatExtensions['iff']  = 'aiff';
	$AssumeFormatExtensions['aiff'] = 'aiff';
	$AssumeFormatExtensions['wmv']  = 'asf';
	$AssumeFormatExtensions['wma']  = 'asf';
	$AssumeFormatExtensions['asf']  = 'asf';
	$AssumeFormatExtensions['au']   = 'au';
	$AssumeFormatExtensions['bmp']  = 'bmp';
	$AssumeFormatExtensions['mod']  = 'bonk';
	$AssumeFormatExtensions['bonk'] = 'bonk';
	$AssumeFormatExtensions['flac'] = 'flac';
	$AssumeFormatExtensions['gif']  = 'gif';
	$AssumeFormatExtensions['iso']  = 'iso';
	$AssumeFormatExtensions['jpeg'] = 'jpg';
	$AssumeFormatExtensions['jpg']  = 'jpg';
	$AssumeFormatExtensions['la']   = 'la';
	$AssumeFormatExtensions['pac']  = 'lpac';
	$AssumeFormatExtensions['mac']  = 'mac';
	$AssumeFormatExtensions['ape']  = 'mac';
	$AssumeFormatExtensions['mid']  = 'midi';
	$AssumeFormatExtensions['midi'] = 'midi';
	$AssumeFormatExtensions['mid']  = 'midi';
	$AssumeFormatExtensions['xm']   = 'mod';
	$AssumeFormatExtensions['it']   = 'mod';
	$AssumeFormatExtensions['s3m']  = 'mod';
	$AssumeFormatExtensions['mp3']  = 'mp3';
	$AssumeFormatExtensions['mp2']  = 'mp3';
	$AssumeFormatExtensions['mp1']  = 'mp3';
	$AssumeFormatExtensions['mpc']  = 'mpc';
	$AssumeFormatExtensions['mpg']  = 'mpeg';
	$AssumeFormatExtensions['mpeg'] = 'mpeg';
	$AssumeFormatExtensions['nsv']  = 'nsv';
	$AssumeFormatExtensions['ofr']  = 'ofr';
	$AssumeFormatExtensions['spx']  = 'ogg';
	$AssumeFormatExtensions['ogg']  = 'ogg';
	$AssumeFormatExtensions['png']  = 'png';
	$AssumeFormatExtensions['mov']  = 'quicktime';
	$AssumeFormatExtensions['qt']   = 'quicktime';
	$AssumeFormatExtensions['rar']  = 'rar';
	$AssumeFormatExtensions['ra']   = 'real';
	$AssumeFormatExtensions['ram']  = 'real';
	$AssumeFormatExtensions['rm']   = 'real';
	$AssumeFormatExtensions['wav']  = 'riff';
	$AssumeFormatExtensions['wv']   = 'riff';
	$AssumeFormatExtensions['vox']  = 'riff';
	$AssumeFormatExtensions['cda']  = 'riff';
	$AssumeFormatExtensions['xvid'] = 'riff';
	$AssumeFormatExtensions['avi']  = 'riff';
	$AssumeFormatExtensions['divx'] = 'riff';
	$AssumeFormatExtensions['avi']  = 'riff';
	$AssumeFormatExtensions['wav']  = 'riff';
	$AssumeFormatExtensions['rka']  = 'rkau';
	$AssumeFormatExtensions['swf']  = 'swf';
	$AssumeFormatExtensions['sz']   = 'szip';
	$AssumeFormatExtensions['voc']  = 'voc';
	$AssumeFormatExtensions['vqf']  = 'vqf';
	$AssumeFormatExtensions['zip']  = 'zip';

	return $AssumeFormatExtensions;
}
*/


function MoreNaturalSort($ar1, $ar2) {
	if ($ar1 === $ar2) {
		return 0;
	}
	$len1     = strlen($ar1);
	$len2     = strlen($ar2);
	$shortest = min($len1, $len2);
	if (substr($ar1, 0, $shortest) === substr($ar2, 0, $shortest)) {
		// the shorter argument is the beginning of the longer one, like "str" and "string"
		if ($len1 < $len2) {
			return -1;
		} elseif ($len1 > $len2) {
			return 1;
		}
		return 0;
	}
	$ar1 = RemoveAccents(strtolower(trim($ar1)));
	$ar2 = RemoveAccents(strtolower(trim($ar2)));
	$translatearray = array('\''=>'', '"'=>'', '_'=>' ', '('=>'', ')'=>'', '-'=>' ', '  '=>' ', '.'=>'', ','=>'');
	foreach ($translatearray as $key => $val) {
		$ar1 = str_replace($key, $val, $ar1);
		$ar2 = str_replace($key, $val, $ar2);
	}

	if ($ar1 < $ar2) {
		return -1;
	} elseif ($ar1 > $ar2) {
		return 1;
	}
	return 0;
}

function PoweredBygetID3($string='<BR><HR NOSHADE><DIV STYLE="font-size: 8pt; font-face: sans-serif;">Powered by <a href="http://getid3.sourceforge.net" TARGET="_blank"><b>getID3() v<!--GETID3VER--></b><BR>http://getid3.sourceforge.net</a></DIV>') {
	return str_replace('<!--GETID3VER-->', GETID3_VERSION, $string);
}
?>