<?php

/* This library of functions helps the /extra file mananger */

function extra_delete_file($inode) {
	$file = extra_file_from_inode($inode);
	return unlink($file->fullpath);
}

function extra_sort_file_objects($a, $b) {
	$an = strtolower($a->name);
	$bn = strtolower($b->name);
	if( $an == $bn ) return 0;
	return ( $an < $bn ) ? -1 : 1;
}

function extra_handle_upload() {
	global $info,$error,$dir;
	
	if( !$_FILES['extra_file'] ) return false;
	
	if( '' == $_FILES['extra_file']['name'] ) return false;
	if( UPLOAD_ERR_NO_FILE == $_FILES['extra_file']['error'] ) return false;
	if( 0 == $_FILES['extra_file']['size'] ) return false;

	$dest = $_FILES['extra_file']['name'];

	if(isset( $_POST['name'] )) $dest = $_POST['name'];
	$dest = extra_sanitize_filename($dest);
	
	if( !is_uploaded_file( $_FILES['extra_file']['tmp_name'] )) return false;
	if( move_uploaded_file($_FILES['extra_file']['tmp_name'], $dir.'/'.$dest) ) return $true;
	
	return false;
}

function extra_file_from_inode($inode) {
	global $dir;
	$files = extra_get_directory_list($dir);
	foreach($files as $f) {
		if( $f->inode == $inode ) return $f;
	}
	return false;
}

function extra_sanitize_filename( $raw_filename ) {
	$filename = str_replace('/', '');
	if( $filename !== $raw_filename) return false;
}

function extra_get_directory_list($dir) {
	if( !is_dir( $dir ) ) return false;
	if( ! $handle = opendir( $dir ) ) return false;
	
	$files = array();
	
	class ExtraFile {
		var $name;
		var $rwx;
		var $mtime;
		var $inode;
		
		function ExtraFile($path, $file) {
			$this->name = $file;
			$this->fullpath = $path . $file;
			$this->rwx = is_readable($this->fullpath) ? 'r' : '-';
			$this->rwx.= is_writable($this->fullpath) ? 'w' : '-';
			$this->rwx.= is_executable($this->fullpath) ? 'x' : '-';
			$this->mtime = filemtime($this->fullpath);
			$this->inode = fileinode($this->fullpath);
		}
		
	}
	
	while (false !== ($file = readdir($handle))) {
		if( is_file( $dir.'/'.$file )) $files[] = new ExtraFile($dir.'/', $file);
	}

	return $files;	
}

?>