Subversion Repositories Applications.projet

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 ddelon 1
<?php
2
/*
3
attach.class.php
4
Code original de ce fichier : Eric FELDSTEIN
5
Copyright (c) 2002, Hendrik Mans <hendrik@mans.de>
6
Copyright 2002, 2003 David DELON
7
Copyright 2002, 2003 Charles NEPOTE
8
Copyright  2003,2004  Eric FELDSTEIN
9
Copyright  2003  Jean-Pascal MILCENT
10
All rights reserved.
11
Redistribution and use in source and binary forms, with or without
12
modification, are permitted provided that the following conditions
13
are met:
14
1. Redistributions of source code must retain the above copyright
15
notice, this list of conditions and the following disclaimer.
16
2. Redistributions in binary form must reproduce the above copyright
17
notice, this list of conditions and the following disclaimer in the
18
documentation and/or other materials provided with the distribution.
19
3. The name of the author may not be used to endorse or promote products
20
derived from this software without specific prior written permission.
21
 
22
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
*/
33
# Classe de gestion de l'action {{attach}}
34
# voir actions/attach.php ppour la documentation
35
# copyrigth Eric Feldstein 2003-2004
36
 
37
class attach {
38
	var $wiki = '';					//objet wiki courant
39
   var $attachConfig = array();	//configuration de l'action
40
   var $file = '';					//nom du fichier
41
   var $desc = '';					//description du fichier
42
   var $link = '';					//url de lien (image sensible)
43
   var $isPicture = 0;				//indique si c'est une image
44
   var $classes = '';				//classe pour afficher une image
45
   var $attachErr = '';				//message d'erreur
46
   var $pageId = 0;					//identifiant de la page
47
   var $isSafeMode = false;		//indicateur du safe mode de PHP
48
   /**
49
   * Constructeur. Met les valeurs par defaut aux paramètres de configuration
50
   */
51
	function attach(&$wiki){
52
   	$this->wiki = $wiki;
53
		$this->attachConfig = $this->wiki->GetConfigValue("attach_config");
54
		if (empty($this->attachConfig["ext_images"])) $this->attachConfig["ext_images"] = "gif|jpeg|png|jpg";
55
		if (empty($this->attachConfig["ext_script"])) $this->attachConfig["ext_script"] = "php|php3|asp|asx|vb|vbs|js";
56
		if (empty($this->attachConfig['upload_path'])) $this->attachConfig['upload_path'] = 'files';
57
		if (empty($this->attachConfig['update_symbole'])) $this->attachConfig['update_symbole'] = '*';
58
		if (empty($this->attachConfig['max_file_size'])) $this->attachConfig['max_file_size'] = 1024*100;	//100ko max
59
		if (empty($this->attachConfig['fmDelete_symbole'])) $this->attachConfig['fmDelete_symbole'] = 'Supr';
60
		if (empty($this->attachConfig['fmRestore_symbole'])) $this->attachConfig['fmRestore_symbole'] = 'Rest';
61
		if (empty($this->attachConfig['fmTrash_symbole'])) $this->attachConfig['fmTrash_symbole'] = 'Poubelle';
62
		$this->isSafeMode = ini_get("safe_mode");
63
	}
64
/******************************************************************************
65
*	FONCTIONS UTILES
66
*******************************************************************************/
67
	/**
68
	* Création d'une suite de répertoires récursivement
69
	*/
70
	function mkdir_recursif ($dir) {
71
		if (strlen($dir) == 0) return 0;
72
		if (is_dir($dir)) return 1;
73
		elseif (dirname($dir) == $dir) return 1;
74
		return ($this->mkdir_recursif(dirname($dir)) and mkdir($dir,0755));
75
	}
76
	/**
77
	* Renvois le chemin du script
78
	*/
79
	function GetScriptPath () {
80
		if (preg_match("/.(php)$/i",$_SERVER["PHP_SELF"])){
81
			$a = explode('/',$_SERVER["PHP_SELF"]);
82
			$a[count($a)-1] = '';
83
			$path = implode('/',$a);
84
		}else{
85
			$path = $_SERVER["PHP_SELF"];
86
		}
87
		return !empty($_SERVER["HTTP_HOST"])? 'http://'.$_SERVER["HTTP_HOST"].$path : 'http://'.$_SERVER["SERVER_NAME"].$path ;
88
	}
89
	/**
90
	* Calcul le repertoire d'upload en fonction du safe_mode
91
	*/
92
	function GetUploadPath(){
93
		if ($this->isSafeMode) {
94
			$path = $this->attachConfig['upload_path'];
95
		}else{
96
         $path = $this->attachConfig['upload_path'].'/'.$this->wiki->GetPageTag();
97
			if (! is_dir($path)) $this->mkdir_recursif($path);
98
		}
99
		return $path;
100
	}
101
	/**
102
	* Calcule le nom complet du fichier attaché en fonction du safe_mode, du nom et de la date de
103
	* revision la page courante.
104
	* Le nom du fichier "mon fichier.ext" attache à la page "LaPageWiki"sera :
105
	*  mon_fichier_datepage_update.ext
106
	*     update : date de derniere mise a jour du fichier
107
	*     datepage : date de revision de la page à laquelle le fichier a ete lié/mis a jour
108
	*  Si le fichier n'est pas une image un '_' est ajoute : mon_fichier_datepage_update.ext_
109
	*  Selon la valeur de safe_mode :
110
	*  safe_mode = on : 	LaPageWiki_mon_fichier_datepage_update.ext_
111
	*  safe_mode = off: 	LaPageWiki/mon_fichier_datepage_update.ext_ avec "LaPageWiki" un sous-repertoire du répertoire upload
112
	*/
113
	function GetFullFilename($newName = false){
114
		$pagedate = $this->convertDate($this->wiki->page['time']);
115
		//decompose le nom du fichier en nom+extension
116
		if (preg_match('`^(.*)\.(.*)$`', str_replace(' ','_',$this->file), $match)){
117
			list(,$file['name'],$file['ext'])=$match;
118
			if(!$this->isPicture()) $file['ext'] .= '_';
119
		}else{
120
			return false;
121
		}
122
		//recuperation du chemin d'upload
123
		$path = $this->GetUploadPath($this->isSafeMode);
124
		//generation du nom ou recherche de fichier ?
125
		if ($newName){
126
			$full_file_name = $file['name'].'_'.$pagedate.'_'.$this->getDate().'.'.$file['ext'];
127
			if($this->isSafeMode){
128
				$full_file_name = $path.'/'.$this->wiki->GetPageTag().'_'.$full_file_name;
129
			}else{
130
				$full_file_name = $path.'/'.$full_file_name;
131
			}
132
		}else{
133
			//recherche du fichier
134
			if($this->isSafeMode){
135
				//TODO Recherche dans le cas ou safe_mode=on
136
				$searchPattern = '`^'.$this->wiki->GetPageTag().'_'.$file['name'].'_\d{14}_\d{14}\.'.$file['ext'].'$`';
137
			}else{
138
				$searchPattern = '`^'.$file['name'].'_\d{14}_\d{14}\.'.$file['ext'].'$`';
139
			}
140
			$files = $this->searchFiles($searchPattern,$path);
141
 
142
			$unedate = 0;
143
			foreach ($files as $file){
144
				//recherche du fichier qui une datepage <= a la date de la page
145
				if($file['datepage']<=$pagedate){
146
					//puis qui a une dateupload la plus grande
147
					if ($file['dateupload']>$unedate){
148
						$theFile = $file;
149
						$unedate = $file['dateupload'];
150
					}
151
				}
152
			}
153
			if (is_array($theFile)){
154
				$full_file_name = $path.'/'.$theFile['realname'];
155
			}
156
		}
157
		return $full_file_name;
158
	}
159
	/**
160
	* Test si le fichier est une image
161
	*/
162
	function isPicture(){
163
		return preg_match("/.(".$this->attachConfig["ext_images"].")$/i",$this->file)==1;
164
	}
165
	/**
166
	* Renvoie la date courante au format utilise par les fichiers
167
	*/
168
	function getDate(){
169
		return date('YmdHis');
170
	}
171
	/**
172
	* convertie une date yyyy-mm-dd hh:mm:ss au format yyyymmddhhmmss
173
	*/
174
	function convertDate($date){
175
		$date = str_replace(' ','', $date);
176
		$date = str_replace(':','', $date);
177
		return str_replace('-','', $date);
178
	}
179
	/**
180
	* Parse une date au format yyyymmddhhmmss et renvoie un tableau assiatif
181
	*/
182
	function parseDate($sDate){
183
		$pattern = '`^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$`';
184
		$res = '';
185
		if (preg_match($pattern, $sDate, $m)){
186
			//list(,$res['year'],$res['month'],$res['day'],$res['hour'],$res['min'],$res['sec'])=$m;
187
			$res = $m[1].'-'.$m[2].'-'.$m[3].' '.$m[4].':'.$m[5].':'.$m[6];
188
		}
189
		return ($res?$res:false);
190
	}
191
	/**
192
	* Decode un nom long de fichier
193
	*/
194
	function decodeLongFilename($filename){
195
		$afile = array();
196
		$afile['realname'] = basename($filename);
197
		$afile['size'] = filesize($filename);
198
		$afile['path'] = dirname($filename);
199
		if(preg_match('`^(.*)_(\d{14})_(\d{14})\.(.*)(trash\d{14})?$`', $afile['realname'], $m)){
200
			$afile['name'] = $m[1];
201
			//suppression du nom de la page si safe_mode=on
202
			if ($this->isSafeMode){
203
				$afile['name'] = preg_replace('`^('.$this->wiki->tag.')_(.*)$`i', '$2', $afile['name']);
204
			}
205
			$afile['datepage'] = $m[2];
206
			$afile['dateupload'] = $m[3];
207
			$afile['trashdate'] = preg_replace('`(.*)trash(\d{14})`', '$2', $m[4]);
208
			//suppression de trashxxxxxxxxxxxxxx eventuel
209
			$afile['ext'] = preg_replace('`^(.*)(trash\d{14})$`', '$1', $m[4]);
210
			$afile['ext'] = rtrim($afile['ext'],'_');
211
			//$afile['ext'] = rtrim($m[4],'_');
212
		}
213
		return $afile;
214
	}
215
	/**
216
	* Renvois un tableau des fichiers correspondant au pattern. Chaque element du tableau est un
217
	* tableau associatif contenant les informations sur le fichier
218
	*/
219
	function searchFiles($filepattern,$start_dir){
220
		$files_matched = array();
221
		$start_dir = rtrim($start_dir,'\/');
222
		$fh = opendir($start_dir);
223
		while (($file = readdir($fh)) !== false) {
224
			if (strcmp($file, '.')==0 || strcmp($file, '..')==0 || is_dir($file)) continue;
225
			if (preg_match($filepattern, $file)){
226
				$files_matched[] = $this->decodeLongFilename($start_dir.'/'.$file);
227
			}
228
		}
229
		return $files_matched;
230
	}
231
/******************************************************************************
232
*	FONCTIONS D'ATTACHEMENTS
233
*******************************************************************************/
234
	/**
235
	* Test les paramètres passé à l'action
236
	*/
237
	function CheckParams(){
238
		//recuperation des parametres necessaire
239
		$this->file = $this->wiki->GetParameter("attachfile");
240
		if (empty($this->file)) $this->file = $this->wiki->GetParameter("file");
241
		$this->desc = $this->wiki->GetParameter("attachdesc");
242
		if (empty($this->desc)) $this->desc = $this->wiki->GetParameter("desc");
243
		$this->link = $this->wiki->GetParameter("attachlink");//url de lien - uniquement si c'est une image
244
		if (empty($this->link)) $this->link = $this->wiki->GetParameter("link");
245
		//test de validité des parametres
246
		if (empty($this->file)){
247
			$this->attachErr = $this->wiki->Format("//action attach : paramètre **file** manquant//---");
248
		}
249
		if ($this->isPicture() && empty($this->desc)){
250
			$this->attachErr .= $this->wiki->Format("//action attach : paramètre **desc** obligatoire pour une image//---");
251
		}
252
		if ($this->wiki->GetParameter("class")) {
253
   		$array_classes = explode(" ", $this->wiki->GetParameter("class"));
254
   		foreach ($array_classes as $c) { $this->classes = $this->classes . "attach_" . $c . " "; }
255
   		$this->classes = trim($this->classes);
256
		}
257
	}
258
	/**
259
	* Affiche le fichier lié comme une image
260
	*/
261
	function showAsImage($fullFilename){
262
		//c'est une image : balise <IMG..../>
263
		$img =	"<img src=\"".$this->GetScriptPath().$fullFilename."\" ".
264
					"alt=\"".$this->desc.($this->link?"\nLien vers: $this->link":"")."\" />";
265
		//test si c'est une image sensible
266
		if(!empty($this->link)){
267
			//c'est une image sensible
268
			//test si le lien est un lien interwiki
269
			if (preg_match("/^([A-Z][A-Z,a-z]+)[:]([A-Z,a-z,0-9]*)$/s", $this->link, $matches))
270
			{  //modifie $link pour être un lien vers un autre wiki
271
				$this->link = $this->wiki->GetInterWikiUrl($matches[1], $matches[2]);
272
			}
273
			//calcule du lien
274
			$output = $this->wiki->Format('[['.$this->link." $this->file]]");
275
			$output = eregi_replace(">$this->file<",">$img<",$output);//insertion du tag <img...> dans le lien
276
		}else{
277
			//ce n'est pas une image sensible
278
			$output = $img;
279
		}
280
		$output = ($this->classes?"<span class=\"$this->classes\">$output</span>":$output);
281
		echo $output;
282
		$this->showUpdateLink();
283
	}
284
	/**
285
	* Affiche le fichier lié comme un lien
286
	*/
287
	function showAsLink($fullFilename){
288
		$url = $this->wiki->href("download",$this->wiki->GetPageTag(),"file=$this->file");
289
		echo '<a href="'.$url.'">'.($this->desc?$this->desc:$this->file)."</a>";
290
		$this->showUpdateLink();
291
	}
292
	/**
293
	* Affiche le lien de mise à jour
294
	*/
295
	function showUpdateLink(){
296
		echo	" <a href=\"".
297
				$this->wiki->href("upload",$this->wiki->GetPageTag(),"file=$this->file").
298
				"\" title='Mise à jour'>".$this->attachConfig['update_symbole']."</a>";
299
	}
300
	/**
301
	* Affiche un liens comme un fichier inexistant
302
	*/
303
	function showFileNotExits(){
304
		echo $this->file."<a href=\"".$this->wiki->href("upload",$this->wiki->GetPageTag(),"file=$this->file")."\">?</a>";
305
	}
306
	/**
307
	* Affiche l'attachement
308
	*/
309
	function doAttach(){
310
		$this->CheckParams();
311
		if ($this->attachErr) {
312
			echo $this->attachErr;
313
			return;
314
		}
315
		$fullFilename = $this->GetFullFilename();
316
		//test d'existance du fichier
317
		if((!file_exists($fullFilename))||($fullFilename=='')){
318
			$this->showFileNotExits();
319
			return;
320
		}
321
      //le fichier existe : affichage en fonction du type
322
      if($this->isPicture()){
323
      	$this->showAsImage($fullFilename);
324
      }else{
325
      	$this->showAsLink($fullFilename);
326
      }
327
	}
328
/******************************************************************************
329
*	FONTIONS D'UPLOAD DE FICHIERS
330
*******************************************************************************/
331
	/**
332
	* Traitement des uploads
333
	*/
334
	function doUpload(){
335
		$HasAccessWrite=$this->wiki->HasAccess("write");
336
		if ($HasAccessWrite){
337
         switch ($_SERVER["REQUEST_METHOD"]) {
338
         	case 'GET' : $this->showUploadForm(); break;
339
         	case 'POST': $this->performUpload(); break;
340
         	default : echo $this->wiki->Format("//Methode de requete invalide//---");
341
			}
342
		}else{
343
			echo $this->wiki->Format("//Vous n'avez pas l'accès en écriture à cette page//---");
344
			echo $this->wiki->Format("Retour à la page ".$this->wiki->GetPageTag());
345
		}
346
	}
347
	/**
348
	* Formulaire d'upload
349
	*/
350
	function showUploadForm(){
351
		echo $this->wiki->Format("====Formulaire d'envois de fichier====\n---");
352
		$this->file = $_GET['file'];
353
		echo 	$this->wiki->Format("**Envois du fichier $this->file :**\n")
354
				."<form enctype=\"multipart/form-data\" name=\"frmUpload\" method=\"POST\" action=\"".$_SERVER["PHP_SELF"]."\">\n"
355
				."	<input type=\"hidden\" name=\"wiki\" value=\"".$this->wiki->GetPageTag()."/upload\" />\n"
356
				."	<input TYPE=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"".$this->attachConfig['max_file_size']."\" />\n"
357
				."	<input type=\"hidden\" name=\"file\" value=\"$this->file\" />\n"
358
				."	<input type=\"file\" name=\"upFile\" size=\"50\" /><br />\n"
359
				."	<input type=\"submit\" value=\"Envoyer\" />\n"
360
				."</form>\n";
361
	}
362
	/**
363
	* Execute l'upload
364
	*/
365
	function performUpload(){
366
		$this->file = $_POST['file'];
367
 
368
		$destFile = $this->GetFullFilename(true);	//nom du fichier destination
369
		//test de la taille du fichier recu
370
		if($_FILES['upFile']['error']==0){
371
			$size = filesize($_FILES['upFile']['tmp_name']);
372
			if ($size > $this->attachConfig['max_file_size']){
373
				$_FILES['upFile']['error']=2;
374
			}
375
		}
376
		switch ($_FILES['upFile']['error']){
377
			case 0:
378
				$srcFile = $_FILES['upFile']['tmp_name'];
379
				if (move_uploaded_file($srcFile,$destFile)){
380
					chmod($destFile,0644);
381
					header("Location: ".$this->wiki->href("",$this->wiki->GetPageTag(),""));
382
				}else{
383
					echo $this->wiki->Format("//Erreur lors du déplacement du fichier temporaire//---");
384
				}
385
				break;
386
			case 1:
387
				echo $this->wiki->Format("//Le fichier téléchargé excède la taille de upload_max_filesize, configuré dans le php.ini.//---");
388
				break;
389
			case 2:
390
				echo $this->wiki->Format("//Le fichier téléchargé excède la taille de MAX_FILE_SIZE, qui a été spécifiée dans le formulaire HTML.//---");
391
				break;
392
			case 3:
393
				echo $this->wiki->Format("//Le fichier n'a été que partiellement téléchargé.//---");
394
				break;
395
			case 4:
396
				echo $this->wiki->Format("//Aucun fichier n'a été téléchargé.//---");
397
				break;
398
		}
399
		echo $this->wiki->Format("Retour à la page ".$this->wiki->GetPageTag());
400
	}
401
/******************************************************************************
402
*	FUNCTIONS DE DOWNLOAD DE FICHIERS
403
*******************************************************************************/
404
	function doDownload(){
405
		$this->file = $_GET['file'];
406
		$fullFilename = $this->GetUploadPath().'/'.$this->file;
407
		if(!file_exists($fullFilename)){
408
			$fullFilename = $this->GetFullFilename();
409
			$dlFilename = $this->file;
410
			$size = filesize($fullFilename);
411
		}else{
412
			$file = $this->decodeLongFilename($fullFilename);
413
			$size = $file['size'];
414
			$dlFilename =$file['name'].'.'.$file['ext'];
415
		}
416
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
417
        header("Content-type: application/force-download");
418
        header('Pragma: public');
419
        header("Pragma: no-cache");// HTTP/1.0
420
        header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
421
        header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
422
        header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
423
        header('Content-Transfer-Encoding: none');
424
        header('Content-Type: application/octet-stream; name="' . $dlFilename . '"'); //This should work for the rest
425
        header('Content-Type: application/octetstream; name="' . $dlFilename . '"'); //This should work for IE & Opera
426
        header('Content-Type: application/download; name="' . $dlFilename . '"'); //This should work for IE & Opera
427
        header('Content-Disposition: attachment; filename="'.$dlFilename.'"');
428
        header("Content-Description: File Transfer");
429
        header("Content-length: $size".'bytes');
430
		readfile($fullFilename);
431
	}
432
/******************************************************************************
433
*	FONTIONS DU FILEMANAGER
434
*******************************************************************************/
435
	function doFileManager(){
436
		$do = $_GET['do']?$_GET['do']:'';
437
		switch ($do){
438
			case 'restore' :
439
				$this->fmRestore();
440
				$this->fmShow(true);
441
				break;
442
			case 'erase' :
443
				$this->fmErase();
444
				$this->fmShow(true);
445
				break;
446
			case 'del' :
447
				$this->fmDelete();
448
				$this->fmShow();
449
				break;
450
			case 'trash' :
451
				$this->fmShow(true); break;
452
			case 'emptytrash' :
453
				$this->fmEmptyTrash();	//pas de break car apres un emptytrash => retour au gestionnaire
454
			default :
455
				$this->fmShow();
456
		}
457
	}
458
	/**
459
	* Affiche la liste des fichiers
460
	*/
461
	function fmShow($trash=false){
462
		$fmTitlePage = $this->wiki->Format("====Gestion des fichiers attachés à  la page ".$this->wiki->tag."====\n---");
463
		if($trash){
464
			//Avertissement
465
			$fmTitlePage .= '<div class="prev_alert">Les fichiers effacés sur cette page le sont définitivement</div>';
466
			//Pied du tableau
467
			$url = $this->wiki->Link($this->wiki->tag,'filemanager','Gestion des fichiers');
468
      	$fmFootTable =	'	<tfoot>'."\n".
469
      						'		<tr>'."\n".
470
      						'			<td colspan="6">'.$url.'</td>'."\n";
471
			$url = $this->wiki->Link($this->wiki->tag,'filemanager&do=emptytrash','Vider la poubelle');
472
      	$fmFootTable.=	'			<td>'.$url.'</td>'."\n".
473
      						'		</tr>'."\n".
474
      						'	</tfoot>'."\n";
475
		}else{
476
			//pied du tableau
477
         $url = '<a href="'.$this->wiki->href('filemanager',$this->wiki->GetPageTag(),'do=trash').'" title="Poubelle">'.$this->attachConfig['fmTrash_symbole']."</a>";
478
      	$fmFootTable =	'	<tfoot>'."\n".
479
      						'		<tr>'."\n".
480
      						'			<td colspan="6">'.$url.'</td>'."\n".
481
      						'		</tr>'."\n".
482
      						'	</tfoot>'."\n";
483
		}
484
		//entete du tableau
485
		$fmHeadTable = '	<thead>'."\n".
486
							'		<tr>'."\n".
487
							'			<td>&nbsp;</td>'."\n".
488
							'			<td>Nom du fichier</td>'."\n".
489
							'			<td>Nom réel du fichier</td>'."\n".
490
							'			<td>Taille</td>'."\n".
491
							'			<td>Révision de la page</td>'."\n".
492
							'			<td>Révison du fichier</td>'."\n";
493
		if($trash){
494
         $fmHeadTable.= '			<td>Suppression</td>'."\n";
495
		}
496
		$fmHeadTable.= '		</tr>'."\n".
497
							'	</thead>'."\n";
498
		//corps du tableau
499
		$files = $this->fmGetFiles($trash);
500
  		$files = $this->sortByNameRevFile($files);
501
 
502
		$fmBodyTable =	'	<tbody>'."\n";
503
		$i = 0;
504
		foreach ($files as $file){
505
			$i++;
506
			$color= ($i%2?"tableFMCol1":"tableFMCol2");
507
			//lien de suppression
508
			if ($trash){
509
				$url = $this->wiki->href('filemanager',$this->wiki->GetPageTag(),'do=erase&file='.$file['realname']);
510
			}else{
511
				$url = $this->wiki->href('filemanager',$this->wiki->GetPageTag(),'do=del&file='.$file['realname']);
512
			}
513
			$dellink = '<a href="'.$url.'" title="Supprimer">'.$this->attachConfig['fmDelete_symbole']."</a>";
514
			//lien de restauration
515
			$restlink = '';
516
			if ($trash){
517
				$url = $this->wiki->href('filemanager',$this->wiki->GetPageTag(),'do=restore&file='.$file['realname']);
518
				$restlink = '<a href="'.$url.'" title="Restaurer">'.$this->attachConfig['fmRestore_symbole']."</a>";
519
			}
520
 
521
			//lien pour downloader le fichier
522
			$url = $this->wiki->href("download",$this->wiki->GetPageTag(),"file=".$file['realname']);
523
			$dlLink = '<a href="'.$url.'">'.$file['name'].'.'.$file['ext']."</a>";
524
			$fmBodyTable .= 	'		<tr class="'.$color.'">'."\n".
525
									'			<td>'.$dellink.' '.$restlink.'</td>'."\n".
526
									'			<td>'.$dlLink.'</td>'."\n".
527
									'			<td>'.$file['realname'].'</td>'."\n".
528
									'			<td>'.$file['size'].'</td>'."\n".
529
									'			<td>'.$this->parseDate($file['datepage']).'</td>'."\n".
530
									'			<td>'.$this->parseDate($file['dateupload']).'</td>'."\n";
531
			if($trash){
532
         	$fmBodyTable.= '			<td>'.$this->parseDate($file['trashdate']).'</td>'."\n";
533
			}
534
			$fmBodyTable .= 	'		</tr>'."\n";
535
		}
536
		$fmBodyTable .= '	</tbody>'."\n";
537
		//pied de la page
538
		$fmFooterPage = "---\n-----\n[[".$this->wiki->tag." Retour à la page ".$this->wiki->tag."]]\n";
539
		//affichage
540
		echo $fmTitlePage."\n";
541
		echo '<table class="tableFM" border="0" cellspacing="0">'."\n".$fmHeadTable.$fmFootTable.$fmBodyTable.'</table>'."\n";
542
		echo $this->wiki->Format($fmFooterPage);
543
	}
544
	/**
545
	* Renvoie la liste des fichiers
546
	*/
547
	function fmGetFiles($trash=false){
548
		$path = $this->GetUploadPath();
549
		if($this->isSafeMode){
550
			$filePattern = '^'.$this->wiki->GetPageTag().'_.*_\d{14}_\d{14}\..*';
551
		}else{
552
			$filePattern = '^.*_\d{14}_\d{14}\..*';
553
		}
554
		if($trash){
555
			$filePattern .= 'trash\d{14}';
556
		}else{
557
			$filePattern .= '[^(trash\d{14})]';
558
		}
559
		return $this->searchFiles('`'.$filePattern.'$`', $path);
560
	}
561
	/**
562
	* Vide la poubelle
563
	*/
564
	function fmEmptyTrash(){
565
		$files = $this->fmGetFiles(true);
566
		foreach ($files as $file){
567
			$filename = $file['path'].'/'.$file['realname'];
568
			if(file_exists($filename)){
569
				unlink($filename);
570
			}
571
		}
572
	}
573
	/**
574
	* Effacement d'un fichier dans la poubelle
575
	*/
576
	function fmErase(){
577
		$path = $this->GetUploadPath();
578
		$filename = $path.'/'.($_GET['file']?$_GET['file']:'');
579
		if (file_exists($filename)){
580
			unlink($filename);
581
		}
582
	}
583
	/**
584
	* Met le fichier a la poubelle
585
	*/
586
	function fmDelete(){
587
		$path = $this->GetUploadPath();
588
		$filename = $path.'/'.($_GET['file']?$_GET['file']:'');
589
		if (file_exists($filename)){
590
			$trash = $filename.'trash'.$this->getDate();
591
			rename($filename, $trash);
592
		}
593
	}
594
	/**
595
	* Restauration d'un fichier mis a la poubelle
596
	*/
597
	function fmRestore(){
598
		$path = $this->GetUploadPath();
599
		$filename = $path.'/'.($_GET['file']?$_GET['file']:'');
600
		if (file_exists($filename)){
601
			$restFile = preg_replace('`^(.*\..*)trash\d{14}$`', '$1', $filename);
602
			rename($filename, $restFile);
603
		}
604
	}
605
	/**
606
	* Tri tu tableau liste des fichiers par nom puis par date de revision(upload) du fichier, ordre croissant
607
	*/
608
	function sortByNameRevFile($files){
609
		if (!function_exists('ByNameByRevFile')){
610
			function ByNameByRevFile($f1,$f2){
611
				$f1Name = $f1['name'].'.'.$f1['ext'];
612
				$f2Name = $f2['name'].'.'.$f2['ext'];
613
				$res = strcasecmp($f1Name, $f2Name);
614
				if($res==0){
615
					//si meme nom => compare la revision du fichier
616
					$res = strcasecmp($f1['dateupload'], $f2['dateupload']);
617
				}
618
				return $res;
619
			}
620
		}
621
		usort($files,'ByNameByRevFile');
622
		return $files;
623
	}
624
}
625
?>