Alternc  3.2
Alternc logiel libre pour l'hébergement
 All Data Structures Namespaces Files Functions Variables Pages
m_bro.php
Go to the documentation of this file.
1 <?php
2 /*
3  ----------------------------------------------------------------------
4  AlternC - Web Hosting System
5  Copyright (C) 2000-2012 by the AlternC Development Team.
6  https://alternc.org/
7  ----------------------------------------------------------------------
8  LICENSE
9 
10  This program is free software; you can redistribute it and/or
11  modify it under the terms of the GNU General Public License (GPL)
12  as published by the Free Software Foundation; either version 2
13  of the License, or (at your option) any later version.
14 
15  This program is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  GNU General Public License for more details.
19 
20  To read the license please visit http://www.gnu.org/copyleft/gpl.html
21  ----------------------------------------------------------------------
22  Purpose of file: file browser class.
23  ----------------------------------------------------------------------
24 */
25 
26 /* Add the mime type list */
27 @include("mime.php");
28 
29 /**
30  * This class manage the file browser of AlternC
31  * allow the file and directory management in the user account web folder
32  */
33 class m_bro {
34 
35  /** How we draw the file in column */
36  var $l_mode;
37 
38  /** download mode of a compressed folder */
39  var $l_tgz;
40 
41  /** Shall we show icons or just names? */
42  var $l_icons;
43 
44  /** What do we do after creating a file? */
46 
47  /** internal cache
48  */
49  var $mime_desc=array();
50 
51  /** internal cache
52  */
53  var $mime_icon=array();
54 
55  /** internal cache
56  */
57  var $mime_type=array();
58 
59  /** Font choice in the editor */
60  var $l_editor_font=array("Arial, Helvetica, Sans-serif","Times, Bookman, Serif","Courier New, Courier, Fixed");
61 
62  /** font size in the editor */
63  var $l_editor_size=array("18px","14px","12px","10px","8px","0.8em","0.9em","1em","1.1em","1.2em");
64 
65  /* ----------------------------------------------------------------- */
66  /** Constructor */
67  function m_bro() {
68  $this->l_mode=array( 0=>_("1 column, detailed"), 1=>_("2 columns, short"), 2=>_("3 columns, short") );
69  $this->l_tgz=array( 0=>_("tgz (Linux)"), 1=>_("tar.bz2 (Linux)"), 2=>_("zip (Windows/Dos)"), 3=>_("tar.Z (Unix)") );
70  $this->l_icons=array( 0=>_("No"), 1=>_("Yes") );
71  $this->l_createfile=array( 0=>_("Go back to the file manager"), 1=>_("Edit the newly created file") );
72  }
73 
74  function hook_menu() {
75  $obj = array(
76  'title' => _("File browser"),
77  'ico' => 'images/folder.png',
78  'link' => 'bro_main.php',
79  'pos' => 40,
80  ) ;
81 
82  return $obj;
83  }
84 
85 
86 
87  /* ----------------------------------------------------------------- */
88  /** Verifie un dossier relatif au dossier de l'utilisateur courant
89  *
90  * @param string $dir Dossier (absolu que l'on souhaite vrifier
91  * @return string Retourne le nom du dossier vrifi, relatif au
92  * dossier de l'utilisateur courant, ventuellement corrig.
93  * ou FALSE si le dossier n'est pas dans le dossier de l'utilisateur.
94  */
95  function convertabsolute($dir,$strip=1) {
96  global $mem;
97  $root=$this->get_user_root($mem->user["login"]);
98  // Sauvegarde du chemin de base.
99  $root_alternc = $root ;
100  // Passage du root en chemin rel (diffrent avec un lien)
101  $root=realpath($root) ;
102  // separer le chemin entre le repertoire et le fichier
103  $file = basename($dir);
104  $dir = dirname($dir);
105  $dir=realpath($root."/".$dir);
106  // verifier que le repertoire est dans le home de l'usager
107  if (substr($dir,0,strlen($root))!=$root) {
108  return false;
109  }
110 
111  // recomposer le chemin
112  $dir = $dir . '/' . $file;
113 
114  # Si on tente de mettre un '..' alors erreur
115  if ( preg_match("/\/\.\.\//", $dir) || preg_match("/\/\.\.$/", $dir) ) {
116  return false;
117  }
118 
119  if ($strip) {
120  $dir=substr($dir,strlen($root));
121  } else {
122  // si on ne strip pas, il faut enlever le chemin rel
123  // et mettre la racine d'alternc pour viter les
124  // problmes de lien depuis /var /alternc !
125  $dir=$root_alternc . substr($dir,strlen($root));
126  }
127  if (substr($dir,-1)=="/") {
128  return substr($dir,0,strlen($dir)-1);
129  } else
130  return $dir;
131  }
132 
133 
134  /* ----------------------------------------------------------------- */
135  /** Retourne le chemin complet vers la racine du repertoire de l'utilisateur.
136  * Returns the complete path to the root of the user's directory.
137  *
138  * @param string $login Username
139  * @return string Returns the complete path to the root of the user's directory.
140  */
141  function get_user_root($login) {
142  return getuserpath();
143  }
144 
145 
146  /* ----------------------------------------------------------------- */
147  /** Retourne le chemin complet vers la racine du repertoire de l'utilisateur.
148  * Returns the complete path to the root of the user's directory.
149  *
150  * @param string $uid User id.
151  * @return string Returns the complete path to the root of the user's directory.
152  */
153  function get_userid_root($uid) {
154  global $admin;
155 
156  // FIXME [ML] Comment faire ca correctement?
157  // C'est utilise' dans class/m_dom.php quand un utilisateur ajoute un domaine dans son compte
158  // et nous devons savoir quel est le chemin complet vers la racine de son compte..
159 
160  $old_enabled = $admin->enabled;
161  $admin->enabled = true;
162  $member = $admin->get($uid);
163  $admin->enabled = $old_enabled;
164 
165  return $this->get_user_root($member['login']);
166  }
167 
168 
169  /* ----------------------------------------------------------------- */
170  /** Retourne un tableau contenant la liste des fichiers du dossier courant
171  * Ce tableau contient tous les paramtres des fichiers du dossier courant
172  * sous la forme d'un tableau index de tableaux associatifs comme suit :
173  * $a["name"]=nom du fichier / dossier
174  * $a["size"]=Taille totale du fichier / dossier + sous-dossier
175  * $a["date"]=Date de dernire modification
176  * $a["type"]=Type du fichier (1 pour fichier, 0 pour dossier)
177  * @param string $dir dossier relatif au dossier racine du compte du
178  * membre courant
179  * @return array le tableau contenant les fichiers de $dir, et
180  */
181  function filelist($dir="", $showdirsize = false) {
182  global $db,$cuid,$err;
183  $db->query("UPDATE browser SET lastdir='$dir' WHERE uid='$cuid';");
184  $absolute=$this->convertabsolute($dir,0);
185  if (! file_exists($absolute)) {
186  $err->raise('bro',_("This directory do not exist"));
187  return false;
188  }
189  if ($dir = @opendir($absolute)) {
190  while (($file = readdir($dir)) !== false) {
191  if ($file!="." && $file!="..") {
192  $c[]=array("name"=>$file, "size"=>$this->fsize($absolute."/".$file, $showdirsize), "date"=>filemtime($absolute."/".$file), "type"=> (!is_dir($absolute."/".$file)) );
193  }
194  }
195  closedir($dir);
196  }
197  if (isset ($c) && is_array($c)) {
198  usort ($c, array("m_bro","_sort_filelist_name"));
199  return $c;
200  } else {
201  return array();
202  }
203  }
204 
205 
206  /* ----------------------------------------------------------------- */
207  /** Retourne un tableau contenant les prfrences de l'utilisateur courant
208  * Ce tableau aqssociatif contient les valeurs des champs de la table "browser"
209  * pour l'utilisateur courant.
210  * @return array Tableau des prfrences de l'utilisateur courant.
211  */
212  function GetPrefs() {
213  global $db,$cuid;
214  $db->query("SELECT * FROM browser WHERE uid='$cuid';");
215  if ($db->num_rows()==0) {
216  $db->query("INSERT INTO browser (editsizex, editsizey, listmode, showicons, downfmt, createfile, showtype, uid, editor_font, editor_size) VALUES (70, 21, 0, 0, 0, 0, 0, '$cuid','Arial, Helvetica, Sans-serif','12px');");
217  $db->query("SELECT * FROM browser WHERE uid='$cuid';");
218  }
219  $db->next_record();
220  return $db->Record;
221  }
222 
223 
224  /* ----------------------------------------------------------------- */
225  /** Modifie les prfrences de l'utilisateur courant.
226  *
227  * @param integer $editsizex Taille de l'diteur (nombre de colonnes)
228  * @param integer $editsizey Taille de l'diteur (nombre de lignes)
229  * @param integer $listmode Mode d'affichage de la liste des fichiers
230  * @param integer $showicons Faut-il afficher / cacher les icones des fichiers
231  * @param integer $downfmt Dans quel format faut-il tlcharger les dossiers compresss
232  * @param integer $createfile Faut-il editer/revenir au browser aprs cration d'un fichier
233  * @param integer $showtype Faut-il afficher le type mime des fichiers
234  * @param integer $editor_font Quelle police faut-il utiliser pour l'diteur
235  * @param integer $editor_size Quelle taille de police faut-il utiliser pour l'diteur
236  * @param integer $golastdir Faut-il revenir la racine ou au dernier dossier visit ?
237  * @return boolean TRUE
238  */
239  function SetPrefs($editsizex, $editsizey, $listmode, $showicons, $downfmt, $createfile, $showtype, $editor_font, $editor_size, $golastdir) {
240  global $db,$cuid;
241  $editsizex=intval($editsizex); $editsizey=intval($editsizey);
242  $listmode=intval($listmode); $showicons=intval($showicons);
243  $showtype=intval($showtype); $downfmt=intval($downfmt);
244  $createfile=intval($createfile); $golastdir=intval($golastdir);
245  $db->query("SELECT * FROM browser WHERE uid='$cuid';");
246  if ($db->num_rows()==0) {
247  $db->query("INSERT INTO browser (editsizex, editsizey, listmode, showicons, downfmt, createfile, showtype, uid, editor_font, editor_size, golastdir) VALUES (70, 21, 0, 0, 0, 0, 0, '".$this->uid."','Arial, Helvetica, Sans-serif','12px',1);");
248  }
249  $db->query("UPDATE browser SET editsizex='$editsizex', editsizey='$editsizey', listmode='$listmode', showicons='$showicons', downfmt='$downfmt', createfile='$createfile', showtype='$showtype', editor_font='$editor_font', editor_size='$editor_size', golastdir='$golastdir' WHERE uid='$cuid';");
250  return true;
251  }
252 
253 
254  /* ----------------------------------------------------------------- */
255  /** Retourne le nom du fichier icone associ au fichier donc le nom est $file
256  * <b>Note</b>: Les fichiers icones sont mis en cache sur la page courante.
257  * @param string $file Fichier dont on souhaite connaitre le fichier icone
258  * @return string Fichier icone correspondant.
259  */
260  function icon($file) {
261  global $bro_icon;
262  if (!strpos($file,".") && substr($file,0,1)!=".") {
263  return "file.png";
264  }
265  $t=explode(".",$file);
266  if (!is_array($t))
267  $ext=$t;
268  else
269  $ext=$t[count($t)-1];
270  // Now seek the extension
271  if (!isset($bro_icon[$ext]) || ! $bro_icon[$ext]) {
272  return "file.png";
273  } else {
274  return $bro_icon[$ext].".png";
275  }
276  }
277 
278 
279  /* ----------------------------------------------------------------- */
280  /** Retourne le type mime associ au fichier donc le nom est $file
281  * <b>Note</b>: Les types mimes sont mis en cache sur la page courante.
282  * Le type mime est dtermin d'aprs l'extension du fichier.
283  * @param string $file Fichier dont on souhaite connaitre le type mime
284  * @return string Type mime / Sous type du fichier demand
285  */
286  function mime($file) {
287  global $bro_type;
288  if (!strpos($file,".") && substr($file,0,1)!=".") {
289  return "File";
290  }
291  $t=explode(".",$file);
292  if (!is_array($t))
293  $ext=$t;
294  else
295  $ext=$t[count($t)-1];
296  // Now seek the extension
297  if (empty($bro_type[$ext])) {
298  return "File";
299  } else {
300  return $bro_type[$ext];
301  }
302  }
303 
304 
305  /* ----------------------------------------------------------------- */
306  /** Retourne la taille du fichier $file
307  * si $file est un dossier, retourne la taille de ce dossier et de tous
308  * ses sous dossiers.
309  * @param string $file Fichier dont on souhaite connaitre la taille
310  * @param boolean $showdirsize recursively compute the directory size.
311  * @return integer Taille du fichier en octets.
312  */
313  function fsize($file, $showdirsize = false) {
314  if (is_dir($file)) {
315  if ($showdirsize) {
316  return $this->dirsize($file);
317  } else {
318  return "-";
319  }
320  } else {
321  return filesize($file);
322  }
323  }
324 
325 
326  /* ----------------------------------------------------------------- */
327  /** Returns the size of a directory, by adding all it's files sizes
328  * @param string $dir the directory whose size we want to compute
329  * @return integer the total size in bytes.
330  */
331  function dirsize($dir) {
332  $totalsize = 0;
333 
334  if ($handle = opendir($dir)) {
335  while (false !== ($file = readdir($handle))) {
336  $nextpath = $dir . '/' . $file;
337 
338  if ($file != '.' && $file != '..' && !is_link($nextpath)) {
339  if (is_dir($nextpath)) {
340  $totalsize += $this->dirsize($nextpath);
341  } elseif (is_file ($nextpath)) {
342  $totalsize += filesize($nextpath);
343  }
344  }
345  }
346  closedir($handle);
347  }
348  return $totalsize;
349  }
350 
351 
352  /* ----------------------------------------------------------------- */
353  /** Cre le dossier $file dans le dossier (parent) $dir
354  * @param string $dir dossier dans lequel on veut crer un sous-dossier
355  * @param string $file nom du dossier crer
356  * @return boolean TRUE si le dossier a t cr, FALSE si une erreur s'est produite.
357  */
358  function CreateDir($dir,$file) {
359  global $db,$cuid,$err;
360  $file=ssla($file);
361  $absolute=$this->convertabsolute($dir."/".$file,0);
362  #echo "$absolute";
363  if ($absolute && (!file_exists($absolute))) {
364  if (!mkdir($absolute,00777,true)) {
365  $err->raise("bro",_("Cannot create the requested directory. Please check the permissions"));
366  return false;
367  }
368  $db->query("UPDATE browser SET crff=1 WHERE uid='$cuid';");
369  return true;
370  } else {
371  $err->raise("bro",_("File or folder name is incorrect"));
372  return false;
373  }
374  }
375 
376 
377  /* ----------------------------------------------------------------- */
378  /** Cre un fichier vide dans un dossier
379  * @param string $dir Dossier dans lequel on cre le nouveau fichier
380  * @param string $file Fichier que l'on souhaite crer.
381  * @return boolean TRUE si le dossier a t cr, FALSE si une erreur s'est produite.
382  */
383  function CreateFile($dir,$file) {
384  global $db,$err,$cuid;
385  $file=ssla($file);
386  $absolute=$this->convertabsolute($dir."/".$file,0);
387  if (!$absolute || file_exists($absolute)) {
388  $err->raise("bro",_("File or folder name is incorrect"));
389  return false;
390  }
391  if (!file_exists($absolute)) {
392  if (!@touch($absolute)) {
393  $err->raise("bro",_("Cannot create the requested file. Please check the permissions"));
394  return false;
395  }
396  }
397  $db->query("UPDATE browser SET crff=0 WHERE uid='$cuid';");
398  return true;
399  }
400 
401 
402  /* ----------------------------------------------------------------- */
403  /** Efface les fichiers du tableau $file_list dans le dossier $R
404  * @param array $file_list Liste des fichiers effacer.
405  * @param string $R Dossier dans lequel on efface les fichiers
406  * @return boolean TRUE si les fichiers ont t effacs, FALSE si une erreur s'est produite.
407  */
408  function DeleteFile($file_list,$R) {
409  global $err, $mem;
410  $root=realpath(getuserpath());
411  $absolute=$this->convertabsolute($R,0);
412  if (!$absolute && strpos($root,$absolute) === 0 && strlen($absolute) > (strlen($root)+1) ) {
413  $err->raise("bro",_("File or folder name is incorrect"));
414  return false;
415  }
416  for ($i=0;$i<count($file_list);$i++) {
417  $file_list[$i]=ssla($file_list[$i]);
418  if (!strpos($file_list[$i],"/") && file_exists($absolute."/".$file_list[$i])) { // Character / forbidden in a FILE name
419  $this->_delete($absolute."/".$file_list[$i]);
420  }
421  }
422  return true;
423  }
424 
425 
426  /* ----------------------------------------------------------------- */
427  /** Renomme les fichier de $old du dossier $R en $new
428  * @param string $R dossier dans lequel se trouve les fichiers renommer.
429  * @param array of string $old Ancien nom des fichiers
430  * @param array of string $new Nouveau nom des fichiers
431  * @return boolean TRUE si les fichiers ont t renomms, FALSE si une erreur s'est produite.
432  */
433  function RenameFile($R,$old,$new) {
434  global $err;
435  $absolute=$this->convertabsolute($R,0);
436  if (!$absolute) {
437  $err->raise("bro",_("File or folder name is incorrect"));
438  return false;
439  }
440  $alea=".".time().rand(1000,9999);
441  for ($i=0;$i<count($old);$i++) {
442  $old[$i]=ssla($old[$i]); // strip slashes if needed
443  $new[$i]=ssla($new[$i]);
444  if (!strpos($old[$i],"/") && !strpos($new[$i],"/")) { // caractre / interdit dans old ET dans new...
445  @rename($absolute."/".$old[$i],$absolute."/".$old[$i].$alea);
446  }
447  }
448  for ($i=0;$i<count($old);$i++) {
449  if (!strpos($old[$i],"/") && !strpos($new[$i],"/")) { // caractre / interdit dans old ET dans new...
450  @rename($absolute."/".$old[$i].$alea,$absolute."/".$new[$i]);
451  }
452  }
453 
454  return true;
455  }
456 
457 
458  /* ----------------------------------------------------------------- */
459  /** Dplace les fichier de $d du dossier $old vers $new
460  * @param array of string $d Liste des fichiers du dossier $old dplacer
461  * @param string $old dossier dans lequel se trouve les fichiers dplacer.
462  * @param string $new dossier vers lequel seront dplacs les fichiers.
463  * @return boolean TRUE si les fichiers ont t renomms, FALSE si une erreur s'est produite.
464  */
465  function MoveFile($d,$old,$new) {
466  global $err;
467  $old=$this->convertabsolute($old,0);
468  if (!$old) {
469  $err->raise("bro",_("File or folder name is incorrect"));
470  return false;
471  }
472 
473  if ($new[0] != '/') {
474  $new = $old . '/' . $new;
475  }
476  $new = $this->convertabsolute($new,0);
477 
478  if (!$new) {
479  $err->raise("bro",_("File or folder name is incorrect"));
480  return false;
481  }
482  if ($old==$new) {
483  $err->raise("bro",_("You cannot move or copy a file to the same folder"));
484  return false;
485  }
486  for ($i=0;$i<count($d);$i++) {
487  $d[$i]=ssla($d[$i]); // strip slashes if needed
488  if (!strpos($d[$i],"/") && file_exists($old."/".$d[$i]) && !file_exists($new."/".$d[$i])) {
489  if (!rename($old."/".$d[$i],$new."/".$d[$i]))
490  $err->raise("bro", "error renaming $old/$d[$i] -> $new/$d[$i]");
491  }
492  }
493  return true;
494  }
495 
496 
497  /* ----------------------------------------------------------------- */
498  /** Change les droits d'acces aux fichier de $d du dossier $R en $p
499  * @param string $R dossier dans lequel se trouve les fichiers renommer.
500  * @param array of string $old Ancien nom des fichiers
501  * @param array of string $new Nouveau nom des fichiers
502  * @param $verbose boolean shall we 'echo' what we did ?
503  * @return boolean TRUE si les fichiers ont t renomms, FALSE si une erreur s'est produite.
504  */
505  function ChangePermissions($R,$d,$perm,$verbose=false) {
506  global $err;
507  $absolute=$this->convertabsolute($R,0);
508  if (!$absolute) {
509  $err->raise("bro",_("File or folder name is incorrect"));
510  return false;
511  }
512  for ($i=0;$i<count($d);$i++) {
513  $d[$i]=ssla($d[$i]); // strip slashes if needed
514  if (!strpos($d[$i],"/")) { // caractre / interdit dans le nom du fichier
515  $m = fileperms($absolute."/". $d[$i]);
516 
517  // pour l'instant on se limite a "write" pour owner, puisque c'est le seul
518  // cas interessant compte tenu de la conf de Apache pour AlternC..
519  if ($perm[$i]['w']) {
520  $m = $m | 0220; // ug+w
521  } else {
522  $m = $m ^ 0222; // ugo-w
523  }
524  chmod($absolute."/".$d[$i], $m);
525  if ($verbose) {
526  echo "chmod " . sprintf('%o', $m) . " file, was " . sprintf('%o', fileperms($absolute."/". $d[$i])). " -- " . $perm[$i]['w'];
527  }
528  }
529  }
530 
531  return true;
532  }
533 
534 
535  /* ----------------------------------------------------------------- */
536  /** Recoit un champ file upload (Global) et le stocke dans le dossier $R
537  * Le champ file-upload originel doit s'appeler "userfile" et doit
538  * bien tre un fichier d'upload.
539  * @param string $R Dossier dans lequel on upload le fichier
540  * @returns the path where the file resides or false if upload failed
541  */
542  function UploadFile($R) {
543  global $_FILES,$err,$cuid,$action;
544  $absolute=$this->convertabsolute($R,0);
545  if (!$absolute) {
546  $err->raise("bro",_("File or folder name is incorrect"));
547  return false;
548  }
549  if (!strpos($_FILES['userfile']['name'],"/")) {
550  if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
551  if (!file_exists($absolute."/".$_FILES['userfile']['name'])) {
552  @touch($absolute."/".$_FILES['userfile']['name']);
553  }
554  if (@move_uploaded_file($_FILES['userfile']['tmp_name'], $absolute."/".$_FILES['userfile']['name'])) {
555  $action->fix_file($absolute."/".$_FILES['userfile']['name']);
556  return $absolute."/".$_FILES['userfile']['name'];
557  } else {
558  $err->raise("bro",_("Cannot create the requested file. Please check the permissions"));
559  return false;
560  }
561  } else {
562  // there was an error, raise it
563  $err->log("bro","uploadfile","Problem when uploading a file");
564  switch ( $_FILES['userfile']['error'] ) {
565  case UPLOAD_ERR_INI_SIZE:
566  $erstr=_("The uploaded file exceeds the max file size allowed");
567  break;
568  case UPLOAD_ERR_FORM_SIZE:
569  case UPLOAD_ERR_PARTIAL:
570  case UPLOAD_ERR_NO_FILE:
571  case UPLOAD_ERR_NO_TMP_DIR:
572  case UPLOAD_ERR_CANT_WRITE:
573  case UPLOAD_ERR_EXTENSION:
574  default:
575  $erstr=_("Undefined error ").$_FILES['userfile']['error'];
576  break;
577  }
578  $err->raise("bro",_("Error during the upload of the file: ").$erstr);
579  return false;
580  }
581  }
582  return $absolute."/".$_FILES['userfile']['name'];
583  }
584 
585 
586  /* ----------------------------------------------------------------- */
587  /**
588  * Extract an archive by using GNU and non-GNU tools
589  * @param string $file is the full or relative path to the archive
590  * @param string $dest is the path of the extract destination, the
591  * same directory as the archive by default
592  * @return boolean != 0 on error
593  */
594  function ExtractFile($file, $dest=null) {
595  global $err,$cuid,$mem,$action;
596  $file = $this->convertabsolute($file,0);
597  if (is_null($dest)) {
598  $dest = dirname($file);
599  } else {
600  $dest = $this->convertabsolute($dest,0);
601  }
602  if (!$file || !$dest) {
603  $err->raise("bro",_("File or folder name is incorrect"));
604  return 1;
605  }
606  $file = escapeshellarg($file);
607  $dest_to_fix = $dest;
608  $dest = escapeshellarg($dest);
609  #$dest_to_fix=str_replace(getuserpath(),'',$dest);
610 
611  // TODO new version of tar supports `tar xf ...` so there is no
612  // need to specify the compression format
613  exec("tar -xf $file -C $dest", $void, $ret);
614  if ($ret) {
615  exec("tar -xjf $file -C $dest", $void, $ret);
616  }
617  if ($ret) {
618  $cmd = "unzip -o $file -d $dest";
619  exec($cmd, $void, $ret);
620  }
621  if ($ret) {
622  $cmd = "gunzip $file";
623  exec($cmd, $void, $ret);
624  }
625  if ($ret) {
626  $err->raise("bro",_("I cannot find a way to extract the file %s, it is an unsupported compressed format"), $file);
627  }
628  // fix the perms of the extracted archive TODO: does it work???
629  $action->fix_dir($dest_to_fix);
630  return $ret;
631  }
632 
633 
634  /* ----------------------------------------------------------------- */
635  /** Copy many files from point A to point B
636  */
637  function CopyFile($d,$old,$new) {
638  global $err;
639  $old=$this->convertabsolute($old,0);
640  if (!$old) {
641  $err->raise("bro",_("File or folder name is incorrect"));
642  return false;
643  }
644  $new=$this->convertabsolute($new,0);
645  if (!$new) {
646  $err->raise("bro",_("File or folder name is incorrect"));
647  return false;
648  }
649  if ($old==$new) {
650  $err->raise("bro",_("You cannot move or copy a file to the same folder"));
651  return false;
652  }
653  for ($i=0;$i<count($d);$i++) {
654  $d[$i]=ssla($d[$i]); // strip slashes if needed
655  if (!strpos($d[$i],"/") && file_exists($old."/".$d[$i]) && !file_exists($new."/".$d[$i])) {
656  $this->CopyOneFile($old."/".$d[$i],$new);
657  }
658  }
659  return true;
660  }
661 
662 
663  /* ----------------------------------------------------------------- */
664  /**
665  * Copy a source to a destination by either copying recursively a
666  * directory or by downloading a file with a URL (only http:// is
667  * supported)
668  * @param string $src is the path or URL
669  * @param string $dest is the absolute path inside the users directory
670  * @return boolean false on error
671  *
672  * Note that we assume that the inputs have been convertabsolute()'d
673  */
674  function CopyOneFile($src, $dest) {
675  global $err;
676  $src = escapeshellarg($src);
677  $dest = escapeshellarg($dest);
678  exec("cp -Rpf $src $dest", $void, $ret);
679  if ($ret) {
680  $err->raise("bro","Errors happened while copying the source to destination. cp return value: %d", $ret);
681  return false;
682  }
683  return true;
684  }
685 
686 
687  /* ----------------------------------------------------------------- */
688  /** Affiche le chemin et les liens de la racine au dossier $path
689  * Affiche autant de liens HTML (anchor) que le chemin $path contient de
690  * niveaux de dossier. Chaque lien est associ la page web $action
691  * laquelle on ajoute le paramtre R=+Le nom du dossier courant.
692  * @param string $path Dossier vers lequel on trace le chemin
693  * @param string $action Page web de destination des liens
694  * @return string le code HTML ainsi obtenu.
695  */
696  function PathList($path,$action, $justparent=false) {
697  $path=$this->convertabsolute($path,1);
698  $a=explode("/",$path);
699  if (!is_array($a)) $a=array($a);
700  $c='';
701  $R='';
702  if ($justparent) {
703  return "<a href=\"$action?R=".urlencode($a[count($a)-2].'/')."\">&uarr;</a>";
704  }
705  for($i=0;$i<count($a);$i++) {
706  if ($a[$i]) {
707  $R.=$a[$i]."/";
708  $c.="<a href=\"$action?R=".urlencode($R)."\">".$a[$i]."</a>&nbsp;/&nbsp;";
709  }
710  }
711  return $c;
712  }
713 
714 
715  /* ----------------------------------------------------------------- */
716  /** Affiche le contenu d'un fichier pour un champ VALUE de textarea
717  * Affiche le contenu du fichier $file dans le dossier $R. Le contenu
718  * du fichier est reformat pour pouvoir entrer dans un champs TextArea
719  * @param string $R Dossier dans lequel on cherche le fichier
720  * @param string $file Fichier dont on souhaite obtenir le contenu.
721  * @return boolean retourne TRUE si le fichier a bien t mis sur
722  * echo, ou FALSE si une erreur est survenue.
723  */
724  function content($R,$file) {
725  global $err;
726  $absolute=$this->convertabsolute($R,0);
727  $std="";
728  if (!strpos($file,"/")) {
729  $absolute.="/".$file;
730  if (file_exists($absolute)) {
731  $std=str_replace("<","&lt;",str_replace("&","&amp;",file_get_contents($absolute)));
732  } else {
733  $err->raise("bro",_("Cannot read the requested file. Please check the permissions"));
734  return false;
735  }
736  } else {
737  $err->raise("bro",_("File or folder name is incorrect"));
738  return false;
739  }
740  return $std;
741  }
742 
743 
744  /** Internal cache for viewurl
745  */
746  var $cacheurl=array();
747 
748 
749  /* ----------------------------------------------------------------- */
750  // Return a browsing url if available.
751  // Maintain a url cache (positive AND negative(-) cache)
752  /* ----------------------------------------------------------------- */
753  /** Retourne une url de navigation pour le fichier $name du dossier $dir
754  * Les url sont mises en caches. Il se peut qu'aucune url n'existe, ou que
755  * celle-ci soit protge par un .htaccess.
756  * @param string $dir Dossier concern
757  * @param string $name Fichier dont on souhaite obtenir une URL
758  * @return string URL concerne, ou FALSE si aucune URL n'est disponible pour ce fichier
759  */
760  function viewurl($dir,$name) {
761  global $db,$cuid;
762  // Is it in cache ?
763  if (substr($dir,0,1)=="/") $dir=substr($dir,1);
764  if (substr($dir,-1)=="/") $dir=substr($dir,0,-1);
765  $dir=str_replace("%2F", "/", urlencode($dir));
766  $name=urlencode($name);
767  if (!@$this->cacheurl["d".$dir]) {
768  // On parcours $dir en remontant les /
769  $end=""; $beg=$dir; $tofind=true;
770  while ($tofind) {
771  $db->query("SELECT sub,domaine FROM sub_domaines WHERE compte='$cuid'
772  AND type=0 AND (valeur='/$beg/' or valeur='/$beg');");
773  $db->next_record();
774  if ($db->num_rows()) {
775  $tofind=false;
776  $this->cacheurl["d".$dir]="http://".$db->f("sub").ife($db->f("sub"),".").$db->f("domaine").$end;
777  }
778  if (!$beg && $tofind) {
779  $tofind=false;
780  $this->cacheurl["d".$dir]="-";
781  // We did not find it ;(
782  }
783  if (($tt=strrpos($beg,"/"))!==false) {
784  $end=substr($beg,$tt).$end; // = /topdir$end so $end starts AND ends with /
785  $beg=substr($beg,0,$tt);
786  } else {
787  $end="/".$beg.$end;
788  $beg="/";
789  }
790  }
791  }
792  if ($this->cacheurl["d".$dir] && $this->cacheurl["d".$dir]!="-") {
793  return $this->cacheurl["d".$dir]."/".$name;
794  } else {
795  return false;
796  }
797  }
798 
799 
800  /* ----------------------------------------------------------------- */
801  /**
802  */
803  function can_edit($dir,$name) {
804  global $mem,$err;
805  $absolute="$dir/$name";
806  $absolute=$this->convertabsolute($absolute,0);
807  if (!$absolute) {
808  $err->raise('bro',_("File not in authorized directory"));
809  include('foot.php');
810  exit;
811  }
812  $finfo = finfo_open(FILEINFO_MIME_TYPE);
813  $mime = finfo_file($finfo,$absolute);
814  if ( substr($mime,0,5)=="text/" || $mime == "application/x-empty" || $mime == "inode/x-empty") {
815  return true;
816  }
817  return false;
818  }
819 
820 
821  /* ----------------------------------------------------------------- */
822  /** Return a HTML snippet representing an extraction function only if the mimetype of $name is supported
823  */
824  function is_extractable($dir,$name) {
825  if ($parts = explode(".", $name)) {
826  $ext = array_pop($parts);
827  switch ($ext) {
828  case "gz":
829  case "bz":
830  case "bz2":
831  $ext = array_pop($parts) . $ext;
832  /* FALLTHROUGH */
833  case "tar.gz":
834  case "tar.bz":
835  case "tar.bz2":
836  case "tgz":
837  case "tbz":
838  case "tbz2":
839  case "tar":
840  case "Z":
841  case "zip":
842  return true;
843  }
844  }
845  return false;
846  }
847 
848  // return true if file is a sql dump (end with .sql or .sql.gz)
849  function is_sqlfile($dir,$name) {
850  if ($parts = explode(".", $name)) {
851  $ext = array_pop($parts);
852  $ext2 = array_pop($parts) . '.'.$ext;
853  if ( $ext=='sql' or $ext2=='sql.gz') return true;
854  }
855  return false;
856  }
857 
858 
859  /* ----------------------------------------------------------------- */
860  /**
861  */
862  function download_link($dir,$file){
863  global $err;
864  $err->log("bro","download_link");
865  header("Content-Disposition: attachment; filename=$file");
866  header("Content-Type: application/force-download");
867  header("Content-Transfer-Encoding: binary");
868  $this->content_send($dir,$file);
869  }
870 
871 
872  /* ------------------------------------------------------------------ */
873  /** Echoes the content of the file $file located in directory $R
874  */
875  function content_send($R,$file) {
876  global $err;
877  $absolute=$this->convertabsolute($R,0);
878  if (!strpos($file,"/")) {
879  $absolute.="/".$file;
880  if (file_exists($absolute)) {
881  readfile($absolute);
882  }
883  } else {
884  $err->raise("bro",_("File or folder name is incorrect"));
885  return false;
886  }
887  }
888 
889 
890  /* ----------------------------------------------------------------- */
891  /** Sauve le fichier $file dans le dossier $R avec pour contenu $texte
892  * le contenu est issu d'un textarea, et ne DOIT PAS contenir de \ ajouts
893  * automatiquement par addslashes
894  * @param string $file Nom du fichier sauver. S'il existe dj, il sera
895  * cras sans confirmation.
896  * @param string $R Dossier dans lequel on modifie le fichier
897  * @param string $texte texte du fichier sauver dedans
898  * @return boolean TRUE si tout s'est bien pass, FALSE si une erreur s'est produite.
899  */
900  function save($file,$R,$texte) {
901  global $err;
902  $absolute=$this->convertabsolute($R,0);
903  if (!strpos($file,"/")) {
904  $absolute.="/".$file;
905  if (file_exists($absolute)) {
906  if (! file_put_contents($absolute, $texte ) ) {
907  $err->raise("bro",_("Cannot edit the requested file. Please check the permissions"));
908  return false;
909  }
910  }
911  } else {
912  $err->raise("bro",_("File or folder name is incorrect"));
913  return false;
914  }
915  }
916 
917 
918  /* ----------------------------------------------------------------- */
919  /** Echo d'un flux .tar.Z contenant tout le contenu du dossier $dir
920  * @param string $dir dossier dumper, relatif la racine du compte du membre.
921  * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs
922  */
923  function DownloadZ($dir="") {
924  global $mem;
925  header("Content-Disposition: attachment; filename=".$mem->user["login"].".Z");
926  header("Content-Type: application/x-Z");
927  header("Content-Transfer-Encoding: binary");
928  $d=escapeshellarg(".".$this->convertabsolute($dir,1));
929  set_time_limit(0);
930  passthru("/bin/tar -cZ -C ".getuserpath()."/".$mem->user["login"]."/ $d");
931  }
932 
933 
934  /* ----------------------------------------------------------------- */
935  /** Echo d'un flux .tgz contenant tout le contenu du dossier $dir
936  * @param string $dir dossier dumper, relatif la racine du compte du membre.
937  * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs
938  */
939  function DownloadTGZ($dir="") {
940  global $mem;
941  header("Content-Disposition: attachment; filename=".$mem->user["login"].".tgz");
942  header("Content-Type: application/x-tgz");
943  header("Content-Transfer-Encoding: binary");
944  $d=escapeshellarg(".".$this->convertabsolute($dir,1));
945  set_time_limit(0);
946  passthru("/bin/tar -cz -C ".getuserpath()."/ $d");
947  }
948 
949 
950  /* ----------------------------------------------------------------- */
951  /** Echo d'un flux .tar.bz2 contenant tout le contenu du dossier $dir
952  * @param string $dir dossier dumper, relatif la racine du compte du membre.
953  * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs
954  */
955  function DownloadTBZ($dir="") {
956  global $mem;
957  header("Content-Disposition: attachment; filename=".$mem->user["login"].".tar.bz2");
958  header("Content-Type: application/x-bzip2");
959  header("Content-Transfer-Encoding: binary");
960  $d=escapeshellarg(".".$this->convertabsolute($dir,1));
961  set_time_limit(0);
962  passthru("/bin/tar -cj -C ".getuserpath()."/ $d");
963  }
964 
965 
966  /* ----------------------------------------------------------------- */
967  /** Echo d'un flux .ZIP contenant tout le contenu du dossier $dir
968  * @param string $dir dossier dumper, relatif la racine du compte du membre.
969  * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs
970  */
971  function DownloadZIP($dir="") {
972  global $mem;
973  header("Content-Disposition: attachment; filename=".$mem->user["login"].".zip");
974  header("Content-Type: application/x-zip");
975  header("Content-Transfer-Encoding: binary");
976  $d=escapeshellarg($this->convertabsolute($dir,0));
977  set_time_limit(0);
978  passthru("/usr/bin/zip -r - $d");
979  }
980 
981 
982  /* ----------------------------------------------------------------- */
983  /** Fonction de tri perso utilis par filelist.
984  * @access private
985  */
986  function _sort_filelist_name($a,$b) {
987  if ($a["type"] && !$b["type"]) return 1;
988  if ($b["type"] && !$a["type"]) return -1;
989  return $a["name"]>$b["name"];
990  }
991 
992 
993  /* ----------------------------------------------------------------- */
994  /** Efface $file et tous ses sous-dossiers s'il s'agit d'un dossier
995  * A UTILISER AVEC PRECAUTION !!!
996  * @param string $file Fichier ou dossier supprimer.
997  * @access private
998  */
999  function _delete($file) {
1000  // permet d'effacer de nombreux fichiers
1001  @set_time_limit(0);
1002  //chmod($file,0777);
1003  if (is_dir($file)) {
1004  $handle = opendir($file);
1005  while($filename = readdir($handle)) {
1006  if ($filename != "." && $filename != "..") {
1007  $this->_delete($file."/".$filename);
1008  }
1009  }
1010  closedir($handle);
1011  rmdir($file);
1012  } else {
1013  unlink($file);
1014  }
1015  }
1016 
1017 
1018  /*----------------------------------------------------------*/
1019  /** Function d'exportation de configuration appelé par la classe m_export via un hooks
1020  *Produit en sorti un tableau formatté ( pour le moment) en HTML
1021  */
1022  function alternc_export_conf() {
1023  global $db,$err;
1024  $err->log("bro","export_conf");
1025  $str="<table border=\"1\"><caption> Browser </caption>\n";
1026  $str=" <browser>\n";
1027  $pref=$this->GetPrefs();
1028 
1029  $i=1;
1030  foreach ($pref as $k=>$v) {
1031  if (($i % 2)==0){
1032  $str.=" <$k>$v</$k>\n";
1033  }
1034  $i++;
1035  }
1036  $str.=" </browser>\n";
1037 
1038  return $str;
1039  }
1040 
1041 
1042  /*----------------------------------------------------------*/
1043  /** Function d'exportation des données appelé par la classe m_export via un hooks
1044  *@param : le chemin destination du tarball produit.
1045  */
1046  function alternc_export_data($dir){
1047  global $mem,$err;
1048  $err->log("bro","export_data");
1049  $dir.="html/";
1050  if(!is_dir($dir)){
1051  if(!mkdir($dir))
1052  $err->raise("bro",_("Cannot create the requested directory. Please check the permissions"));
1053  }
1054  $timestamp=date("H:i:s");
1055 
1056  // relacher le lock global sinon ce download va geler alternc pour
1057  // tout le monde
1058  alternc_shutdown();
1059  if(exec("/bin/tar cvf - ".getuserpath()."/ | gzip -9c > ".$dir."/".$mem->user['login']."_html_".$timestamp.".tar.gz")){
1060  $err->log("bro","export_data_succes");
1061  }else{
1062  $err->log("bro","export_data_failed");
1063 
1064  }
1065 
1066  }
1067 
1069  return min(ini_get('post_max_size'), ini_get('upload_max_filesize'));
1070  }
1071 
1072 } /* Class Browser */
1073