source: alternc/trunk/bureau/class/m_bro.php @ 2624

Revision 2624, 33.6 KB checked in by benjamin, 3 years ago (diff)

Fixes #1107 : downloading a folder works indeed ! but yes, we had a file naming issue (zip or tar.bz2 were in fact zip or tar.bz2, but they were still named .tar.gz...)

Line 
1<?php
2/*
3 $Id: m_bro.php,v 1.15 2005/12/18 09:51:32 benjamin Exp $
4 ----------------------------------------------------------------------
5 LICENSE
6
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License (GPL)
9 as published by the Free Software Foundation; either version 2
10 of the License, or (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 To read the license please visit http://www.gnu.org/copyleft/gpl.html
18 ----------------------------------------------------------------------
19 Original Author of file:
20 Purpose of file:
21 ----------------------------------------------------------------------
22*/
23
24/* Add the mime type list */
25@include("mime.php");
26
27/**
28* Classe de gestion du navigateur de fichiers en ligne.
29*
30* Cette classe permet de gérer les fichiers, dossiers ...
31* d'un membre hébergé.<br />
32* Copyleft {@link http://alternc.net/ AlternC Team}
33*
34* @copyright    AlternC-Team 2002-11-01 http://alternc.net/
35*
36*/
37
38
39class m_bro {
40
41  /** Mode d'affichage des fichiers en colonne */
42  var $l_mode=array(0=>"1 column, detailed",1=>"2 columns, short",2=>"3 columns, short");
43
44  /** Mode de téléchargement d'un dossier compressé (zip,bz,tar,..) */
45  var $l_tgz=array(0=>"tgz (Linux)",1=>"tar.bz2 (Linux)",2=>"zip (Windows/Dos)",3=>"tar.Z (Unix)");
46
47  /** Faut-il afficher ou non les icones ? */
48  var $l_icons=array(0=>"No",1=>"Yes");
49
50  /** Que fait-on après la création d'un fichier ? */
51  var $l_createfile=array(0=>"Go back to the file manager",1=>"Edit the newly created file");
52
53  /** Cache des descriptions de fichier extraits de la base
54   * @access private
55   */
56  var $mime_desc=array();
57
58  /** Cache des icones extraits de la base
59   * @access private
60   */
61  var $mime_icon=array();
62
63  /** Cache des types mimes extraits de la base
64   * @access private
65   */
66  var $mime_type=array();
67
68  /** Choix des polices d'édition de fichiers */
69  var $l_editor_font=array("Arial, Helvetica, Sans-serif","Times, Bookman, Serif","Courier New, Courier, Fixed");
70
71  /** Choix des tailles de police d'édition de fichiers */
72  var $l_editor_size=array("18px","14px","12px","10px","8px","0.8em","0.9em","1em","1.1em","1.2em");
73
74  /* ----------------------------------------------------------------- */
75  /** Constructeur */
76  function m_bro() {
77  }
78
79  /* ----------------------------------------------------------------- */
80  /** Vérifie un dossier relatif au dossier de l'utilisateur courant
81   *
82   * @param string $dir Dossier (absolu que l'on souhaite vérifier
83   * @return string Retourne le nom du dossier vérifié, relatif au
84   * dossier de l'utilisateur courant, éventuellement corrigé.
85   * ou FALSE si le dossier n'est pas dans le dossier de l'utilisateur.
86   */
87  function convertabsolute($dir,$strip=1) {
88    global $mem;
89    $root=$this->get_user_root($mem->user["login"]);
90    // Sauvegarde du chemin de base.
91    $root_alternc = $root ;
92    // Passage du root en chemin réel (différent avec un lien)
93    $root=realpath($root) ;
94    // separer le chemin entre le repertoire et le fichier
95    $file = basename($dir);
96    $dir = dirname($dir);
97    $dir=realpath($root."/".$dir);
98    // verifier que le repertoire est dans le home de l'usgaer
99    if (substr($dir,0,strlen($root))!=$root) {
100      return false;
101    } 
102    // recomposer le chemin
103    $dir = $dir . '/' . $file;
104    if ($strip) {
105      $dir=substr($dir,strlen($root));
106    } else {
107      // si on ne strip pas, il faut enlever le chemin réel
108      // et mettre la racine d'alternc pour éviter les
109      // problèmes de lien depuis /var/alternc !
110      $dir=$root_alternc . substr($dir,strlen($root));
111    }
112    if (substr($dir,-1)=="/") {
113      return substr($dir,0,strlen($dir)-1);
114    } else
115      return $dir;
116  }
117
118  /** Retourne le chemin complet vers la racine du repertoire de l'utilisateur.
119   *  Returns the complete path to the root of the user's directory.
120   *
121   * @param string $login Username
122   * @return string Returns the complete path to the root of the user's directory.
123   */
124  function get_user_root($login) {
125    return "/var/alternc/html/".substr($login,0,1)."/".$login;
126  }
127
128  /** Retourne le chemin complet vers la racine du repertoire de l'utilisateur.
129   *  Returns the complete path to the root of the user's directory.
130   *
131   * @param string $uid User id.
132   * @return string Returns the complete path to the root of the user's directory.
133   */
134  function get_userid_root($uid) {
135    global $admin;
136
137    // FIXME [ML] Comment faire ca correctement?
138    // C'est utilise' dans class/m_dom.php quand un utilisateur ajoute un domaine dans son compte
139    // et nous devons savoir quel est le chemin complet vers la racine de son compte..
140
141    $old_enabled = $admin->enabled;
142    $admin->enabled = true;
143    $member = $admin->get($uid);
144    $admin->enabled = $old_enabled;
145
146    return $this->get_user_root($member['login']);
147  }
148
149  /* ----------------------------------------------------------------- */
150  /** Retourne un tableau contenant la liste des fichiers du dossier courant
151   * Ce tableau contient tous les paramètres des fichiers du dossier courant
152   * sous la forme d'un tableau indexé de tableaux associatifs comme suit :
153   * $a["name"]=nom du fichier / dossier
154   * $a["size"]=Taille totale du fichier / dossier + sous-dossier
155   * $a["date"]=Date de dernière modification
156   * $a["type"]=Type du fichier (1 pour fichier, 0 pour dossier)
157   * @param string $dir dossier relatif au dossier racine du compte du
158   * membre courant
159   * @return array le tableau contenant les fichiers de $dir, et
160   */
161  function filelist($dir="", $showdirsize = false) {
162    global $db,$cuid;
163    $db->query("UPDATE browser SET lastdir='$dir' WHERE uid='$cuid';");
164    $absolute=$this->convertabsolute($dir,0);
165    if ($dir = @opendir($absolute)) {
166      while (($file = readdir($dir)) !== false) {
167        if ($file!="." && $file!="..") {
168          $c[]=array("name"=>$file, "size"=>$this->fsize($absolute."/".$file, $showdirsize), "date"=>filemtime($absolute."/".$file), "type"=> (!is_dir($absolute."/".$file)) );
169        }
170      }
171      closedir($dir);
172    }
173    if (is_array($c)) {
174      usort ($c, array("m_bro","_sort_filelist_name"));
175      return $c;
176    } else {
177      return array();
178    }
179  }
180
181  /* ----------------------------------------------------------------- */
182  /** Retourne un tableau contenant les préférences de l'utilisateur courant
183   * Ce tableau aqssociatif contient les valeurs des champs de la table "browser"
184   * pour l'utilisateur courant.
185   * @return array Tableau des préférences de l'utilisateur courant.
186   */
187  function GetPrefs() {
188    global $db,$cuid;
189    $db->query("SELECT * FROM browser WHERE uid='$cuid';");
190    if ($db->num_rows()==0) {
191      $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');");
192      $db->query("SELECT * FROM browser WHERE uid='$cuid';");
193    }
194    $db->next_record();
195    return $db->Record;
196  }
197
198  /* ----------------------------------------------------------------- */
199  /** Modifie les préférences de l'utilisateur courant.
200   *
201   * @param integer $editsizex  Taille de l'éditeur (nombre de colonnes)
202   * @param integer $editsizey  Taille de l'éditeur (nombre de lignes)
203   * @param integer $listmode   Mode d'affichage de la liste des fichiers
204   * @param integer $showicons  Faut-il afficher / cacher les icones des fichiers
205   * @param integer $downfmt    Dans quel format faut-il télécharger les dossiers compressés
206   * @param integer $createfile Faut-il editer/revenir au browser après création d'un fichier
207   * @param integer $showtype Faut-il afficher le type mime des fichiers
208   * @param integer $editor_font  Quelle police faut-il utiliser pour l'éditeur
209   * @param integer $editor_size  Quelle taille de police faut-il utiliser pour l'éditeur
210   * @param integer $golastdir  Faut-il revenir à la racine ou au dernier dossier visité ?
211   * @return boolean TRUE
212   */
213  function SetPrefs($editsizex, $editsizey, $listmode, $showicons, $downfmt, $createfile, $showtype, $editor_font, $editor_size, $golastdir) {
214    global $db,$cuid;
215    $editsizex=intval($editsizex);      $editsizey=intval($editsizey);
216    $listmode=intval($listmode);        $showicons=intval($showicons);
217    $showtype=intval($showtype);        $downfmt=intval($downfmt);
218    $createfile=intval($createfile);    $golastdir=intval($golastdir);
219    $db->query("SELECT * FROM browser WHERE uid='$cuid';");
220    if ($db->num_rows()==0) {
221      $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);");
222    }
223    $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';");
224    return true;
225  }
226
227  /* ----------------------------------------------------------------- */
228  /** Retourne le nom du fichier icone associé au fichier donc le nom est $file
229   * <b>Note</b>: Les fichiers icones sont mis en cache sur la page courante.
230   * @param string $file Fichier dont on souhaite connaitre le fichier icone
231   * @return string Fichier icone correspondant.
232   */
233  function icon($file) {
234    global $bro_icon;
235    if (!strpos($file,".") && substr($file,0,1)!=".") {
236      return "file.png";
237    }
238    $t=explode(".",$file);
239    if (!is_array($t))
240      $ext=$t;
241    else
242      $ext=$t[count($t)-1];
243    // Now seek the extension
244    if (!$bro_icon[$ext]) {
245        return "file.png";
246    } else {
247        return $bro_icon[$ext].".png";
248    }
249  }
250
251  /* ----------------------------------------------------------------- */
252  /** Retourne le type mime associé au fichier donc le nom est $file
253   * <b>Note</b>: Les types mimes sont mis en cache sur la page courante.
254   * Le type mime est déterminé d'après l'extension du fichier.
255   * @param string $file Fichier dont on souhaite connaitre le type mime
256   * @return string Type mime / Sous type du fichier demandé
257   */
258  function mime($file) {
259    global $bro_type;
260    if (!strpos($file,".") && substr($file,0,1)!=".") {
261      return "File";
262    }
263    $t=explode(".",$file);
264    if (!is_array($t))
265      $ext=$t;
266    else
267      $ext=$t[count($t)-1];
268    // Now seek the extension
269    if (!$bro_type[$ext]) {
270        return "File";
271    } else {
272        return $bro_type[$ext];
273    }
274  }
275
276  /* ----------------------------------------------------------------- */
277  /** Retourne la taille du fichier $file
278   * si $file est un dossier, retourne la taille de ce dossier et de tous
279   * ses sous dossiers.
280   * @param string $file Fichier dont on souhaite connaitre la taille
281   * @param boolean $showdirsize recursively compute the directory size.
282   * @return integer Taille du fichier en octets.
283   */
284  function fsize($file, $showdirsize = false) {
285    if (is_dir($file)) {
286      if ($showdirsize) {
287        return $this->dirsize($file);
288      } else {
289        return "-";
290      }
291    } else {
292      return filesize($file);
293    }
294  }
295
296
297  /* ----------------------------------------------------------------- */
298  /** Returns the size of a directory, by adding all it's files sizes
299   * @param string $dir the directory whose size we want to compute
300   * @return integer the total size in bytes.
301   */
302  function dirsize($dir) {
303    $totalsize = 0;
304
305    if ($handle = opendir($dir)) {
306      while (false !== ($file = readdir($handle))) {
307        $nextpath = $dir . '/' . $file;
308
309        if ($file != '.' && $file != '..' && !is_link($nextpath)) {
310          if (is_dir($nextpath)) {
311            $totalsize += $this->dirsize($nextpath);
312          } elseif (is_file ($nextpath)) {
313            $totalsize += filesize($nextpath);
314          }
315        }
316      }
317      closedir($handle);
318    }
319    return $totalsize;
320  }
321
322  /* ----------------------------------------------------------------- */
323  /** Crée le dossier $file dans le dossier (parent) $dir
324   * @param string $dir dossier dans lequel on veut créer un sous-dossier
325   * @param string $file nom du dossier à créer
326   * @return boolean TRUE si le dossier a été créé, FALSE si une erreur s'est produite.
327   */
328  function CreateDir($dir,$file) {
329    global $db,$cuid,$err;
330    $file=ssla($file);
331    $absolute=$this->convertabsolute($dir."/".$file,0);
332    if ($absolute && !file_exists($absolute)) {
333      mkdir($absolute,00777);
334      $db->query("UPDATE browser SET crff=1 WHERE uid='$cuid';");
335      return true;
336    } else {
337      $err->raise("bro",1);
338      return false;
339    }
340  }
341
342
343  /* ----------------------------------------------------------------- */
344  /** Crée un fichier vide dans un dossier
345   * @param string $dir Dossier dans lequel on crée le nouveau fichier
346   * @param string $file Fichier que l'on souhaite créer.
347   * @return boolean TRUE si le dossier a été créé, FALSE si une erreur s'est produite.
348   */
349  function CreateFile($dir,$file) {
350    global $db,$err,$cuid;
351    $file=ssla($file);
352    $absolute=$this->convertabsolute($dir."/".$file,0);
353    if (!$absolute) {
354      $err->raise("bro",1);
355      return false;
356    }
357    if (!file_exists($absolute)) {
358      touch($absolute);
359    }
360    $db->query("UPDATE browser SET crff=0 WHERE uid='$cuid';");
361    return true;
362  }
363
364
365  /* ----------------------------------------------------------------- */
366  /** Efface les fichiers du tableau $file_list dans le dossier $R
367   * @param array $file_list Liste des fichiers à effacer.
368   * @param string $R Dossier dans lequel on efface les fichiers
369   * @return boolean TRUE si les fichiers ont été effacés, FALSE si une erreur s'est produite.
370   */
371  function DeleteFile($file_list,$R) {
372    global $err, $mem;
373    $root=realpath("/var/alternc/html/".substr($mem->user["login"],0,1)."/".$mem->user["login"]);
374    $absolute=$this->convertabsolute($R,0);
375    if (!$absolute && strpos($root,$absolute) === 0 && strlen($absolute) > (strlen($root)+1) ) {
376      $err->raise("bro",1);
377      return false;
378    }
379    for ($i=0;$i<count($file_list);$i++) {
380      $file_list[$i]=ssla($file_list[$i]);
381      if (!strpos($file_list[$i],"/") && file_exists($absolute."/".$file_list[$i])) { // Character / forbidden in a FILE name
382        $this->_delete($absolute."/".$file_list[$i]);
383      }
384    }
385    return true;
386  }
387
388
389  /* ----------------------------------------------------------------- */
390  /** Renomme les fichier de $old du dossier $R en $new
391   * @param string $R dossier dans lequel se trouve les fichiers à renommer.
392   * @param array of string $old Ancien nom des fichiers
393   * @param array of string $new Nouveau nom des fichiers
394   * @return boolean TRUE si les fichiers ont été renommés, FALSE si une erreur s'est produite.
395   */
396  function RenameFile($R,$old,$new) {
397    global $err;
398    $absolute=$this->convertabsolute($R,0);
399    if (!$absolute) {
400      $err->raise("bro",1);
401      return false;
402    }
403    $alea=".".time().rand(1000,9999);
404    for ($i=0;$i<count($old);$i++) {
405      $old[$i]=ssla($old[$i]); // strip slashes if needed
406      $new[$i]=ssla($new[$i]);
407      if (!strpos($old[$i],"/") && !strpos($new[$i],"/")) {  // caractère / interdit dans old ET dans new...
408        @rename($absolute."/".$old[$i],$absolute."/".$old[$i].$alea);
409      }
410    }
411    for ($i=0;$i<count($old);$i++) {
412      if (!strpos($old[$i],"/") && !strpos($new[$i],"/")) {  // caractère / interdit dans old ET dans new...
413        @rename($absolute."/".$old[$i].$alea,$absolute."/".$new[$i]);
414      }
415    }
416
417    return true;
418  }
419
420
421  /* ----------------------------------------------------------------- */
422  /** Déplace les fichier de $d du dossier $old vers $new
423   * @param array of string $d Liste des fichiers du dossier $old à déplacer
424   * @param string $old dossier dans lequel se trouve les fichiers à déplacer.
425   * @param string $new dossier vers lequel seront déplacés les fichiers.
426   * @return boolean TRUE si les fichiers ont été renommés, FALSE si une erreur s'est produite.
427   */
428  function MoveFile($d,$old,$new) {
429    global $err;
430    $old=$this->convertabsolute($old,0);
431    if (!$old) {
432      $err->raise("bro",1);
433      return false;
434    }
435
436    // FIXME: check that we don't have a huge security issue here ...
437    // If the destionation (new) doesn't have an absolute path, give it the prefix (old) from the first file found
438    if ($new[0] != '/') {
439      // Ex: settings.php will become /var/alternc/html/f/foo/www/example.org/drupal-6.10/sites/default/settings.php
440      $new = $old . '/' . $new;
441    } else {
442      $new = $this->convertabsolute($new,0);
443    }
444
445    if (!$new) {
446      $err->raise("bro",1);
447      return false;
448    }
449    if ($old==$new) {
450      $err->raise("bro",2);
451      return false;
452    }
453    for ($i=0;$i<count($d);$i++) {
454      $d[$i]=ssla($d[$i]); // strip slashes if needed
455      if (!strpos($d[$i],"/") && file_exists($old."/".$d[$i]) && !file_exists($new."/".$d[$i])) { 
456        @rename($old."/".$d[$i],$new."/".$d[$i]);
457      }
458    }
459    return true;
460  }
461
462  /* ----------------------------------------------------------------- */
463  /** Change les droits d'acces aux fichier de $d du dossier $R en $p
464   * @param string $R dossier dans lequel se trouve les fichiers à renommer.
465   * @param array of string $old Ancien nom des fichiers
466   * @param array of string $new Nouveau nom des fichiers
467   * @return boolean TRUE si les fichiers ont été renommés, FALSE si une erreur s'est produite.
468   */
469  function ChangePermissions($R,$d,$perm) {
470    global $err;
471    $absolute=$this->convertabsolute($R,0);
472    if (!$absolute) {
473      $err->raise("bro",1);
474      return false;
475    }
476    for ($i=0;$i<count($d);$i++) {
477      $d[$i]=ssla($d[$i]); // strip slashes if needed
478      if (!strpos($d[$i],"/")) {  // caractère / interdit dans le nom du fichier
479        // @rename($absolute."/".$old[$i],$absolute."/".$old[$i].$alea);
480        $m = fileperms($absolute."/". $d[$i]);
481
482        // pour l'instant on se limite a "write" pour owner, puisque c'est le seul
483        // cas interessant compte tenu de la conf de Apache pour AlternC..
484        if ($perm[$i]['w']) {
485          $m = $m | 128;
486        } else {
487          $m = $m ^ 128;
488        }
489        $m = $m | ($perm[$i]['w'] ? 128 : 0); // 0600
490        chmod($absolute."/".$d[$i], $m);
491        echo "chmod " . sprintf('%o', $m) . " file, was " . sprintf('%o', fileperms($absolute."/". $d[$i])). " -- " . $perm[$i]['w'];
492      }
493    }
494
495    return true;
496  }
497
498  /* ----------------------------------------------------------------- */
499  /** Recoit un champ file upload (Global) et le stocke dans le dossier $R
500   * Le champ file-upload originel doit s'appeler "userfile" et doit
501   * bien être un fichier d'upload.
502   * @param string $R Dossier dans lequel on upload le fichier
503   * @returns the path where the file resides or false if upload failed
504   */
505  function UploadFile($R) {
506    global $_FILES,$err;
507    $absolute=$this->convertabsolute($R,0);
508    if (!$absolute) {
509      $err->raise("bro",1);
510      return false;
511    }
512    if (!strpos($_FILES['userfile']['name'],"/")) {
513      if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
514        if (!file_exists($absolute."/".$_FILES['userfile']['name'])) {
515          touch($absolute."/".$_FILES['userfile']['name']);
516        }
517        move_uploaded_file($_FILES['userfile']['tmp_name'], $absolute."/".$_FILES['userfile']['name']);
518      } else {
519            $err->log("bro","uploadfile","Tentative d'attaque : ".$_FILES['userfile']['tmp_name']);
520        return false;
521      }
522    }
523    return $absolute."/".$_FILES['userfile']['name'];
524  }
525
526  /**
527   * Extract an archive by using GNU and non-GNU tools
528   * @param string $file is the full or relative path to the archive
529   * @param string $dest is the path of the extract destination, the
530   * same directory as the archive by default
531   * @return boolean != 0 on error
532   */
533  function ExtractFile($file, $dest=null)
534  {
535    global $err;
536    $file = $this->convertabsolute($file,0);
537    if (is_null($dest)) {
538      $dest = dirname($file);
539    } else {
540      $dest = $this->convertabsolute($dest,0);
541    }
542    if (!$file || !$dest) {
543      $err->raise("bro",1);
544      return 1;
545    }
546    $file = escapeshellarg($file);
547    $dest = escapeshellarg($dest);
548#TODO new version of tar supports `tar xf ...` so there is no
549#     need to specify the compression format
550    exec("tar -xzf $file -C $dest", $void, $ret);
551    if ($ret) {
552      #print "tgz extraction failed, moving on to tbz\n";
553      exec("tar -xjf $file -C $dest", $void, $ret);
554    }
555    if ($ret) {
556      $cmd = "unzip -o $file -d $dest";
557      #print "tbz extraction failed, moving on to zip: $cmd\n";
558      exec($cmd, $void, $ret);
559    }
560    if ($ret) {
561      $err->raise("bro","could not find a way to extract file %s, unsupported format?", $file);
562    }
563
564    return $ret;
565  }
566
567
568  /**
569   * Copy many files from point A to point B
570   */
571  function CopyFile($d,$old,$new) {
572    global $err;
573    $old=$this->convertabsolute($old,0);
574    if (!$old) {
575      $err->raise("bro",1);
576      return false;
577    }
578    $new=$this->convertabsolute($new,0);
579    if (!$new) {
580      $err->raise("bro",1);
581      return false;
582    }
583    if ($old==$new) {
584      $err->raise("bro",2);
585      return false;
586    }
587    for ($i=0;$i<count($d);$i++) {
588      $d[$i]=ssla($d[$i]); // strip slashes if needed
589      if (!strpos($d[$i],"/") && file_exists($old."/".$d[$i]) && !file_exists($new."/".$d[$i])) { 
590        $this->CopyOneFile($old."/".$d[$i],$new);
591      }
592    }
593    return true;
594  }
595
596  /**
597   * Copy a source to a destination by either copying recursively a
598   * directory or by downloading a file with a URL (only http:// is
599   * supported)
600   * @param string $src is the path or URL
601   * @param string $dest is the absolute path inside the users directory
602   * @return boolean false on error
603   *
604   * Note that we assume that the inputs have been convertabsolute()'d
605   */
606  function CopyOneFile($src, $dest)
607  {
608    global $err;
609
610    /*
611     * XXX: Disabled functionality until audit is completed
612     */
613    /*
614    if (substr($src, 0, 7) == "http://") {
615      $filename = basename($src);
616      $extractdir = tempnam("/tmp", "brouteur");
617      unlink($extractdir);
618      mkdir($extractdir);
619
620      if (!$http = @fopen($src, "rb")) {
621        // Try to get a handle on $http with fsockopen instead
622//FIXME we'd better use a real http getter function/class (such as Octopuce_Http_Client (ask Benjamin)
623        ereg('^http://([^/]+)(/.*)$', $src, $eregs);
624        $hostname = $eregs[1];
625        $path = $eregs[2];
626        $http = @fsockopen($hostname, 80);
627        @fputs($http, "GET $path HTTP/1.1\nHost: $hostname\n\n");
628      }
629      if ($http) {
630        // Save the bits
631        $f = fopen("$extractdir/$filename", "wb");
632        while (!feof($http)) {
633          $bin = fgets($http, 16384);
634          fwrite($f, $bin);
635//FIXME if (!trim($bin)) break;
636        }
637        fclose($f);
638        fclose($http);
639      } else {
640        // Dammit, try with wget than
641        exec("wget -q '$src' -O '$extractdir/$filename'", $void, $ret);
642        if ($ret) {
643          $error = _("Unable to download the web application's package.");
644          return false;
645        }
646      }
647
648      // Now extract that package
649      if (!brouteur_extract("$extractdir/$filename", $extractdir)) {
650        $error = _("Unable to extract the files");
651        return false;
652      }
653      unlink("$extractdir/$filename");
654
655      // Corrupt $src since we want to copy $extractdir/packagename
656      $hd = opendir($extractdir);
657      while ($file = readdir($hd)) {
658        if ($file != "." && $file != "..") {
659          $src = "$extractdir/$file";
660          break;
661        }
662      }
663    }
664    */
665
666    // Last step // Copy -R
667    $src = escapeshellarg($src);
668    $dest = escapeshellarg($dest);
669    exec("cp -Rpf $src $dest", $void, $ret);
670    if ($ret) {
671      $err->raise("bro","Errors happened while copying the source to destination. cp return value: %d", $ret);
672      return false;
673    }
674
675    return true;
676  }
677
678  /* ----------------------------------------------------------------- */
679  /** Affiche le chemin et les liens de la racine au dossier $path
680   * Affiche autant de liens HTML (anchor) que le chemin $path contient de
681   * niveaux de dossier. Chaque lien est associé à la page web $action
682   * à laquelle on ajoute le paramètre R=+Le nom du dossier courant.
683   * @param string $path Dossier vers lequel on trace le chemin
684   * @param string $action Page web de destination des liens
685   * @return string le code HTML ainsi obtenu.
686   */
687  function PathList($path,$action) {
688    $path=$this->convertabsolute($path,1);
689    $a=explode("/",$path);
690    if (!is_array($a)) $a=array($a);
691    for($i=0;$i<count($a);$i++) {
692      if ($a[$i]) {
693        $R.=$a[$i]."/";
694        $c.="<a href=\"$action?R=".urlencode($R)."\">".$a[$i]."</a>&nbsp;/&nbsp;";
695      }
696    }
697    return $c;
698  }
699
700  /* ----------------------------------------------------------------- */
701  /** Affiche le contenu d'un fichier pour un champ VALUE de textarea
702   * Affiche le contenu du fichier $file dans le dossier $R. Le contenu
703   * du fichier est reformaté pour pouvoir entrer dans un champs TextArea
704   * @param string $R Dossier dans lequel on cherche le fichier
705   * @param string $file Fichier dont on souhaite obtenir le contenu.
706   * @return boolean retourne TRUE si le fichier a bien été émis sur
707   * echo, ou FALSE si une erreur est survenue.
708   */
709  function content($R,$file) {
710    global $err;
711    $absolute=$this->convertabsolute($R,0);
712    if (!strpos($file,"/")) {
713      $absolute.="/".$file;
714      if (file_exists($absolute)) {
715        $content = @file($absolute);
716        for($i=0;$i<count($content);$i++) {
717          echo str_replace("<","&lt;",str_replace("&","&amp;",$content[$i]));
718        }
719      }
720    } else {
721      $err->raise("bro",1);
722      return false;
723    }
724  }
725
726  /** Cache des urls pour VIEW
727   * @access private
728   */
729  var $cacheurl=array();
730
731  // Return a browsing url if available.
732  // Maintain a url cache (positive AND negative(-) cache)
733  /* ----------------------------------------------------------------- */
734  /** Retourne une url de navigation pour le fichier $name du dossier $dir
735   * Les url sont mises en caches. Il se peut qu'aucune url n'existe, ou que
736   * celle-ci soit protégée par un .htaccess.
737   * @param string $dir Dossier concerné
738   * @param string $name Fichier dont on souhaite obtenir une URL
739   * @return string URL concernée, ou FALSE si aucune URL n'est disponible pour ce fichier
740   */
741  function viewurl($dir,$name) {
742    global $db,$cuid;
743    // Is it in cache ?
744    if (substr($dir,0,1)=="/") $dir=substr($dir,1);
745    if (substr($dir,-1)=="/") $dir=substr($dir,0,-1);
746    $dir=str_replace("%2F", "/", urlencode($dir));
747    $name=urlencode($name);
748    if (!$this->cacheurl["d".$dir]) {
749      // On parcours $dir en remontant les /
750      $end="";  $beg=$dir;      $tofind=true;
751      while ($tofind) {
752        $db->query("SELECT sub,domaine FROM sub_domaines WHERE compte='$cuid'
753                         AND type=0 AND (valeur='/$beg/' or valeur='/$beg');");
754        $db->next_record();
755        if ($db->num_rows()) {
756          $tofind=false;
757          $this->cacheurl["d".$dir]="http://".$db->f("sub").ife($db->f("sub"),".").$db->f("domaine").$end;
758        }
759        if (!$beg && $tofind) {
760          $tofind=false;
761          $this->cacheurl["d".$dir]="-";
762                                // We did not find it ;(
763        }
764        if (($tt=strrpos($beg,"/"))!==false) {
765          $end=substr($beg,$tt).$end; // = /topdir$end so $end starts AND ends with /
766          $beg=substr($beg,0,$tt);
767        } else {
768          $end="/".$beg.$end;
769          $beg="/";
770        }
771      }
772    }
773    if ($this->cacheurl["d".$dir] && $this->cacheurl["d".$dir]!="-") {
774      return $this->cacheurl["d".$dir]."/".$name;
775    } else {
776      return false;
777    }
778  }
779
780  /**
781   * Return a HTML snippet representing an extraction function only if the mimetype of $name is supported
782   */
783  function is_extractable($dir,$name) {
784    if ($parts = explode(".", $name)) {
785      $ext = array_pop($parts);
786      switch ($ext) {
787      case "gz":
788      case "bz":
789      case "bz2":
790        $ext = array_pop($parts) . $ext;
791        /* FALLTHROUGH */
792      case "tar.gz":
793      case "tar.bz":
794      case "tar.bz2":
795      case "tgz":
796      case "tbz":
797      case "tbz2":
798      case "tar":
799      case "Z":
800      case "zip":
801        return true;
802      }
803    }
804    return false;
805  }
806
807  function content_send($R,$file) {
808    global $err;
809    $absolute=$this->convertabsolute($R,0);
810    if (!strpos($file,"/")) {
811      $absolute.="/".$file;
812      if (file_exists($absolute)) {
813        $content = @file($absolute);
814        for($i=0;$i<count($content);$i++) {
815          echo stripslashes($content[$i]);
816        }
817      }
818    } else {
819      $err->raise("bro",1);
820      return false;
821    }
822  }
823
824  /* ----------------------------------------------------------------- */
825  /** Sauve le fichier $file dans le dossier $R avec pour contenu $texte
826   * le contenu est issu d'un textarea, et ne DOIT PAS contenir de \ ajoutés
827   * automatiquement par addslashes
828   * @param string $file Nom du fichier à sauver. S'il existe déjà, il sera
829   *  écrasé sans confirmation.
830   * @param string $R Dossier dans lequel on modifie le fichier
831   * @param string $texte texte du fichier à sauver dedans
832   * @return boolean TRUE si tout s'est bien passé, FALSE si une erreur s'est produite.
833   */
834  function save($file,$R,$texte) {
835    global $err;
836    $absolute=$this->convertabsolute($R,0);
837    if (!strpos($file,"/")) {
838      $absolute.="/".$file;
839      if (file_exists($absolute)) {
840        $f=@fopen($absolute,"wb");
841        if ($f) {
842          fputs($f,$texte,strlen($texte));
843          fclose($f);
844        }
845      }
846    } else {
847      $err->raise("bro",1);
848      return false;
849    }
850  }
851
852  /* ----------------------------------------------------------------- */
853  /** Echo d'un flux .tar.Z contenant tout le contenu du dossier $dir
854   * @param string $dir dossier à dumper, relatif à la racine du compte du membre.
855   * @return void NE RETOURNE RIEN, et il faut Quitter le script immédiatement après
856   */
857 function DownloadZ($dir="") {
858    global $mem;
859    header("Content-Disposition: attachment; filename=".$mem->user["login"].".Z");
860    header("Content-Type: application/x-Z");
861    header("Content-Transfer-Encoding: binary");
862    $d=escapeshellarg(".".$this->convertabsolute($dir,1));
863    set_time_limit(0);
864    passthru("/bin/tar -cZ -C /var/alternc/html/".substr($mem->user["login"],0,1)."/".$mem->user["login"]."/ $d");
865  }
866
867  /* ----------------------------------------------------------------- */
868  /** Echo d'un flux .tgz contenant tout le contenu du dossier $dir
869   * @param string $dir dossier à dumper, relatif à la racine du compte du membre.
870   * @return void NE RETOURNE RIEN, et il faut Quitter le script immédiatement après
871   */
872 function DownloadTGZ($dir="") {
873    global $mem;
874    header("Content-Disposition: attachment; filename=".$mem->user["login"].".tgz");
875    header("Content-Type: application/x-tgz");
876    header("Content-Transfer-Encoding: binary");
877    $d=escapeshellarg(".".$this->convertabsolute($dir,1));
878    set_time_limit(0);
879    passthru("/bin/tar -cz -C /var/alternc/html/".substr($mem->user["login"],0,1)."/".$mem->user["login"]."/ $d");
880  }
881
882
883  /* ----------------------------------------------------------------- */
884  /** Echo d'un flux .tar.bz2 contenant tout le contenu du dossier $dir
885   * @param string $dir dossier à dumper, relatif à la racine du compte du membre.
886   * @return void NE RETOURNE RIEN, et il faut Quitter le script immédiatement après
887   */
888 function DownloadTBZ($dir="") {
889    global $mem;
890    header("Content-Disposition: attachment; filename=".$mem->user["login"].".tar.bz2");
891    header("Content-Type: application/x-bzip2");
892    header("Content-Transfer-Encoding: binary");
893    $d=escapeshellarg(".".$this->convertabsolute($dir,1));
894    set_time_limit(0);
895    passthru("/bin/tar -cj -C /var/alternc/html/".substr($mem->user["login"],0,1)."/".$mem->user["login"]."/ $d");
896  }
897
898  /* ----------------------------------------------------------------- */
899  /** Echo d'un flux .ZIP contenant tout le contenu du dossier $dir
900   * @param string $dir dossier à dumper, relatif à la racine du compte du membre.
901   * @return void NE RETOURNE RIEN, et il faut Quitter le script immédiatement après
902   */
903 function DownloadZIP($dir="") {
904    global $mem;
905    header("Content-Disposition: attachment; filename=".$mem->user["login"].".zip");
906    header("Content-Type: application/x-zip");
907    header("Content-Transfer-Encoding: binary");
908    $d=escapeshellarg($this->convertabsolute($dir,0));
909    set_time_limit(0);
910    passthru("/usr/bin/zip -r - $d");
911  }
912
913  /* ----------------------------------------------------------------- */
914  /** Fonction de tri perso utilisé par filelist.
915   * @access private
916   */
917  function _sort_filelist_name($a,$b) {
918    if ($a["type"] && !$b["type"]) return 1;
919    if ($b["type"] && !$a["type"]) return -1;
920    return $a["name"]>$b["name"];
921  }
922
923  /* ----------------------------------------------------------------- */
924  /** Efface $file et tous ses sous-dossiers s'il s'agit d'un dossier
925   * A UTILISER AVEC PRECAUTION !!!
926   * @param string $file Fichier ou dossier à supprimer.
927   * @access private
928   */
929  function _delete($file) {
930    // permet d'effacer de nombreux fichiers
931    @set_time_limit(0);
932    //chmod($file,0777);
933    if (is_dir($file)) {
934      $handle = opendir($file);
935      while($filename = readdir($handle)) {
936        if ($filename != "." && $filename != "..") {
937          $this->_delete($file."/".$filename);
938        }
939      }
940      closedir($handle);
941      rmdir($file);
942    } else {
943      unlink($file);
944    }
945  }
946
947
948  /* ----------------------------------------------------------------- */
949  /**
950   * Exporte toutes les informations ftp du compte AlternC
951   * @access private
952   * EXPERIMENTAL 'sid' function ;)
953   */
954  function alternc_export() {
955    global $db,$err;
956    $err->log("bro","export");
957    $str="<bro>\n";
958    $pref=$this->GetPrefs();
959    foreach ($pref as $k=>$v) {
960      $str.="  <pref>\n";
961      $str.="    <".$k.">".xml_entities($v)."</".$k.">\n";
962      $str.="  </pref>\n";
963    }
964    $str.="</bro>\n";
965   
966    return $str;
967  }
968
969
970} /* Classe BROUTEUR */
971
972?>
Note: See TracBrowser for help on using the repository browser.