File "index.php"

Full Path: /home/analogde/www/Administratif/FTP/Code03/index.php
File size: 19.65 KB
MIME-type: text/x-php
Charset: utf-8

<?php
//
// $Id: index.php,v1.0 2004-12-18 1:29a EST Onion Exp $
//

//
// Might not be a good idea to show people how slow this thing is, but eh.
//
define ('START', microtime (1));

//
// Basic Things
//
error_reporting   (E_ALL | E_STRICT);
set_time_limit    (0);
ignore_user_abort (0);
ini_set           ('default_socket_timeout', 1); // this might need to be changed for slow connections with FTP servers; but it must be set lest we have a script that never times out.

//
// Session Stuff
//
session_name          ('s');
session_cache_limiter ('private, must-revalidate');
session_start         ();

/*
 * $_HOSTS variable
 *
 * Set this variable if you want to limit the number of sites FTPhp Manager can access.
 *
 * Example:
 *
 * $_HOSTS = array ('ftp.example.com', 'localhost');
 */
$_HOSTS = array ();

//
// Mime Types
//
$_MIME = array ();
foreach (file ('./inc/mime.types') as $line) {
 if ($line{0} != '#') {
  $bits = preg_split ('#\s+#', $line);
  $k = trim (array_shift ($bits));
  $v = rtrim (trim (implode ('|', $bits)), '|');
  $v ? $_MIME[$k] = $v : '';
 }
}

//
// Functions
//
/*
 * __autoload ()
 *
 * http://jp2.php.net/manual/en/language.oop5.autoload.php
 *
 * void __autoload ( string class )
 */
function __autoload ( $class ) {
 require_once ('./inc/class.'.strtolower ($class).'.inc');
}

/*
 * _usort_abc_archetype ()
 *
 * Just shortening the code a bit (although I'm making up for it in comments >_>)
 *
 * int _usort_abc_archetype ( string a, string b, int order )
 */
function _usort_abc_archetype ( $a, $b, $order = 1 ) {
 static $abc123 = '0123456789abcdefghijklmnopqrstuvwxyz';
 if (is_numeric ($a) && is_numeric ($b)) {
  return $a == $b ? 0 : ($a < $b ? -1 : 1);
 }
 return ($a == $b ? 0 : (!stristr ($abc123, $a{0}) || !stristr ($abc123, $b{0}) || stripos ($abc123, $a{0}) < stripos ($abc123, $b{0}) ? $order*-1 : $order*1));
}

/*
 * _usort_abc ()
 *
 * Callback that sorts things in alphabetical order.
 *
 * int _usort_abc ( string a, string b )
 */
function _usort_abc ( $a, $b ) {
 return _usort_abc_archetype ($a, $b, 1);
}

/*
 * _usort_zyx ()
 *
 * Callback that sorts things in reverse-alphabetical order.
 *
 * int _usort_zyx ( string a, string b )
 */
function _usort_zyx ( $a, $b ) {
 return _usort_abc_archetype ($a, $b, -1);
}

/*
 * _array_walk_trim ()
 *
 * Callback that trim()s things.
 *
 * void _array_walk_trim ( mixed &v, mixed &k )
 */
function _array_walk_trim ( &$v, &$k ) {
 if (is_array ($v)) {
  array_walk ($v, '_array_walk_trim');
 } else {
  $v = trim ($v);
 }
}

/*
 * get_type_by_permissions ()
 *
 * Returns whether an item is a directory, link, or file. If it's a file, it can optionally return the mime type of that file.
 *
 * mixed get_type_by_permissions ( string perm_str [, string file_ext ] )
 */
function get_type_by_permissions ( $perm_str, $file_ext = false ) {
 switch ($perm_str{0}) {
  case 'd':
   return 'directory';
  case 'l':
   return 'link';
  case '-':
   if ($file_ext && $type = get_type_by_extension ($file_ext)) {
    return substr ($type, 0, strpos ($type, '/'));
   }
   return 'file';
 }
 return false;
}

/*
 * get_type_by_extension ()
 *
 * Returns the mime type of a file based on its extension.
 *
 * mixed get_type_by_extension ( string file_ext )
 */
function get_type_by_extension ( $file_ext ) {
 global $_MIME;
 foreach ($_MIME as $type => $ext) {
  if ($ext && preg_match ('#'.$ext.'#i', $file_ext)) {
   return $type;
  }
 }
 return false;
}

/*
 * format_bytes ()
 *
 * Turns '1024' into '1 KB'.
 *
 * string format_bytes ( int bytes )
 */
function format_bytes ( $bytes ) {
 if ($bytes >= 1099511627776) {
  $bytes = round ($bytes/1099511627776, 2);
  $type  = 'TB';
 } elseif ($bytes >= 1073741824) {
  $bytes = round ($bytes/1073741824, 2);
  $type  = 'GB';
 } elseif ($bytes >= 1048576) {
  $bytes = round ($bytes/1048576, 2);
  $type  = 'MB';
 } elseif ($bytes >= 1024) {
  $bytes = round ($bytes/1024, 2);
  $type  = 'KB';
 } elseif ($bytes < 1024) {
  $type = 'B';
 }
 return $bytes . ' ' . $type;
}

/*
 * shade ()
 *
 * Alernating coloured cells plz.
 *
 * string shade ( void )
 */
function shade ( ) {
 static $i;
 return ' class="cell'.(((int)(bool)($i++ & 1))+1).'"';
}

/*
 * foot ()
 *
 * Echos a message and stops execution.
 *
 * void foot ( [ string msg ] )
 */
function foot ( $msg = '' ) {
 exit (vsprintf ('%s  <div id="foot">FTPhp Manager v1.0.1 &copy; 2004 <a href="mailto:webmaster(at symbol)script(dash)tease(period)net">Onion</a><br />Script executed in %.3f seconds.</div>%c </body>%c</html>', array ("$msg\n", microtime (1) - START, 10, 10)));
}

//
// Sets Login Info
//
if ((isset ($_POST['host'], $_POST['port'], $_POST['user'], $_POST['pass']) || isset ($_POST['ftp_url'])) && (empty ($_HOSTS) || in_array ($_POST['host'], $_HOSTS))) {
 if ($_POST['ftp_url']) {
  //                protocol    username & password        host address  host port  path
  //                 1            23    4 5                6             7 8        9      
  preg_match_all ('#^(ftp|ftps)://((.+?)(:(.+)){0,1}@){0,1}([a-z0-9-\.]+)(:([\d]+))*(/?.*?)$#i', $_POST['ftp_url'], $matches, PREG_SET_ORDER);
  $_SESSION['user']  = $matches[0][3] ? $matches[0][3] : 'anonymous';
  $_SESSION['pass']  = $matches[0][5] ? $matches[0][5] : 'root@localhost';
  $_SESSION['host']  = $matches[0][6];
  $_SESSION['port']  = $matches[0][8] ? (int) $matches[0][8] : 21;
  $_SESSION['path']  = $matches[0][9] ? $matches[0][9] : null;  
 } else {
  $_SESSION['host'] = $_POST['host'];
  $_SESSION['port'] = $_POST['port'] ? (int) $_POST['port'] : 21;
  $_SESSION['user'] = $_POST['user'] ? $_POST['user']       : 'anonymous';
  $_SESSION['pass'] = $_POST['pass'] ? $_POST['pass']       : 'root@localhost';
  $_SESSION['path'] = null;
 }
}

//
// So that we may have the option of destroying the buffer later.
//
ob_start ();

//
// XHTML 1.1 plz
//
header ('Content-Type: '. (isset ($_SERVER['HTTP_ACCEPT']) && stristr ($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') ? 'application/xhtml+xml' : 'text/html') .'; charset=utf-8');

//
// Start Output
echo '<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>FTPhp Manager</title>
  <link rel="stylesheet" type="text/css" title="default" href="inc/style.css" />
 </head>
 <body>
  <h1>FTPhp Manager</h1>
  <form action="',$_SERVER['PHP_SELF'],'" method="post">
   <table id="topbar">
    <tbody>
     <tr>
      <th>Enter Individual Fields:</th>
      <th><acronym title="The server address to connect to. I.E.: \'ftp.example.com\'">Host:</acronym> ';
if (count ($_HOSTS)) {
 echo '
       <select name="host">',"\n";
 foreach ($_HOSTS as $host) {
  echo '        <option value="',$host,'">',$host,'</option>',"\n";
 }
 echo '       </select>',"\n",'      ';
} else {
 echo '<input type="text" size="25" name="host" value="',isset ($_SESSION['host']) ? $_SESSION['host'] : '','" />';
}
echo '</th>
      <th><acronym title="Port to connect to the server on. Usually 21.">Port:</acronym> <input type="text" size="5" name="port" value="',isset ($_SESSION['port']) ? $_SESSION['port'] : '21','" /></th>
      <th><acronym title="User to log into the server as. If you don\'t usually need a username, try \'anonymous\'.">User:</acronym> <input type="text" size="25" name="user" value="',isset ($_SESSION['user']) ? $_SESSION['user'] : '','" /></th>
      <th><acronym title="Password to log into the server with. If you don\'t usually need a password, try using an e-mail address.">Password:</acronym> <input type="password" size="25" name="pass" value="',isset ($_SESSION['pass']) ? $_SESSION['pass'] : '','" /></th>
      <th><input type="submit" value="Connect" /></th>
     </tr>
     <tr>
      <th>Or Enter All or Part of an FTP URL:</th>
      <th colspan="4"><acronym title="Something like \'ftp://user:pass@ftp.example.com:21/directory/myfile.txt\'">URL:</acronym> <input type="text" size="50" name="ftp_url" value="" /></th>
      <th><input type="submit" value="Connect" /></th>
     </tr>
    </tbody>
   </table>
  </form>',"\n";

//
// Create FTPhp Object or die
//
if (isset ($_SESSION['host'], $_SESSION['port'], $_SESSION['user'], $_SESSION['pass'])) {
 $ftphp = new FTPhp ($_SESSION['host'], $_SESSION['port'], $_SESSION['user'], $_SESSION['pass']);
} else {
 foot ();
}

//
// Simple Actions
//
isset ($_GET['delete']) && $ftphp->perform_action ('dele', array ($_GET['delete']));
isset ($_GET['rmd'])    && $ftphp->perform_action ('rmd', array ($_GET['rmd']));
isset ($_GET['path'])   && $ftphp->perform_action ('cwd', array ($_GET['path']));
isset ($_GET['mkdir'])  && $ftphp->perform_action ('mkd', array ($_GET['mkdir']));

isset ($_POST['rename_from'], $_POST['rename_to']) && $ftphp->perform_action ('rename', array ($_POST['rename_from'], $_POST['rename_to']));
isset ($_POST['chmod_file'], $_POST['chmod_value']) && $ftphp->perform_action ('site', array ('EXEC CHMOD 0'.(int) $_POST['chmod_value'].' '.$_POST['chmod_file']));

//
// File Downloads
//
isset ($_GET['download']) && $ftphp->download ($_GET['download']);

//
// File Uploads
//
if (isset ($_POST['upload'])  && !empty ($_FILES)) {
 $i = 0;
 foreach ($_FILES as $file) {
  if ($i++ == 3) {
   break;
  }
  if ($file['error'] != 0) {
   continue;
  }
  $ftphp->upload ($file['tmp_name'], $file['name']);
 }
}

//
// Retrieve File Listing
//
$sorted_list = $ftphp->file_list ();
array_walk (&$sorted_list, '_array_walk_trim');
reset ($sorted_list);

//
// Sort File Listing
//
switch (isset ($_GET['sort']) && isset ($sorted_list[$_GET['sort']]) ? $_GET['sort'] : 'filename') {
 default: 
 case 'filename':      $index = $sort = 'filename';      break;
 case 'filesize':      $index = $sort = 'filesize';      break;
 case 'last_modified': $index = $sort = 'last_modified'; break;
 case 'permissions':   $index = $sort = 'permissions';   break;
 case 'owner':         $index = $sort = 'owner';         break;
 case 'group':         $index = $sort = 'group';         break;
}
switch (isset ($_GET['order']) ? $_GET['order'] : 'asc') {
 default:
 case 'asc':
  uasort ($sorted_list[$index], '_usort_abc');
  $order  = 'asc';
  $rorder = 'desc';
  break;
 case 'desc':
  uasort ($sorted_list[$index], '_usort_zyx');
  $order  = 'desc';
  $rorder = 'asc';
  break;
}

//
// Querystring Bits
//
$querystring          = array();
$querystring['path']  = 'path='.urlencode ($ftphp->current_directory);
$querystring['sort']  = 'sort='.($sort);
$querystring['order'] = 'order='.($order);
$querystring[0]       = '?'.implode ('&amp;', $querystring);
$querystring[1]       = '&amp;'.substr ($querystring[0], 1);

//
// Rename Form
//
if (isset ($_GET['rename']) && in_array (substr ($_GET['rename'], strlen ($ftphp->current_directory)), $sorted_list['filename'])) {
 echo '  <form action="',$_SERVER['PHP_SELF'],$querystring[0],'" method="post">
   <table id="main">
    <thead>
     <tr>
      <th>Rename &quot;',htmlentities ($_GET['rename']),'&quot;</th>
     </tr>
    </thead>
    <tbody>
     <tr>
      <td',shade (),'>Rename To: <input type="hidden" name="rename_from" value="',htmlentities ($_GET['rename']),'" /><input type="text" size="50" name="rename_to" value="',htmlentities ($_GET['rename']),'" /> <input type="submit" value="Go -&gt;" /></td>
     </tr>
    </tbody>
   </table>
  </form>',"\n";
 foot ();
}

//
// Change Permissions
//
if (isset ($_GET['permissions'], $sorted_list['permissions']) && in_array (substr ($_GET['permissions'], strlen ($ftphp->current_directory)), $sorted_list['filename'])) {
 echo '  <script type="text/javascript" src="inc/permissions.js"></script>
  <form action="',$_SERVER['PHP_SELF'],$querystring[0],'" method="post">
   <table id="main">
    <thead>
     <tr>
      <th colspan="4">Change Permissions for &quot;',$_GET['permissions'],'&quot;</th>
     </tr>
     <tr>
      <th colspan="4" class="error">Note that this page requires javascript to be enabled<!--[if IE]> and that it\'s kind of screwed up in IE<![end if]-->.</th>
     </tr>
    </thead>
    <tbody>
     <tr',shade (),'>
      <td>owner</td>
      <td><input type="checkbox" id="own_r" onchange="update_octal ();" /><label for="own_r">read</label></td>
      <td><input type="checkbox" id="own_w" onchange="update_octal ();" /><label for="own_w">write</label></td>
      <td><input type="checkbox" id="own_x" onchange="update_octal ();" /><label for="own_x">execute</label></td>
     </tr>
     <tr',shade (),'>
      <td>group</td>
      <td><input type="checkbox" id="grp_r" onchange="update_octal ();" /><label for="grp_r">read</label></td>
      <td><input type="checkbox" id="grp_w" onchange="update_octal ();" /><label for="grp_w">write</label></td>
      <td><input type="checkbox" id="grp_x" onchange="update_octal ();" /><label for="grp_x">execute</label></td>
     </tr>
     <tr',shade (),'>
      <td>public</td>
      <td><input type="checkbox" id="pub_r" onchange="update_octal ();" /><label for="pub_r">read</label></td>
      <td><input type="checkbox" id="pub_w" onchange="update_octal ();" /><label for="pub_w">write</label></td>
      <td><input type="checkbox" id="pub_x" onchange="update_octal ();" /><label for="pub_x">execute</label></td>
     </tr>
     <tr>
      <td colspan="4">Octal Value: <input type="hidden" name="chmod_file" value="',htmlentities ($_GET['permissions']),'" /><input type="text" name="chmod_value" id="octal" onchange="update_checkboxes ();" value="" /> <input type="submit" value="Change -&gt;" /></td>
     </tr>
    </tbody>
   </table>
  </form>
  <script type="text/javascript">
   // <![CDATA[
   set_vars (\'',$sorted_list['permissions'][array_search (substr ($_GET['permissions'], strlen ($ftphp->current_directory)), $sorted_list['filename'])],'\');
   update_checkboxes ();
   update_octal ();
   // ]]>
  </script>',"\n";
 foot ();
}
        
//
// More Output
//
$colspan = count ($sorted_list) + 2;
echo '  <table id="main">
   <thead>
    <tr>
     <th colspan="',floor ($colspan/2),'">Current Working Directory:</th>
     <th colspan="',ceil ($colspan/2),'">
      <form action="',$_SERVER['PHP_SELF'],'?',$querystring['sort'],'&amp;',$querystring['order'],'" method="get">
       <div>
        <input type="text" size="50" name="path" value="',$ftphp->current_directory,'" />
        <input type="submit" value="Go -&gt;" />
       </div>
      </form>
     </th>
    </tr>
   </thead>
   <tfoot>
    <tr>
     <th colspan="',floor ($colspan/2),'">Create New Directory:</th>
     <td colspan="',ceil ($colspan/2),'"',shade (),'>
      <form action="',$_SERVER['PHP_SELF'], $querystring[0],'" method="post">
       <div>
        <input type="text" size="50" name="mkdir" value="" />
        <input type="submit" value="Make Directory" />
       </div>
      </form>
     </td>
    </tr>
    <tr>
     <th colspan="',floor ($colspan/2),'">Upload Files:</th>
     <td colspan="',ceil ($colspan/2),'"',shade (),'>
      <form action="',$_SERVER['PHP_SELF'], $querystring[0],'" method="post" enctype="multipart/form-data">
       <div>
        <input type="hidden" name="MAX_FILE_SIZE" value="1073741824" />
        <input type="file" name="upload_1" size="30" value="" /><br />
        <input type="file" name="upload_2" size="30" value="" /><br />
        <input type="file" name="upload_3" size="30" value="" /><br />
        <input type="submit" name="upload" value="Upload Files" />
       </div>
      </form>
     </td>
    </tr>
   </tfoot>
   <tbody>
    <tr>
     <th colspan="2"><a href="',$_SERVER['PHP_SELF'],'?sort=filename&amp;order=',$sort == 'filename' ? $rorder : 'asc', '&amp;', $querystring['path'],'">Filename</a></th>', isset ($sorted_list['filesize']) ? '
     <th><a href="'.$_SERVER['PHP_SELF'].'?sort=filesize&amp;order='. ($sort == 'filesize' ? $rorder : 'asc') . '&amp;' . $querystring['path'].'">Filesize</a></th>' : '', isset ($sorted_list['last_modified']) ? '
     <th><a href="'.$_SERVER['PHP_SELF'].'?sort=last_modified&amp;order='. ($sort == 'last_modified' ? $rorder : 'asc') . '&amp;' . $querystring['path'].'">Last Modified</a></th>' : '', isset ($sorted_list['permissions']) ? '
     <th><a href="'.$_SERVER['PHP_SELF'].'?sort=permissions&amp;order='. ($sort == 'permissions' ? $rorder : 'asc') . '&amp;' . $querystring['path'].'">Permissions</a></th>' : '', isset ($sorted_list['owner']) ? '
     <th><a href="'.$_SERVER['PHP_SELF'].'?sort=owner&amp;order='. ($sort == 'owner' ? $rorder : 'asc') . '&amp;' . $querystring['path'].'">Owner</a></th>' : '', isset ($sorted_list['group']) ? '
     <th><a href="'.$_SERVER['PHP_SELF'].'?sort=group&amp;order='. ($sort == 'group' ? $rorder : 'asc') . '&amp;' . $querystring['path'].'">Group</a></th>' : '', '
     <th>Options</th>
    </tr>',$ftphp->current_directory != '/' ? '
    <tr>
     <td>..</td>
     <td colspan="6"><a href="'.$_SERVER['PHP_SELF'].'?path='.$ftphp->current_directory.urlencode ('/..').'&amp;'.$querystring['sort'].'&amp;'.$querystring['order'].'">Up One Directory</a></td>
    </tr>' : '',"\n";

//
// Echo File Listing
//
foreach (array_keys ($sorted_list[$index]) as $key) {
 $dots = explode ('.', $sorted_list['filename'][$key]);
 switch (isset ($sorted_list['permissions']) ? get_type_by_permissions ($sorted_list['permissions'][$key], is_array ($dots) ? end ($dots) : false) : 'unknown') {
  case 'application': $img = 'binary';  break;
  case 'audio':       $img = 'audio';   break;
  case 'image':       $img = 'image';   break;
  case 'text':        $img = 'text';    break;
  case 'video':       $img = 'movie';   break;
  case 'directory':
  case 'link'     :   $img = 'menu';    break;
  case 'file':
  default:            $img = 'unknown'; break;
 }
 vprintf ('    <tr%s>
     <td><img src="img/gopher-%s.gif" alt="%s" title="%s" /></td>
     <td><a href="%s?%s=%s">%s</a></td>',
          array (shade (),
                 $img,
                 $img,
                 $img,
                 $_SERVER['PHP_SELF'],
                 isset ($sorted_list['permissions']) && get_type_by_permissions ($sorted_list['permissions'][$key]) == 'file' ? 'download' : 'path',
                 urlencode ($ftphp->current_directory.($ftphp->current_directory == '/' ? '' : '/').$sorted_list['filename'][$key]),
                 htmlentities ($sorted_list['filename'][$key])
                )
          );
 if (isset ($sorted_list['filesize'])) {
  echo "\n", '     <td>', (isset ($sorted_list['permissions']) && get_type_by_permissions ($sorted_list['permissions'][$key]) == 'file') || is_int ($sorted_list['filesize'][$key]) ? format_bytes ($sorted_list['filesize'][$key]) : '---', '</td>';
 }

 if (isset ($sorted_list['last_modified'])) {
  echo "\n", '     <td>', $sorted_list['last_modified'][$key], '</td>';
 }

 if (isset ($sorted_list['permissions'])) {
  echo "\n", '     <td>', $sorted_list['permissions'][$key], '</td>';
 }

 if (isset ($sorted_list['owner'])) {
  echo "\n", '     <td>', $sorted_list['owner'][$key], '</td>';
 }

 if (isset ($sorted_list['group'])) {
  echo "\n", '     <td>', $sorted_list['group'][$key], '</td>';
 }

 $is_dir      = (isset ($sorted_list['permissions']) && get_type_by_permissions ($sorted_list['permissions'][$key]) == 'directory');
 $encoded_url = urlencode ($ftphp->current_directory.($ftphp->current_directory == '/' ? '' : '/').$sorted_list['filename'][$key]);
 vprintf ('     <td>[<a href="%s?%s=%s" title="%s">%s</a>]&nbsp;[<a href="%s?rename=%s%s" title="rename">ren</a>]&nbsp;[<a href="%s?permissions=%s%s" title="change permissions">ch</a>]</td>
    </tr>%c', 
          array ($_SERVER['PHP_SELF'],
                 $is_dir ? 'rmd' : 'delete',
                 $encoded_url,
                 $is_dir ? 'remove directory' : 'delete',
                 $is_dir ? 'rmd' : 'del',
                 $_SERVER['PHP_SELF'],
                 $encoded_url,
                 $querystring[1],
                 $_SERVER['PHP_SELF'],
                 $encoded_url,
                 $querystring[1],
                 10
                )
         );
}

echo '   </tbody>
  </table>';

//
// The End
//
foot ();