Your IP : 216.73.217.64


Current Path : /home3/gp97/docs.sapat20172020.97gp.net/php/
Upload File :
Current File : //home3/gp97/docs.sapat20172020.97gp.net/php/m_docmanager.php

<?php
/* *************************************************
 *
 * Document Manager (C) 2002-2010
 * Version 4 - dmanager MySQL
 * Benjamin Sonntag <benjamin@sonntag.fr>
 * Chantal Bernard-Putz <chantal@bernard-putz.net>
 * Franck Denis
 * This software is protected by copyright laws,
 * please read the file COPYRIGHT
 * This software is provided as is with no warranty.
 *
 ************************************************* */

/* $Id: m_docmanager.php 59 2011-07-22 09:07:30Z benjamin $ */

/**
 * This class manage a Document Manager with user rights and folders
 *
 * Rights can be as follow :
 *	A can Administrate users (full rights)
 * 	W can change its password
 *
 *	R can Read a document
 *	U can Upload a document
 *	D can Delete a document
 *	F can create a Folder
 *	N can change file Names
 *	T can change direcTory names (categories)
 *	M can Move files in folders
 *	C can change Comments on files (Uploaders can set the initial comment)
 *	P can delete a Folder
 *
 */
// we use this global variable to remember the place of the document manager sources :

$dmanagerRootDir = substr(dirname(__FILE__), 0, -3);

class DocManager {

  /** Error messages that may be launched by the class */
  var $errors = array (
		       1  => "Database cannot be opened",
		       2  => "User already exists",
		       3  => "User does not exists",
		       4  => "Password is incorrect",
		       5  => "The new file already exists !",
		       6  => "The file does not exist !",
		       7  => "File or Directory already exists !",
		       8  => "Directory does not exist !",
		       9  => "Cannot delete non-empty directories !",
		       10 => "Password cannot contain the character ':'",
		       11 => "A file with the same name already exists in the destination folder !",
		       12 => "The mail cannot be sent : the mail.txt file doesn't exist !",
		       13 => "This user has already some rights for this folder",
		       14 => "This user has no email, please contact your administrator",
		       15 => "This email is not a registered account, please contact your administrator",
		       16 => "The specified user does not exist",
		       17 => "The mail has not been sent, check your settings",
		       18 => "Cannot rename the file, check your server permissions",
		       19 => "Cannot create the directory, check your server permissions",
		       20 => "Cannot save the file, check your server permissions",
		       0  => "OK",
		       );

  var $error = 0;
  var $root = "";
  var $totalSize = 0;
  var $commenthandle = 0;

  /** Mime type used to allow a proper "view" link in the browser */
  var $a_mime = array (
		       "txt"   => "text/plain",
		       "html"  => "text/html",
		       "css"   => "text/css",
		       "htm"   => "text/html",
		       "doc"   => "application/msword",
		       "dot"   => "application/msword",
		       "xls"   => "application/vnd.ms-excel",
		       "jpg"   => "image/jpeg",
		       "jpeg"  => "image/jpeg",
		       "gif"   => "image/gif",
		       "psd"   => "image/psd",
		       "tif"   => "image/tiff",
		       "tiff"  => "image/tiff",
		       "png"   => "image/png",
		       "pdf"   => "application/pdf",
		       "xcf"   => "image/xcf",
		       "hqx"   => "application/mac-binhex40",
		       "ps"    => "application/postscript",
		       "epf"   => "application/postscript",
		       "ppt"   => "application/powerpoint",
		       "pps"   => "application/powerpoint",
		       "rtf"   => "text/rtf",
		       "zip"   => "application/zip",
		       "mp3"   => "audio/mpeg",
		       "m3u"   => "audio/mpegurl",
		       "csv"   => "text/comma-separated-values",
		       "vcs"   => "text/x-vCalendar",
		       "vcf"   => "text/x-vCard",
		       "php"   => "text/plain",
		       "rar"   => "application/rar",
		       "sxw"   => "application/vnd.sun.xml.writer",
		       "sxi"   => "application/vnd.sun.xml.impress",
		       "sxd"   => "application/vnd.sun.xml.draw",
		       "sxc"   => "application/vnd.sun.xml.calc",
		       "dia"   => "application/x-dia",
		       "odt"   => "application/vnd.oasis.opendocument.text",
		       "ods"   => "application/vnd.oasis.opendocument.spreadsheet",
		       "odp"   => "application/vnd.oasis.opendocument.presentation",
		       "odg"   => "application/vnd.oasis.opendocument.graphics",
		       "odc"   => "application/vnd.oasis.opendocument.chart",
		       "odf"   => "application/vnd.oasis.opendocument.formula",
		       "odb"   => "application/vnd.oasis.opendocument.database",
		       "odi"   => "application/vnd.oasis.opendocument.image",
		       "odm"   => "application/vnd.oasis.opendocument.text-master",
		       "ott"   => "application/vnd.oasis.opendocument.text-template",
		       "ots"   => "application/vnd.oasis.opendocument.spreadsheet-template",
		       "otp"   => "application/vnd.oasis.opendocument.presentation-template",
		       "otg"   => "application/vnd.oasis.opendocument.graphics-template",
		       );

  /** Icon we will show for each mime type */
  var $a_icon = array (
		       "txt"   => "txt",
		       "html"  => "html",
		       "htm"   => "html",
		       "css"   => "css",
		       "doc"   => "doc",
		       "dot"   => "doc",
		       "xls"   => "xls",
		       "jpg"   => "gif",
		       "jpeg"  => "gif",
		       "gif"   => "gif",
		       "psd"   => "gif",
		       "tif"   => "gif",
		       "tiff"  => "gif",
		       "png"   => "gif",
		       "xcf"   => "gif",
		       "pdf"   => "pdf",
		       "hqx"   => "exe",
		       "ps"    => "txt",
		       "epf"   => "txt",
		       "ppt"   => "ppt",
		       "pps"   => "ppt",
		       "rtf"   => "doc",
		       "zip"   => "zip",
		       "mp3"   => "wav",
		       "m3u"   => "wav",
		       "csv"   => "xls",
		       "vcs"   => "vcs",
		       "vcf"   => "vcf",
		       "php"   => "php",
		       "php3"  => "php",
		       "rar"   => "zip",
		       "sxw"   => "sxw",
		       "sxi"   => "sxi",
		       "sxd"   => "sxd",
		       "sxc"   => "sxc",
		       "dia"   => "dia",
		       "exe"   => "exe",
		       "odt"   => "odt",
		       "odp"   => "odp",
		       "odb"   => "odb",
		       "ods"   => "ods",
		       "odf"   => "odf",
		       "odg"   => "odg",
		       "gz"    => "zip",
		       "deb"   => "deb",
		       "rpm"   => "rpm",
		       "mdb"   => "mdb",
		       );

  /** Type in human language for each file extension */
  var $a_type = array (
		       "txt"   => "Text Document",
		       "html"  => "HTML Document",
		       "htm"   => "HTML Document",
		       "css"   => "CSS",
		       "doc"   => "Word Document",
		       "dot"   => "Word Document Template",
		       "xls"   => "Excel Spreadsheet",
		       "jpg"   => "JPEG Image",
		       "jpeg"  => "JPEG Image",
		       "gif"   => "GIF Image",
		       "psd"   => "Photoshop Image",
		       "tif"   => "TIFF Image",
		       "tiff"  => "TIFF Image",
		       "png"   => "PNG Image",
		       "xcf"   => "Gimp Image",
		       "pdf"   => "Acrobat PDF",
		       "hqx"   => "Macintosh Executable",
		       "ps"    => "Postscript Document",
		       "epf"   => "Encapsulated Postscript",
		       "ppt"   => "Powerpoint Slideshow",
		       "pps"   => "Powerpoint Slideshow",
		       "rtf"   => "Rich Text Document",
		       "zip"   => "Zip Compressed Files",
		       "mp3"   => "Music File",
		       "m3u"   => "Music Playlist",
		       "csv"   => "Comma Separated Table",
		       "vcs"   => "Virtual Card",
		       "vcf"   => "Virtual Card",
		       "php"   => "PHP Source",
		       "rar"   => "Rar Compressed Files",
		       "sxw"   => "OpenOffice Writer",
		       "sxi"   => "OpenOffice Presentation",
		       "sxc"   => "OpenOffice Spreadsheet",
		       "sxd"   => "OpenOffice Drawing",
		       "dia"   => "DIA Diagram",
		       "odt"   => "OpenOffice 2 Writer",
		       "odp"   => "OpenOffice 2 Presentation",
		       "ods"   => "OpenOffice 2 Spreadsheet",
		       "odg"   => "OpenOffice 2 Drawing",
		       "deb"   => "Debian Package",
		       );

  var $config;


  /* ------------------------------------------------------------ */
  /** 
   * Constructor 
   **/
  function DocManager()
  {
    global $dmanagerRootDir;
    $this->root = $dmanagerRootDir;
  }


  /* ------------------------------------------------------------ */
  /** 
   * Rights cache for a user 
   **/
  var $rch = array();
  var $rchID = array();

  var $dirListFolders = array();
  var $dirListFoldersName = array();


  /* ------------------------------------------------------------ */
  /** 
   * Tells if a user id_user has the specified right $checkRight (or any rights if empty)
   **/
  function hasRight($id_user, $checkRight, $dir = 0) {
    $checkRight = strtolower($checkRight);

    if (empty($this->rch)) {
      $this->rch = $this->getRights($id_user);
      
      $tmpRightsFolders = $this->getRightsFolders($id_user);
      foreach ($tmpRightsFolders as $id_folder => $path) {
	$tmpFolders = explode(SEP, $path);
	foreach ($tmpFolders as $tmpFolder) {
	  if (!isEmpty($tmpFolder))
	    $this->rchID[$tmpFolder] = $tmpFolder;
	}
      }
    }
    
    if (!isset($this->rch[$dir])) {
      $recursiveRight = $this->getRecursiveRight($dir);
      if (substr($recursiveRight, 0, 1) == SEP)
	$recursiveRight = substr($recursiveRight, 1);
      if (substr($recursiveRight, -1) == SEP)
	$recursiveRight = substr($recursiveRight, 0, -1);
      
      $tmpRight = explode(SEP, $recursiveRight);
      
      $rootRight = isset($this->rch[0]) ? $this->rch[0] : "";
      $c = count($tmpRight);
      for ($i = 0; $i < $c; $i++) {
	if (isset($this->rch[$tmpRight[$i]]))
	  $rootRight = $this->rch[$tmpRight[$i]];
	else
	  $rootRight = $rootRight;
      }
      $this->rch[$dir] = $rootRight;
    }
    
    if (isEmpty($checkRight)) {
      if (!isEmpty($this->rch[$dir]) || isset($this->rchID[$dir]))
	return true;
      else
	return false;
    }
    
    if (strpos($this->rch[$dir], $checkRight) !== false)
      return true;

    return false;
  }



  /* ------------------------------------------------------------ */
  /** 
   * Update the last login information of user $id_user
   **/
  function updateUserLastLogin($id_user) {
    $q = "UPDATE " . TABLE_PREFIX . "users SET user_lastlogin = NOW() WHERE id_user = '" . $id_user . "'";
    query($q);
  }



  /* ------------------------------------------------------------ */
  /** 
   * Set if the user want to view the file's comments or not
   * @param $id_user integer The user_id 
   * @param $showComment boolean Does it want to see the files comments ?  
   * 
   **/
  function updateUserShowComment($id_user, $showComment) {
    $q = "UPDATE " . TABLE_PREFIX . "users SET user_showcom = '" . $showComment . "' WHERE id_user = '" . $id_user . "'";
    query($q);
  }



  /* ------------------------------------------------------------ */
  /** 
   * Update the global configuration of the Document Manager
   * @param $conf_lang string Default Language
   * @param $conf_adminmail string The email address or mailing list of the document manager administrators
   * @param $conf_mailcondition integer When shall-we send an email when a document is uploaded ? (@see common.php $available_mailcondition)
   * @param $conf_sendrecipient string The email that will be used as a 'from' for outgoing emails
   * @param $conf_showhelpbutton string Shall-we show the help button everywhere linking to the online help ?
   * @param $conf_shcom string shall-we show the files comments (by default) ?
   * @param $conf_style string Which css shall we use ?
   **/
  function updateConfig($conf_lang, $conf_adminmail, $conf_mailcondition, $conf_sendrecipient, $conf_showhelpbutton, $conf_shcom, $conf_style) {
    $q = "DELETE FROM " . TABLE_PREFIX . "config";
    query($q);

    $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "config";
    query($q);

    $q = "INSERT INTO " . TABLE_PREFIX . "config (conf_lang, conf_adminmail, conf_mailcondition, conf_sendrecipient, conf_showhelpbutton, conf_shcom, conf_style) VALUES ('" . $conf_lang . "', '" . $conf_adminmail . "', '" . $conf_mailcondition . "', '" . $conf_sendrecipient . "', '" . $conf_showhelpbutton . "', '" . $conf_shcom . "', '" . $conf_style . "')";
    query($q);
  }



  /* ------------------------------------------------------------ */
  /** 
   * Returns the array of configuration data
   * @returns array an associative array with key => value of configuration d ata
   **/
  function getConfig() {
    $q = "SELECT * FROM " . TABLE_PREFIX . "config";
    $infoConfig = queryOne($q);
    $this->config = $infoConfig;
  }



  /* ------------------------------------------------------------ */
  /** 
   * Echoes the content of a file (similar to readfile) but 1Mb at a time ...
   * @param $file string The filename to echoes
   * @param $returnBytes boolean shall this function returns the number of bytes read ?
   * 
   **/
  function readFileChunked($file, $returnBytes = true) {
    $chunkSize = 1*(1024*1024); // how many bytes per chunk
    $buffer = "";
    $cnt = 0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($file, "rb");
    if ($handle === false)
      return false;

    while (!feof($handle)) {
      $buffer = fread($handle, $chunkSize);
      echo $buffer;
      ob_flush();
      flush();
      if ($returnBytes)
	$cnt += strlen($buffer);
    }

    $status = fclose($handle);
    if ($returnBytes && $status)
      return $cnt; // return num. bytes delivered like readfile() does.

    return $status;
  }



  /* ------------------------------------------------------------ */
  /** 
   * Returns the folders of a path, search recursively
   * @param $id_folder integer The id of the folder in the DB we search for
   * @param $path string the folder we search for
   * @return string the folders'id 
   * 
   **/
  function getRecursiveRight($id_folder, $path = SEP) {
    $q = "SELECT folder_path FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
    $infoFolder = queryOneField($q);

    return $infoFolder;

    if ($id_folder == 0)
      return $path;
    else {
      $q = "SELECT id_parent, id_folder FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
      $infoFolder = queryOne($q);
      return $this->getRecursiveRight($infoFolder["id_parent"], $path . $infoFolder["id_folder"] . SEP);
    }
  }


  /* ------------------------------------------------------------ */
  /** 
   * Return the last error string (translated)
   **/
  function errstr() {
    return _l($this->errors[$this->error]);
  }



  /* ------------------------------------------------------------ */
  /**
   * Return the list of rights associated with a username
   *
   * @return array Return an associative array. Each key is a folder name and each val
   *  is a string containing the rights for this folder.
   *  return false if an error occured.
   */
  function getRights($id_user) {
    $q = "SELECT id_folder, rights FROM " . TABLE_PREFIX . "rights WHERE id_user = '" . $id_user . "'";
    $listRights = queryAssoc($q);
    return $listRights;
  }



  /* ------------------------------------------------------------ */
  /** 
   * Return the list of folders for which a user has any right
   * @param $id_user integer The user-id we search for
   * @return array an associative array of id_folder => foldername
   **/
  function getRightsFolders($id_user) {
    $q = "SELECT f.id_folder, f.folder_path FROM " . TABLE_PREFIX . "folders f LEFT JOIN " . TABLE_PREFIX . "rights r ON (r.id_folder = f.id_folder) WHERE r.id_user = '" . $id_user . "'";
    $listRightsFolders = queryAssoc($q);
    return $listRightsFolders;
  }


  /* ------------------------------------------------------------ */
  /**
   * Add rights to a folder for a user.
   *
   * @param $id_user integer The user_id
   * @param $folder integer The folder_id
   * @param $rights string the rights we give to that user on this folder
   * @return boolean return TRUE if the rights has been added, or FALSE if an error occurred
   */
  function addRights($id_user, $folder, $rights) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "rights WHERE id_user = '" . $id_user . "' && id_folder = '" . $folder . "'";
    $infoRight = queryOne($q);

    if (!empty($infoRight)) {
      $this->error = 13;
      return false;
    }

    $q = "INSERT INTO " . TABLE_PREFIX . "rights (id_user, id_folder, rights) VALUES ('" . $id_user . "', '" . $folder . "', '" . $rights . "')";
    query($q);

    return true;
  }



  /* ------------------------------------------------------------ */
  /**
   * Delete a right for a user from the document manager
   *
   * @param string $id_user The user
   * @param $id_folder integer The folder-id 
   * @return boolean Return TRUE if the right has been deleted, or FALSE if an error occured.
   */
  function delRights($id_user, $id_folder) {
    $q = "DELETE FROM " . TABLE_PREFIX . "rights WHERE id_user = '" . $id_user . "' && id_folder = '" . $id_folder . "'";
    query($q);

    $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "rights";
    query($q);

    return true;
  }



  /* ------------------------------------------------------------ */
  /**
   * Return the list of user accounts on this document manager.
   *
   * @return array Return an associative array. Each key is a login and each val is
   *  an array with $a[pass]=password and $a[rights]=user rights (see rights managment)
   *  return false if an error occured
   */
  function listUsers() {
    $q = "SELECT * FROM " . TABLE_PREFIX . "users ORDER BY user_name ASC";
    $listUsers = queryList($q);
    return $listUsers;
  }



  /* ------------------------------------------------------------ */
  /**
   * Returns the list of user accounts who have at least the Read access to $folder.
   * @param $folder integer A folder-id
   * @params array a list of user's data
   */
  function listUsersWithFolderAccess($folder) {
    $folder=intval($folder);
    $fp=array();
    if ($folder) {
      // First, we list the folders_id in the path, in reverse side order (from the deeper folder_id up to the root)
      $fp=queryOneField("SELECT folder_path FROM " . TABLE_PREFIX . "folders WHERE id_folder='$folder';");
      if (substr($fp,0,1)=="/") $fp=substr($fp,1);
      if (substr($fp,-1,1)=="/") $fp=substr($fp,0,-1);
      $fp=array_reverse(explode("/",$fp));  // Here we have the folder id list
    }
    $fp[]=0;
    $q = "SELECT CONCAT(id_user,'-',id_folder), rights FROM " . TABLE_PREFIX . "rights WHERE id_folder IN (".implode($fp,",").");";
    $allrights=queryAssoc($q);
    // Then, for each user, we check in this order that the user has the rights 
    $q = "SELECT * FROM " . TABLE_PREFIX . "users ORDER BY user_name ASC";
    $r = mysql_query($q);
    $listUsers=array();
    while ($c=mysql_fetch_array($r)) {
      // Check the user's rights
      $hasright=false;
      foreach($fp as $fid) {
	if (isset($allrights[$c["id_user"]."-".$fid])) {
	  if (strpos($allrights[$c["id_user"]."-".$fid],"r")!==false) {
	    $hasright=true;
	  }
	  // if there is rights defined in this folder, let's quit the loop : 
	  // it means that either the user HAS a right to read or NOT
	  // but it means it ! 
	  break;
	}
      } // go up in the folder path
      if ($hasright) {
	$listUsers[]=$c;
      }
    } // for each user
    return $listUsers;
  }


  /* ------------------------------------------------------------ */
  /** 
   * Echo an <option> list of users and their user-id
   **/
  function listUsersOptions() {
    $listUsers = $this->listUsers();

    if (empty($listUsers))
      return;

    $nbUsers = count($listUsers);
    for ($i = 0; $i < $nbUsers; $i++)
      echo "<option value=\"" . $listUsers[$i]["id_user"] . "\">" . $listUsers[$i]["user_name"] . "</option>\n";
  }



  /* ------------------------------------------------------------ */
  /**
   * Add a user to the document manager.
   *
   * @param string $login User Login
   * @param string $pass User Password
   * @param string $rights User rights (see rights managment)
   * @param integer $dr Rights that should be given to the new user : 0=none 1=ro 2=rw 3=see next param
   * @param string $dru User that we should copy rights from
   * @return boolean TRUE if the user has been created, FALSE if an error occured
   */
  function addUser($login, $pass, $admin, $ccp, $email, $defaultRight, $copyUserRight) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "users WHERE user_name = '" . quote($login) . "'";
    $infoUser = queryOne($q);
    if (!empty($infoUser)) {
	$this->error = 2;
	return false;
      }

    $q = "INSERT INTO " . TABLE_PREFIX . "users (user_name, user_password, user_mail, user_admin, user_ccp) VALUES ('" . quote($login) . "', '" . md5($pass) . "', '" . $email . "', '" . $admin . "', '" . $ccp . "')";
    query($q);
    $id_user = mysql_insert_id();

    if ($defaultRight == 1)
      $this->addRights($id_user, 0, "r");

    if ($defaultRight == 2) // Read/Write everywhere
      $this->addRights($id_user, 0, "rudfntmcp");

    if ($defaultRight == 3 && $copyUserRight != 0) // Same as user $dru, let's copy its rights
      $this->copyRights($copyUserRight, $id_user);

    return true;
  }



  /* ------------------------------------------------------------ */
  /** 
   * Copy the rights from one user to another
   * @param $fromUser integer The user id we copy FROM
   * @param $toUser integer The user id we copy TO
   **/
  function copyRights($fromUser, $toUser) {
    $q = "INSERT INTO " . TABLE_PREFIX . "rights (id_user, id_folder, rights) SELECT " . $toUser . ", id_folder, rights FROM " . TABLE_PREFIX . "rights WHERE id_user = '" . $fromUser . "'";
    query($q);
  }



  /* ------------------------------------------------------------ */
  /**
   * Edit a user of the document manager.
   *
   * @param string $login User Login
   * @param string $pass User Password
   * @param string $rights User rights (see rights managment)
   * @return boolean TRUE if the user has been edited, FALSE if an error occured
   */
  function editUser($id_user, $login, $pass, $admin, $ccp, $email) {
    $infoUser = $this->getUser($id_user);

    if (empty($infoUser)) {
      $this->error = 3;
      return false;
    }

    if (empty($pass)) {
      $q = "UPDATE " . TABLE_PREFIX . "users SET user_name = '" . $login . "', user_admin = '" . $admin . "', user_ccp = '" . $ccp . "', user_mail = '" . $email . "' WHERE id_user = '" . $id_user . "'";
    } else {
      $q = "UPDATE " . TABLE_PREFIX . "users SET user_name = '" . $login . "', user_password = '" . md5($pass) . "', user_admin = '" . $admin . "', user_ccp = '" . $ccp . "', user_mail = '" . $email . "' WHERE id_user = '" . $id_user . "'";
    }
    query($q);
    
    return true;
  }



  /* ------------------------------------------------------------ */
  /** 
   * Change the password of a user
   * @param $id_user integer The user-id
   * @param $pass The new password
   **/
  function changePassword($id_user, $pass) {
    $q = "UPDATE " . TABLE_PREFIX . "users SET user_password = '" . md5($pass) . "' WHERE id_user = '" . $id_user . "'";
    query($q);

    return true;
  }



  /* ------------------------------------------------------------ */
  /**
   * Delete a user from the document manager
   *
   * @param string $login Username that must be deleted
   * @return boolean Return TRUE if the user has been deleted, or FALSE if an error occured.
   */
  function delUser($id_user) {
    $infoUser = $this->getUser($id_user);

    if (empty($infoUser)) {
      $this->error = 3;
      return false;
    }

    $q = "DELETE FROM " . TABLE_PREFIX . "users WHERE id_user = '" . $id_user . "'";
    query($q);
    $q = "DELETE FROM " . TABLE_PREFIX . "rights WHERE id_user = '" . $id_user . "'";
    query($q);

    $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "users";
    query($q);
    $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "rights";
    query($q);

    return true;
  }



  /* ------------------------------------------------------------ */
  /**
   * Get a user's parameters and rights
   *
   * @param string $login Username to check
   * @return string Return an array with 'pass', 'email' and 'rights' of the user, or FALSE if an error occured.
   */
  function getUser($id_user) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "users WHERE id_user = '" . $id_user . "'";
    $infoUser = queryOne($q);

    if (empty($infoUser)) {
      $this->error = 3;
      return false;
    }

    return $infoUser;
  }



  /* ------------------------------------------------------------ */
  /**
   * Check a user login/pass and return his rights
   *
   * @param string $login Username to check
   * @param string $pass Password given for this user
   * @return string Return the rights of the user, or FALSE if an error occured.
   */
  function checkUser($login, $pass) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "users WHERE user_name = '" . quote($login) . "'";
    $infoUser = queryOne($q);
    if (empty($infoUser)) {
      $this->error = 3;
      return false;
    }

    $q = "SELECT * FROM " . TABLE_PREFIX . "users WHERE user_name = '" . quote($login) . "' && user_password = '" . md5($pass) . "'";
    $infoUser = queryOne($q);
    if (empty($infoUser)) {
      $this->error = 4;
      return false;
    }

    return $infoUser;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function secureFolder($dir) {
    $fileRoot = realpath($this->root . "files");
    $dir = realpath($fileRoot . $dir);
    if (substr($dir, 0, strlen($fileRoot)) != $fileRoot)
      return "";
    else
      return substr($dir, strlen($fileRoot));
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function secureFile($file) {
    return str_replace(SEP, "", $file);
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function getParentFolder($id_folder) {
    $q = "SELECT id_parent FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
    return queryOneField($q);
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function listFolders($id_folder = 0, $sort = 0) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "folders WHERE id_parent = '" . $id_folder . "' ORDER BY folder_name ASC";
    $listFolders = queryList($q);
    if (!empty($listFolders))
      $listFolders = $this->sortList($listFolders, "folder");

    return $listFolders;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function folderPath($id_folder, $path = "") {
    if ($id_folder == 0)
      return $path;
    else {
      $q = "SELECT id_parent, folder_name FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
      $infoFolder = queryOne($q);
      return $this->folderPath($infoFolder["id_parent"], $path) . SEP . $infoFolder["folder_name"];
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function folderArborescence($id_folder, $path = "") {
    if ($id_folder == 0)
      return $path;
    else {
      $q = "SELECT id_parent, folder_name FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
      $infoFolder = queryOne($q);
      return $this->folderArborescence($infoFolder["id_parent"], $path) . SEP . "<a href=\"browser.php?dir=" . $id_folder . "\">" . $infoFolder["folder_name"] . "</a>";
    }
  }



  /* ------------------------------------------------------------ */
  /**
   * Return the list of the files in a folder relative to $root/files
   *
   * The returned value is an array of array. Each array is a file containing :<pre>
   * $a["name"] = filename
   * $a["size"] = file size in bytes
   * $a["date"] = file last modification time
   * $a["type"] = File type (1 for file, 0 for folder)
   * $this->sizetot = Total size of this folder.
   * @param string $dir Directory to list
   * @param integer $sort How to sort it (see function below)
   */
  function listFiles($id_folder = 0, $sort = 0) {
    $q = "SELECT f.*,u.user_name FROM " . TABLE_PREFIX . "files f LEFT JOIN " . TABLE_PREFIX . "users u ON u.id_user=f.id_user WHERE f.id_folder = '" . $id_folder . "' && f.file_flag = 0 ORDER BY f.file_name ASC";
    $listFiles = queryList($q);
    if (!empty($listFiles))
      $listFiles = $this->sortList($listFiles, "file");

    return $listFiles;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function searchFolders($pattern) {
    $patternArray = explode(" ", $pattern);
    $patternSearch = array();
    foreach ($patternArray as $thePattern) {
      $patternSearch[] = "folder_name LIKE '%" . $thePattern . "%' || folder_comment LIKE '%" . $thePattern . "%'";
    }
    $q = "SELECT * FROM " . TABLE_PREFIX . "folders WHERE " . implode(" || ", $patternSearch) . " ORDER BY folder_name ASC";
    $listFolders = queryList($q);
    if (!empty($listFolders))
      $listFolders = $this->sortList($listFolders, "folder");

    return $listFolders;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function searchFiles($pattern) {
    $patternArray = explode(" ", $pattern);
    $patternSearch = array();
    foreach ($patternArray as $thePattern) {
      $patternSearch[] = "file_name LIKE '%" . $thePattern . "%' || file_comment LIKE '%" . $thePattern . "%'";
    }
    $q = "SELECT * FROM " . TABLE_PREFIX . "files WHERE " . implode(" || ", $patternSearch) . " ORDER BY file_name ASC";
    $listFiles = queryList($q);
    if (!empty($listFiles))
      $listFiles = $this->sortList($listFiles, "file");

    return $listFiles;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function formatSize($size) {
    if ($size == 0)
      return "";

    $size = (float) $size;
    if ($size < 1024)
      $r = $size . "&nbsp;o";
    else {
      $size = $size / 1024;
      if ($size < 1024)
	$r = round($size, 2) . "&nbsp;Ko";
      else {
	$size = $size / 1024;
	if ($size < 1024)
	  $r = round($size, 2) . "&nbsp;Mo";
	else {
	  $size = $size / 1024;
	  if ($size < 1024)
	    $r = round($size, 2) . "&nbsp;Go";
	  else
	    $r = round($size / 1024, 2) . "&nbsp;To";
	}
      }
    }
    return $r;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function type($fileName) {
    $ext = explode(".", $fileName);
    if (!is_array($ext))
      return _l("File");
    $ext = $ext[count($ext) - 1];
    if (!empty($this->a_type[$ext])) {
      $m = $this->a_type[$ext];
      return _l($m);
    }
    return _l("File");
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function mime($fileName) {
    $ext = explode(".", $fileName);
    if (is_array($ext))
      $ext = $ext[count($ext) - 1];
    else
      $ext = "";
    $m = $this->a_mime[$ext];
    if (!$m)
      return "application/octet-stream";
    else
      return $m;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function icon($fileName) {
    $ext = explode(".", $fileName);
    if (!is_array($ext))
      return "file";
    $ext = $ext[count($ext) - 1];
    if (!empty($this->a_icon[$ext])) {
      $m = $this->a_icon[$ext];
      return $m;
    }
    return "file";
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function editFileComment($id_file, $comment) {
    $infoFile = $this->getFileInfo($id_file);

    if (empty($infoFile)) {
      $this->error = 6;
      return false;
    }

    $q = "UPDATE " . TABLE_PREFIX . "files SET file_comment = '" . quote($comment) . "' WHERE id_file = '" . $id_file . "'";
    query($q);

    $this->updateFolderTime($infoFile["id_folder"]);
    return true;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function editFolderComment($id_folder, $comment) {
    $infoFolder = $this->getFolderInfo($id_folder);

    if (empty($infoFolder)) {
      $this->error = 6;
      return false;
    }

    $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_comment = '" . quote($comment) . "' WHERE id_folder = '" . $id_folder . "'";
    query($q);

    $this->updateFolderTime($infoFolder["id_folder"]);
    return true;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function renameFile($id_file, $newFileName) {
    $infoFile = $this->getFileInfo($id_file);
    $newFileName = $this->secureFile($newFileName);
    $folderPath = $this->folderPath($infoFile["id_folder"]);

    if (substr($infoFile["file_name"], 0, 3) == ".ht") {
      $this->error = 6;
      return false;
    }
    if (file_exists($this->root . "files" . $folderPath . SEP . $newFileName)) {
      $this->error = 5;
      return false;
    }
    if (@rename($this->root . "files" . $folderPath . SEP . $infoFile["file_name"], $this->root . "files" . $folderPath . SEP . $newFileName)) {
      $q = "UPDATE " . TABLE_PREFIX . "files SET id_user = '" . $_SESSION["Sid_user"] ."', file_name = '" . quote($newFileName) . "' WHERE id_file = '" . $id_file . "'";
      query($q);

      $this->updateFolderTime($infoFile["id_folder"]);
      return true;
    } else {
      $this->error = 18;
      return false;
    }
    return false;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function getFileInfo($id_file) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "files WHERE id_file = '" . $id_file . "'";
    $infoFile = queryOne($q);
    return $infoFile;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function deleteFile($id_file) {
    $infoFile = $this->getFileInfo($id_file);
    $folderPath = $this->folderPath($infoFile["id_folder"]);

    if (substr($infoFile["file_name"], 0, 3) == ".ht") {
      $this->error = 6;
      return false;
    }

    if (!file_exists($this->root . "files" . $folderPath . SEP . $infoFile["file_name"])) {
      $q = "UPDATE " . TABLE_PREFIX . "files SET file_flag = 1 WHERE id_file = '" . $id_file . "'";
      query($q);
      $this->error = 6;
      return false;
    }

    if (@unlink($this->root . "files" . $folderPath . SEP . $infoFile["file_name"])) {
      $q = "DELETE FROM " . TABLE_PREFIX . "files WHERE id_file = '" . $id_file . "'";
      query($q);

      $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "files";
      query($q);

      $this->updateFolderSize($infoFile["id_folder"], $infoFile["file_size"], "-");
      $this->updateFolderTime($infoFile["id_folder"]);
      return true;
    }
    return false;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function deleteFolder($folder) {
    $folderPath = $this->folderPath($folder);
    if (!file_exists($this->root . "files" . $folderPath)) {
      $this->error = 8;
      return false;
    }

    $q = "SELECT * FROM " . TABLE_PREFIX . "folders WHERE id_parent = '" . $folder . "'";
    $listInsideFolders = queryList($q);
    $q = "SELECT * FROM " . TABLE_PREFIX . "files WHERE id_folder = '" . $folder . "'";
    $listInsideFiles = queryList($q);

    if (!empty($listInsideFolders) || !empty($listInsideFiles)) {
      $this->error = 9;
      return false;
    }

    if (@rmdir($this->root . "files" . $folderPath)) {
      $q = "DELETE FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $folder . "'";
      query($q);
      $q = "DELETE FROM " . TABLE_PREFIX . "rights WHERE id_folder = '" . $folder . "'";
      query($q);
      $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "folders";
      query($q);
      $q = "OPTIMIZE TABLE " . TABLE_PREFIX . "rights";
      query($q);
      return true;
    }
    $this->error = 9;
    return false;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function createFolder($dir, $folder) {
    $folder = $this->secureFile($folder);
    $parentFolder = $this->folderPath($dir);
    if (file_exists($this->root . "files" . $parentFolder . SEP . $folder)) {
      $this->error = 7;
      return false;
    } else {
      if (@mkdir($this->root . "files" . $parentFolder . SEP . $folder, 0777)) {
	  $q = "INSERT INTO " . TABLE_PREFIX . "folders (id_parent, folder_name, folder_mtime) VALUES ('" . $dir . "', '" . quote($folder) . "', NOW())";
	  query($q);

	  $id_folder = mysql_insert_id();
	  $folderPathID = $this->getRecursiveFolderID($id_folder);
	  $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_path = '" . quote($folderPathID) . "' WHERE id_folder = '" . $id_folder . "'";
	  query($q);
	  return $id_folder;
      } else {
	$this->error = 19;
	return false;
      }
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function getRecursiveFolderID($id_folder, $path = SEP) {
    if ($id_folder == 0)
      return $path;
    else {
      $q = "SELECT id_parent, id_folder FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
      $infoFolder = queryOne($q);
      return $this->getRecursiveFolderID($infoFolder["id_parent"], SEP . $infoFolder["id_folder"] . $path);
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function getFolderInfo($id_folder) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
    $infoFolder = queryOne($q);
    return $infoFolder;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function renameFolder($id_folder, $folderName) {
    $folderName = $this->secureFile($folderName);
    $infoFolder = $this->getFolderInfo($id_folder);
    $folderPath = $this->folderPath($infoFolder["id_parent"]);

    if (empty($infoFolder)) {
      $this->error = 8;
      return false;
    }
    if (file_exists($this->root . "files" . $folderPath . SEP . $folderName)) {
      $this->error = 5;
      return false;
    }
    if (@rename($this->root . "files" . $folderPath . SEP . $infoFolder["folder_name"], $this->root . "files" . $folderPath . SEP . $folderName)) {
      $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_name = '" . quote($folderName) . "', folder_mtime = NOW() WHERE id_folder = '" . $id_folder . "'";
      query($q);
      return true;
    }
    return false;
  }


  /* ------------------------------------------------------------ */
  /** 
   * Delete the rights for $id_user on folder that don't exist anymore ...
   * if $id_user is -1 or unspecified, use the current logged-in user.
   **/
  function calculRights($id_user=-1) {
    if ($id_user==-1) $id_user=$_SESSION["Sid_user"];
    $q="SELECT r.id_rights FROM " . TABLE_PREFIX . "rights r LEFT JOIN " . TABLE_PREFIX . "folders f ON f.id_folder=r.id_folder WHERE r.id_folder!=0 AND f.id_folder IS NULL;";
    $r=query($q);
    while ($c=mysql_fetch_array($r)) {
      query("DELETE FROM " . TABLE_PREFIX . "rights WHERE id_rights='".$c["id_rights"]."';");
      printf(_l("right %s has been deleted for this user"),"<b>".$c["id_rights"]."</b>");
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * Update the list of files and folders in this folder. 
   * if $rec is true, do it recursively.
   * if $showresult is true, draw (echo) the list of deleted or added files or folders
   **/
  function calculFolder($folder,$rec=true,$showresult=true) {
    $folderPath = $this->folderPath($folder);
    $listFolders = $this->listFolders($folder);
    $listFiles = $this->listFiles($folder);

    $q="SELECT * FROM " . TABLE_PREFIX . "files WHERE id_folder='$folder'";
    $r=query($q);
    while ($c=mysql_fetch_array($r)) {
      if (!is_file($this->root . "files" .$folderPath . SEP . $c["file_name"])) {
	if ($showresult) printf(_l("file %s has been deleted inside %s directory"),"<b>".$c["file_name"]."</b>","<b>".($folderPath  ? $folderPath : SEP)."</b>");
	query("DELETE FROM " . TABLE_PREFIX . "files WHERE id_file=".$c["id_file"].";");
	echo "<br />";
      }
    }
    $q="SELECT * FROM " . TABLE_PREFIX . "folders WHERE id_parent='$folder'";
    $r=query($q);
    while ($c=mysql_fetch_array($r)) {
      if (!is_dir($this->root . "files" .$folderPath . SEP . $c["folder_name"])) {
	if ($showresult) printf(_l("directory %s has been deleted inside %s directory"),"<b>".$c["folder_name"]."</b>","<b>".($folderPath  ? $folderPath : SEP)."</b>");
	if ($rec) {
	  $this->calculFolder($c["id_folder"]); // recurse !
	}
	query("DELETE FROM " . TABLE_PREFIX . "folders WHERE id_folder=".$c["id_folder"].";");
	echo "<br />";
      }
    }

    $handle = @opendir($this->root . "files" . $folderPath);
    if ($handle) {
      while ($file = readdir($handle)) {
	if (substr($file, 0, 1) != ".") {
	  if (is_dir($this->root . "files" . $folderPath . SEP . $file)) {
	    $id_folder = findInArray("folder_name", $file, $listFolders, "id_folder");
	    if (!$id_folder) {
	      if ($showresult) printf(_l("%s directory has been created inside %s directory"), "<b>" . $file . "</b>", "<b>" . ($folderPath  ? $folderPath : SEP) . "</b>");
	      echo "<br />";
	      $folderMTime = filemtime($this->root . "files" . $folderPath . SEP . $file);
	      $folderMTime = date("Y-m-d H:i:s", $folderMTime);
	      $q = "INSERT INTO " . TABLE_PREFIX . "folders (id_parent, folder_name, folder_mtime) VALUES ('" . $folder . "', '" . quote($file) . "', '" . $folderMTime . "')";
	      query($q);
	      
	      $id_folder = mysql_insert_id();
	      $folderPathID = $this->getRecursiveFolderID($id_folder);
	      $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_path = '" . quote($folderPathID) . "' WHERE id_folder = '" . $id_folder . "'";
	      query($q);
	    }
	    
	    $this->calculFolder($id_folder);
	  } else {
	    if (findInArray("file_name", $file, $listFiles) === false) {
	      if ($showresult) printf(_l("File %s has been added inside %s directory"), "<b>" . $file . "</b>", "<b>" . ($folderPath  ? $folderPath : SEP) . "</b>");
	      echo "<br />";
	      $fileSize = filesize($this->root . "files" . $folderPath . SEP . $file);
	      $fileMTime = filemtime($this->root . "files" . $folderPath . SEP . $file);
	      $fileMTime = date("Y-m-d H:i:s", $fileMTime);
	      $fileComment = "";
	      $q = "INSERT INTO " . TABLE_PREFIX . "files (id_folder, id_user, file_name, file_size, file_mtime, file_comment) VALUES ('" . $folder ."', '" . $_SESSION["Sid_user"] . "', '" . quote($file) . "', '" . $fileSize . "', '" . $fileMTime . "', '" . quote($fileComment) . "')";
	      query($q);
	      
	      $this->updateFolderSize($folder, $fileSize, "+");
	    }
	  }
	}
      } 
      closedir($handle);
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function updateFolderTime($id_folder) {
    if ($id_folder != 0) {
      $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_mtime = NOW() WHERE id_folder = '" . $id_folder . "'";
      query($q);
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function updateFolderSize($id_folder, $size, $operator) {
    if ($id_folder == 0)
      return;

    $q = "SELECT id_parent FROM " . TABLE_PREFIX . "folders WHERE id_folder = '" . $id_folder . "'";
    $parentFolder = queryOne($q);
    $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_size = folder_size " . $operator . " '" . $size . "' WHERE id_folder = '" . $id_folder . "'";
    query($q);
    $this->updateFolderSize($parentFolder["id_parent"], $size, $operator);
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function uploadFile($dir, $file, $fileComment) {
    $fileName = strtolower($file["name"]);
    $fileTmpName = $file["tmp_name"];
    $fileSize = $file["size"];
    $folderPath = $this->folderPath($dir);
    $fileName = $this->secureFile($fileName);

    if (file_exists($this->root . "files" . $folderPath . SEP . $fileName)) {
      $this->error = 5;
      return false;
    }

    if (@move_uploaded_file($fileTmpName, $this->root . "files" . $folderPath . SEP . $fileName)) {
      $q = "INSERT INTO " . TABLE_PREFIX . "files (id_folder, id_user, file_name, file_size, file_mtime, file_comment) VALUES ('" . $dir ."', '" . $_SESSION["Sid_user"] . "', '" . quote($fileName) . "', '" . $fileSize . "', NOW(), '" . quote($fileComment) . "')";
      query($q);

      $this->updateFolderSize($dir, $fileSize, "+");
      $this->updateFolderTime($dir);
      return true;
    } else {
      $this->error = 20;
      return false;
    }
    return false;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function dirList($currentDir, $root = 0, $writeOnly = 0) {
    $q = "SELECT id_folder, id_parent FROM " . TABLE_PREFIX . "folders WHERE 1 ORDER BY folder_name ASC";
    $this->dirListFolders = queryassoc($q);
    $q = "SELECT id_folder, folder_name FROM " . TABLE_PREFIX . "folders WHERE 1";
    $this->dirListFoldersName = queryassoc($q);

    if (!$writeOnly || $this->hasRight($_SESSION["Sid_user"], "u", $root)) {
      echo "<option value=\"" . $root . "\"";
      if ($currentDir == $root) echo " selected=\"selected\"";
      echo ">" . SEP . "</option>\n";
    } // has right ?
    if (array_keys($this->dirListFolders, 0))
      $this->dirListOptions($currentDir, $writeOnly);
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function dirListMoveFolder($currentDir, $folderSource, $root = 0, $writeOnly = 0) {
    $q = "SELECT id_folder, id_parent FROM " . TABLE_PREFIX . "folders WHERE folder_path NOT LIKE '%" . SEP . $folderSource . SEP . "%' || id_folder != '" . $folderSource . "' ORDER BY folder_name ASC";
    $this->dirListFolders = queryassoc($q);
    $q = "SELECT id_folder, folder_name FROM " . TABLE_PREFIX . "folders WHERE 1";
    $this->dirListFoldersName = queryassoc($q);

    if (!$writeOnly || $this->hasRight($_SESSION["Sid_user"], "u", $root)) {
      echo "<option value=\"" . $root . "\"";
      if ($currentDir == $root) echo " selected=\"selected\"";
      echo ">" . SEP . "</option>\n";
    } // has right ?
    if (array_keys($this->dirListFolders, 0))
      $this->dirListOptions($currentDir, $writeOnly);
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function dirListOptions($currentDir, $writeOnly = 0, $search = 0, $path = SEP) {
    if ($tmp = array_keys($this->dirListFolders, $search)) {
      foreach ($tmp as $tmpFolder) {
	if (!$writeOnly || $this->hasRight($_SESSION["Sid_user"], "u", $tmpFolder)) {
	  $currentPath = $path . $this->dirListFoldersName[$tmpFolder] . SEP;
	  if (array_keys($this->dirListFolders, $tmpFolder)) {
	    echo "<option value=\"" . $tmpFolder . "\"" . ($currentDir == $tmpFolder ? " selected=\"selected\"" : "") . ">" . $currentPath . "</option>\n";
	    $this->dirListOptions($currentDir, $writeOnly, $tmpFolder, $currentPath);
	  } else
	    echo "<option value=\"" . $tmpFolder . "\"" . ($currentDir == $tmpFolder ? " selected=\"selected\"" : "") . ">" . $currentPath . "</option>\n";
	}
      }
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function sendMail($user, $dir, $file, $comment) {
    $infoUser = $this->getUser($user);
    $folderPath = $this->folderPath($dir);

    // Depending on the language used, we open the corresponding mail file.
    if ($_SESSION["lang"] && file_exists($this->root . "data" . SEP . "mail_" . $_SESSION["lang"] . ".txt"))
      $mailFile = $this->root . "data" . SEP . "mail_" . $_SESSION["lang"] . ".txt";
    else {
      if (!file_exists($this->root . "data" . SEP . "mail.txt")) {
	$this->error = 12;
	return false;
      } else
	$mailFile = $this->root . "data" . SEP . "mail.txt";
    }

    $f = file($mailFile);

    $subject = $f[0];
    $f[0] = "";
    $f = implode("", $f);
    if (!$f) {
      $this->error = 12;
      return false;
    }

    $URL = (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on" ? "http" : "https") . "://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    $URL = substr($URL, 0, strrpos($URL,"/php/"));
    $f = str_replace("%%DATE%%", date(_l("Y/m/d")), $f);
    $f = str_replace("%%FILENAME%%", $file, $f);
    $f = str_replace("SEP", SEP, $f);
    $f = str_replace("%%DIR%%", $folderPath, $f);
    $f = str_replace("%%USER%%", $infoUser["user_name"], $f);
    $f = str_replace("%%COMMENT%%", $comment, $f);
    $f = str_replace("%%URL%%", $URL, $f);
    $subject = str_replace("%%DATE%%", date(_l("Y/m/d")), $subject);
    $subject = str_replace("%%FILENAME%%", $file, $subject);
    $subject = str_replace("SEP", SEP, $subject);
    $subject = str_replace("%%DIR%%", $folderPath, $subject);
    $subject = str_replace("%%USER%%", $infoUser["user_name"], $subject);
    $subject = str_replace("%%COMMENT%%", $comment, $subject);
    $subject = str_replace("%%URL%%", $URL, $subject);

    if ($this->config["conf_sendrecipient"] == 0) { /* Send the email to the administrator only */
      if (!@mail($this->config["conf_adminmail"], $subject, $f, "From: " . $this->config["conf_adminmail"] . "\nReply-to: " . $this->config["conf_adminmail"] . "\nContent-Type: text/plain; charset=ISO8859-1\n")) {
	$this->error = 17;
	return false;
      }
    } else { // Send the mail to all the users who have at least read access to this folder : 
      $listUser = $this->listUsersWithFolderAccess($dir);
      $nbUsers = count($listUser);
      for ($i = 0; $i < $nbUsers; $i++) {
	if (!empty($listUser[$i]["user_mail"])) {
	  if (!@mail($listUser[$i]["user_mail"], $subject, $f, "From: ".$this->config["conf_adminmail"]."\nReply-to: ".$this->config["conf_adminmail"]."\nContent-Type: text/plain; charset=ISO8859-1\n")) {
	    $this->error = 17;
	    return false;
	  }
	}
      }
    }
    return true;
  }
  


  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function moveFile($dir, $file, $newDir) {
    $infoFile = $this->getFileInfo($file);
    $dirPath = $this->folderPath($infoFile["id_folder"]);
    $newDirPath = $this->folderPath($newDir);
    if (file_exists($this->root . "files" . $newDirPath . SEP . $infoFile["file_name"])) {
      $this->error = 11;
      return false;
    }

    if (@rename($this->root . "files" . $dirPath . SEP . $infoFile["file_name"], $this->root . "files" . $newDirPath . SEP . $infoFile["file_name"])) {
      $q = "UPDATE " . TABLE_PREFIX . "files SET id_folder = '" . $newDir . "' WHERE id_file = '" . $infoFile["id_file"] . "'";
      query($q);

      $this->updateFolderTime($newDir);
      $this->updateFolderSize($dir, $infoFile["file_size"], "-");
      $this->updateFolderSize($newDir, $infoFile["file_size"], "+");
      return true;
    }
    return false;
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function moveFolder($folderSource, $folderDest, $copy = false) {
    $infoFolderSource = $this->getFolderInfo($folderSource);
    $infoFolderDest = $this->getFolderInfo($folderDest);
    $sourcePath = $this->folderPath($folderSource);
    if ($folderDest == 0)
      $destPath = SEP . $infoFolderSource["folder_name"];
    else
      $destPath = $this->folderPath($folderDest) . SEP . $infoFolderSource["folder_name"];

    if (file_exists($this->root . "files" . $destPath)) {
      $this->error = 7;
      return false;
    }

    if (mkdir($this->root . "files" . $destPath, 0777)) {
      $handle = opendir($this->root . "files" . $sourcePath);
      while ($file = readdir($handle)) {
	if (is_dir($this->root . "files" . $sourcePath . SEP . $file)) {
	  if (substr($file, 0, 1) != ".") {
	    if (mkdir($this->root . "files" . $destPath . SEP . $file, 0777)) {
	      $this->moveFolderRecursive($sourcePath . SEP . $file, $destPath . SEP . $file, $copy);
	    }
	  }
	} else {
	  copy($this->root . "files" . $sourcePath . SEP . $file, $this->root . "files" . $destPath . SEP . $file);
	  if (!$copy) {
	    unlink($this->root . "files" . $sourcePath . SEP . $file);
	  }
	}
      }
      closedir($handle);
      if (!$copy) {
	rmdir($this->root . "files" . $sourcePath);
      }
      $q = "UPDATE " . TABLE_PREFIX . "folders SET id_parent = '" . $folderDest . "' WHERE id_folder = '" . $folderSource . "'";
      query($q);
      $this->updateFolderPath($folderSource, $folderDest);
      $this->updateFolderSize($infoFolderSource["id_parent"], $infoFolderSource["folder_size"], "-");
      if ($folderDest != 0)
	$this->updateFolderSize($infoFolderDest["id_folder"], $infoFolderSource["folder_size"], "+");

      return true;
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function moveFolderRecursive($sourcePath, $destPath, $copy = false) {
    $handle = opendir($this->root . "files" . $sourcePath);
    while ($file = readdir($handle)) {
      if (is_dir($this->root . "files" . $sourcePath . SEP . $file)) {
	if (substr($file, 0, 1) != ".") {
	  if (mkdir($this->root . "files" . $destPath . SEP . $file, 0777)) {
	    $this->moveFolderRecursive($sourcePath . SEP . $file, $destPath . SEP . $file, $copy);
	  }
	}
      } else {
	copy($this->root . "files" . $sourcePath . SEP . $file, $this->root . "files" . $destPath . SEP . $file);
	if (!$copy) {
	  unlink($this->root . "files" . $sourcePath . SEP . $file);
	}
      }
    }
    closedir($handle);
    if (!$copy) {
      rmdir($this->root . "files" . $sourcePath);
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function updateFolderPath($folderSource, $folderDest) {
    $infoFolderSource = $this->getFolderInfo($folderSource);
    $infoFolderDest = $this->getFolderInfo($folderDest);

    $q = "SELECT * FROM " . TABLE_PREFIX . "folders WHERE folder_path LIKE '%" . SEP . $folderSource . SEP . "%'";
    $listFolderPathSource = queryList($q);

    foreach ($listFolderPathSource as $folderPathSource) {
      $newFolderPath = strstr($folderPathSource["folder_path"], SEP . $folderSource . SEP);
      if ($folderDest != 0)
	$newFolderPath = $infoFolderDest["folder_path"] . $newFolderPath;
      $newFolderPath = str_replace(SEP . SEP, SEP, $newFolderPath);

      $q = "UPDATE " . TABLE_PREFIX . "folders SET folder_path = '" . quote($newFolderPath) . "' WHERE id_folder = '" . $folderPathSource["id_folder"] . "'";
      query($q);
    }
  }



  /* ------------------------------------------------------------ */
  /** 
   * Send a login/password to a user who lost its login/password
   **/
  function forgotPassword($login) {
    $q = "SELECT * FROM " . TABLE_PREFIX . "users WHERE user_name = '" . quote($login) . "'";
    $infoUser = queryOne($q);

    if (empty($infoUser)) {
      $this->error = 3;
      return false;
    }

    if (empty($infoUser["user_mail"])) {
      $this->error = 14;
      return false;
    }
    // the user's password is encrypted, create a new one
    $chars = "aaabcdeeefghiiiklnoooprtuuuvwxyz23456789";
    $password = "";

    for($i = 0; $i < 7; $i++)
      $password .= substr($chars, rand()%strlen($chars), 1);

    $this->changePassword($infoUser["id_user"], $password);

    // Depending on the language, we send the login/pass
    if ($_SESSION["lang"] && file_exists($this->root . "data" . SEP . "forgot_" . $_SESSION["lang"] . ".txt"))
      $mailfile = $this->root . "data" . SEP . "forgot_" . $_SESSION["lang"] . ".txt";
    else {
      if (!file_exists($this->root . "data" . SEP . "forgot.txt")) {
	$this->error = 12;
	return false;
      } else
	$mailfile = $this->root . "data" . SEP . "forgot.txt";
    }

    $f = file($mailfile);
    $subject = $f[0];
    $f[0] = "";
    $f = implode('', $f);
    if (!$f) {
      $this->error = 12;
      return false;
    }

    $f = str_replace("%%DATE%%", date(_l("Y/m/d")), $f);
    $f = str_replace("%%LOGIN%%", $infoUser["user_name"], $f);
    $f = str_replace("%%PASSWORD%%", $password, $f);

    mail($infoUser["user_mail"], $subject, $f, "From: " . $doc->config["conf_adminmail"] . "\nReply-to: " . $doc->config["conf_adminmail"] . "\n");
    return true;
  }



  /* ------------------------------------------------------------ */
  /**
   * Send a login/password to a user who lost its login/password
   **/
  function forgotLogin($email) {
    // TODO : maintain a reverse email index
    $q = "SELECT * FROM " . TABLE_PREFIX . "users WHERE user_mail = '" . $email . "'";
    $infoUser = queryOne($q);

    if (empty($infoUser)) {
      $this->error = 15;
      return false;
    }

    return $this->forgotPassword($infoUser["user_name"]);
  }



  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function arraySort() {
    $args = func_get_args();
    $mArray = array_shift($args);
    $i = 0;
    $mSortLine = "return(array_multisort(";
    foreach ($args AS $arg) {
      $i++;
      if (is_string($arg)) {
	foreach ($mArray AS $row)
	  $sortArr[$i][] = strtolower($row[$arg]);
      }
      else
	$sortArr[$i] = $arg;

      $mSortLine .= "\$sortArr[" . $i . "],";
    }

    $mSortLine .= "\$mArray));";
    eval($mSortLine);
    return $mArray;
  }


  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function sortList($list, $prefix) {
    switch ($this->sort) {
    case 0: // Name ascending
      return $this->arraySort($list, $prefix . "_name", SORT_ASC);
      break;
    case 1: // Name descending
      return $this->arraySort($list, $prefix . "_name", SORT_DESC);
      break;
    case 2: // Size ascending
      return $this->arraySort($list, $prefix . "_size", SORT_ASC);
      break;
    case 3: // Size descending
      return $this->arraySort($list, $prefix . "_size", SORT_DESC);
      break;
    case 4: // Date descending
      return $this->arraySort($list, $prefix . "_mtime", SORT_ASC);
      break;
    case 5: // Date descending
      return $this->arraySort($list, $prefix . "_mtime", SORT_DESC);
      break;
    case 6: // Author descending
      if ($prefix=="folder") {
	return $this->arraySort($list, $prefix."_name", SORT_ASC);
      } else {
	return $this->arraySort($list, "user_name", SORT_ASC);
      }
      break;
    case 7: // Author ascending
      if ($prefix=="folder") {
	return $this->arraySort($list, $prefix."_name", SORT_DESC);
      } else {
	return $this->arraySort($list, "user_name", SORT_DESC);
      }
      break;
    }
  }

  /* ------------------------------------------------------------ */
  /** 
   * 
   **/
  function getAuthorName($author) {
    $author=intval($author); if (!$author) return "";
    if (!$this->authorfetched) {
      $this->authorcache=queryAssoc("SELECT id_user,user_name FROM ".TABLE_PREFIX."users ORDER BY id_user LIMIT 0,20");
      $this->authorfetched=true;
    }
    if (!$me=$this->authorcache[$author]) {
      $me=$this->authorcache[$author]=queryOneField("SELECT user_name FROM ".TABLE_PREFIX."users WHERE id_user='$author';");
      if (!$me) 
	return "<i>"._l("Unknown")."</i>";
      else
	return $me;
    } else {
      return $me;
    }
  }



	
} // Class DocManager

?>