Subversion Repositories Applications.framework

Rev

Rev 246 | Rev 250 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
246 jpm 1
<?php
2
class CacheFichier {
3
	/**
4
	 * Available options
5
	 *
6
	 * =====> (string) cache_dir :
7
	 * - Directory where to put the cache files
8
	 *
9
	 * =====> (boolean) file_locking :
10
	 * - Enable / disable file_locking
11
	 * - Can avoid cache corruption under bad circumstances but it doesn't work on multithread
12
	 * webservers and on NFS filesystems for example
13
	 *
14
	 * =====> (boolean) read_control :
15
	 * - Enable / disable read control
16
	 * - If enabled, a control key is embeded in cache file and this key is compared with the one
17
	 * calculated after the reading.
18
	 *
19
	 * =====> (string) read_control_type :
20
	 * - Type of read control (only if read control is enabled). Available values are :
21
	 *   'md5' for a md5 hash control (best but slowest)
22
	 *   'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
23
	 *   'adler32' for an adler32 hash control (excellent choice too, faster than crc32)
24
	 *   'strlen' for a length only test (fastest)
25
	 *
26
	 * =====> (int) hashed_directory_level :
27
	 * - Hashed directory level
28
	 * - Set the hashed directory structure level. 0 means "no hashed directory
29
	 * structure", 1 means "one level of directory", 2 means "two levels"...
30
	 * This option can speed up the cache only when you have many thousands of
31
	 * cache file. Only specific benchs can help you to choose the perfect value
32
	 * for you. Maybe, 1 or 2 is a good start.
33
	 *
34
	 * =====> (int) hashed_directory_umask :
35
	 * - Umask for hashed directory structure
36
	 *
37
	 * =====> (string) file_name_prefix :
38
	 * - prefix for cache files
39
	 * - be really carefull with this option because a too generic value in a system cache dir
40
	 *   (like /tmp) can cause disasters when cleaning the cache
41
	 *
42
	 * =====> (int) cache_file_umask :
43
	 * - Umask for cache files
44
	 *
45
	 * =====> (int) metatadatas_array_max_size :
46
	 * - max size for the metadatas array (don't change this value unless you
47
	 *   know what you are doing)
48
	 *
49
	 * @var array available options
50
	 */
51
	protected $options = array(
52
		'stockage_chemin' => null,
248 jpm 53
		'fichier_verrou' => true,
54
		'controle_lecture' => true,
246 jpm 55
		'controle_lecture_type' => 'crc32',
56
		'dossier_niveau' => 0,
57
		'dossier_umask' => 0700,
58
		'fichier_prefixe' => 'tbf',
59
		'fichier_umask' => 0600,
60
		'metadonnees_max_taille' => 100
61
	);
62
 
63
	/**
64
	 * Array of metadatas (each item is an associative array)
65
	 *
66
	 * @var array
67
	 */
248 jpm 68
	protected $metadonnees = array();
246 jpm 69
 
70
 
71
	/**
72
	 * Constructor
73
	 *
74
	 * @param  array $options associative array of options
75
	 * @throws Zend_Cache_Exception
76
	 * @return void
77
	 */
78
	public function __construct(array $options = array()) {
248 jpm 79
		$this->setOptions($options);
80
 
246 jpm 81
		if (isset($this->options['prefixe_fichier'])) {
82
			if (!preg_match('~^[a-zA-Z0-9_]+$~D', $this->options['prefixe_fichier'])) {
83
				trigger_error("Préfixe de nom de fichier invalide : doit contenir seulement [a-zA-Z0-9_]", E_USER_WARNING);
84
			}
85
		}
248 jpm 86
		if ($this->options['metadonnees_max_taille'] < 10) {
246 jpm 87
			trigger_error("Taille du tableau des méta-données invalide, elle doit être > 10", E_USER_WARNING);
88
		}
89
		if (isset($options['dossier_umask']) && is_string($options['dossier_umask'])) {
90
			// See #ZF-4422
91
			$this->options['dossier_umask'] = octdec($this->options['dossier_umask']);
92
		}
93
		if (isset($options['fichier_umask']) && is_string($options['fichier_umask'])) {
94
			// See #ZF-4422
95
			$this->options['fichier_umask'] = octdec($this->options['fichier_umask']);
96
		}
97
	}
248 jpm 98
 
99
	private function setOptions($options) {
100
		while (list($nom, $valeur) = each($options)) {
101
			if (!is_string($nom)) {
102
				trigger_error("Nom d'option incorecte : $nom", E_USER_WARNING);
103
			}
104
			$nom = strtolower($nom);
105
			if (array_key_exists($nom, $this->options)) {
106
				$this->options[$nom] = $valeur;
107
			}
108
		}
109
	}
246 jpm 110
 
248 jpm 111
   	public function setEmplacement($emplacement) {
246 jpm 112
		if (!is_dir($emplacement)) {
113
			trigger_error("L'emplacement doit être un dossier.", E_USER_WARNING);
114
		}
115
		if (!is_writable($emplacement)) {
116
			trigger_error("Le dossier de stockage du cache n'est pas accessible en écriture", E_USER_WARNING);
117
		}
118
		$emplacement = rtrim(realpath($emplacement), '\\/').DS;
119
		$this->options['stockage_chemin'] = $emplacement;
120
	}
121
 
122
	/**
123
	 * Test if a cache is available for the given id and (if yes) return it (false else)
124
	 *
125
	 * @param string $id cache id
126
	 * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
127
	 * @return string|false cached datas
128
	 */
129
	public function charger($id, $ne_pas_tester_validiter_du_cache = false) {
130
		$donnees = false;
131
		if ($this->tester($id, $ne_pas_tester_validiter_du_cache)) {
132
			$metadonnees = $this->getMetadonneesFichier($id);
133
			$fichier = $this->getFichierNom($id);
134
			$donnees = $this->getContenuFichier($fichier);
135
			if ($this->options['controle_lecture']) {
136
				$cle_secu_donnees = $this->genererCleSecu($donnees, $this->options['controle_lecture_type']);
137
				$cle_secu_controle = $metadonnees['hash'];
138
				if ($cle_secu_donnees != $cle_secu_controle) {
139
					// Probléme détecté par le contrôle de lecture !
140
					// TODO : loguer le pb de sécu
141
					$this->supprimer($id);
142
					$donnees = false;
143
				}
144
			}
145
		}
146
		return $donnees;
147
	}
148
 
149
	/**
150
	 * Teste si un enregistrement en cache est disponible ou pas (pour l'id passé en paramètre).
151
	 *
152
	 * @param string $id identifiant de cache.
153
	 * @return mixed false (le cache n'est pas disponible) ou timestamp (int) "de dernière modification" de l'enregistrement en cache
154
	 */
155
	public function tester($id) {
156
		clearstatcache();
157
		return $this->testerExistenceCache($id, false);
158
	}
159
 
160
	/**
161
	 * Save some string datas into a cache record
162
	 *
163
	 * Note : $data is always "string" (serialization is done by the
164
	 * core not by the backend)
165
	 *
166
	 * @param  string $data			 Datas to cache
167
	 * @param  string $id			   Cache id
168
	 * @param  array  $tags			 Array of strings, the cache record will be tagged by each string entry
169
	 * @param  int	$specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
170
	 * @return boolean true if no problem
171
	 */
248 jpm 172
	public function sauver($donnees, $id, $tags = array(), $duree_vie_specifique = false) {
246 jpm 173
		clearstatcache();
248 jpm 174
		$fichier = $this->getFichierNom($id);
175
		$chemin = $this->getChemin($id);
176
 
177
		$resultat = true;
178
		if ($this->options['dossier_niveau'] > 0) {
179
			if (!is_writable($chemin)) {
246 jpm 180
				// maybe, we just have to build the directory structure
181
				$this->lancerMkdirEtChmodRecursif($id);
182
			}
248 jpm 183
			if (!is_writable($chemin)) {
184
				$resultat = false;
246 jpm 185
			}
186
		}
248 jpm 187
 
188
		if ($resultat === true) {
189
			if ($this->options['controle_lecture']) {
190
				$cle_secu = $this->genererCleSecu($donnees, $this->options['controle_lecture_type']);
191
			} else {
192
				$cle_secu = '';
193
			}
194
 
195
			$metadonnees = array(
196
				'hash' => $cle_secu,
197
				'mtime' => time(),
198
				'expiration' => $this->getTimestampExpiration($duree_vie_specifique),
199
				'tags' => $tags
200
			);
201
 
202
			if (! $resultat = $this->setMetadonnees($id, $metadonnees)) {
203
				// TODO : ajouter un log
204
			} else {
205
				$resultat = $this->setContenuFichier($fichier, $donnees);
206
			}
246 jpm 207
		}
248 jpm 208
		return $resultat;
246 jpm 209
	}
210
 
211
	/**
212
	 * Remove a cache record
213
	 *
214
	 * @param  string $id cache id
215
	 * @return boolean true if no problem
216
	 */
217
	public function supprimer($id) {
218
		$fichier = $this->getFichierNom($id);
219
		$suppression_fichier = $this->supprimerFichier($fichier);
220
		$suppression_metadonnees = $this->supprimerMetadonnees($id);
221
		return $suppression_metadonnees && $suppression_fichier;
222
	}
223
 
224
	/**
225
	 * Clean some cache records
226
	 *
227
	 * Available modes are :
228
	 * 'all' (default)  => remove all cache entries ($tags is not used)
229
	 * 'old'			=> remove too old cache entries ($tags is not used)
230
	 * 'matchingTag'	=> remove cache entries matching all given tags
231
	 *					 ($tags can be an array of strings or a single string)
232
	 * 'notMatchingTag' => remove cache entries not matching one of the given tags
233
	 *					 ($tags can be an array of strings or a single string)
234
	 * 'matchingAnyTag' => remove cache entries matching any given tags
235
	 *					 ($tags can be an array of strings or a single string)
236
	 *
237
	 * @param string $mode clean mode
238
	 * @param tags array $tags array of tags
239
	 * @return boolean true if no problem
240
	 */
241
	public function nettoyer($mode = Cache::NETTOYAGE_MODE_TOUS, $tags = array()) {
242
		// We use this protected method to hide the recursive stuff
243
		clearstatcache();
248 jpm 244
		return $this->nettoyerFichiers($this->options['stockage_chemin'], $mode, $tags);
246 jpm 245
	}
246
 
247
	/**
248
	 * Return an array of stored cache ids
249
	 *
250
	 * @return array array of stored cache ids (string)
251
	 */
248 jpm 252
	public function getIds() {
253
		return $this->analyserCache($this->options['stockage_chemin'], 'ids', array());
246 jpm 254
	}
255
 
256
	/**
257
	 * Return an array of stored tags
258
	 *
259
	 * @return array array of stored tags (string)
260
	 */
248 jpm 261
	public function getTags() {
262
		return $this->analyserCache($this->options['stockage_chemin'], 'tags', array());
246 jpm 263
	}
264
 
265
	/**
266
	 * Return an array of stored cache ids which match given tags
267
	 *
268
	 * In case of multiple tags, a logical AND is made between tags
269
	 *
270
	 * @param array $tags array of tags
271
	 * @return array array of matching cache ids (string)
272
	 */
248 jpm 273
	public function getIdsAvecLesTags($tags = array()) {
274
		return $this->analyserCache($this->options['stockage_chemin'], 'matching', $tags);
246 jpm 275
	}
276
 
277
	/**
278
	 * Return an array of stored cache ids which don't match given tags
279
	 *
280
	 * In case of multiple tags, a logical OR is made between tags
281
	 *
282
	 * @param array $tags array of tags
283
	 * @return array array of not matching cache ids (string)
284
	 */
248 jpm 285
	public function getIdsSansLesTags($tags = array()) {
286
		return $this->analyserCache($this->options['stockage_chemin'], 'notMatching', $tags);
246 jpm 287
	}
288
 
289
	/**
290
	 * Return an array of stored cache ids which match any given tags
291
	 *
292
	 * In case of multiple tags, a logical AND is made between tags
293
	 *
294
	 * @param array $tags array of tags
295
	 * @return array array of any matching cache ids (string)
296
	 */
248 jpm 297
	public function getIdsAvecUnTag($tags = array()) {
298
		return $this->analyserCache($this->options['stockage_chemin'], 'matchingAny', $tags);
246 jpm 299
	}
300
 
301
	/**
302
	 * Return the filling percentage of the backend storage
303
	 *
304
	 * @throws Zend_Cache_Exception
305
	 * @return int integer between 0 and 100
306
	 */
248 jpm 307
	public function getPourcentageRemplissage() {
308
		$libre = disk_free_space($this->options['sotckage_chemin']);
309
		$total = disk_total_space($this->options['sotckage_chemin']);
310
 
311
		$pourcentage = 0;
246 jpm 312
		if ($total == 0) {
248 jpm 313
			trigger_error("Impossible d'utiliser la fonction disk_total_space", E_USER_WARNING);
246 jpm 314
		} else {
248 jpm 315
			$pourcentage = ($libre >= $total) ? 100 : ((int) (100. * ($total - $libre) / $total));
246 jpm 316
		}
248 jpm 317
		return $pourcentage;
246 jpm 318
	}
319
 
320
	/**
321
	 * Return an array of metadatas for the given cache id
322
	 *
323
	 * The array must include these keys :
324
	 * - expire : the expire timestamp
325
	 * - tags : a string array of tags
326
	 * - mtime : timestamp of last modification time
327
	 *
328
	 * @param string $id cache id
329
	 * @return array array of metadatas (false if the cache id is not found)
330
	 */
248 jpm 331
	public function getMetadonnees($id) {
332
		if ($metadonnees = $this->getMetadonneesFichier($id)) {
333
			if (time() > $metadonnees['expiration']) {
334
				$metadonnees = false;
335
			} else {
336
				$metadonnees = array(
337
					'expiration' => $metadonnees['expiration'],
338
					'tags' => $metadonnees['tags'],
339
					'mtime' => $metadonnees['mtime']
340
				);
341
			}
246 jpm 342
		}
248 jpm 343
 
344
		return $metadonnees;
246 jpm 345
	}
346
 
347
	/**
348
	 * Give (if possible) an extra lifetime to the given cache id
349
	 *
350
	 * @param string $id cache id
351
	 * @param int $extraLifetime
352
	 * @return boolean true if ok
353
	 */
248 jpm 354
	public function ajouterSupplementDureeDeVie($id, $supplement_duree_de_vie) {
355
		$augmentation = true;
356
		if ($metadonnees = $this->getMetadonneesFichier($id)) {
357
			if (time() > $metadonnees['expiration']) {
358
				$augmentation = false;
359
			} else {
360
				$metadonnees_nouvelle = array(
361
					'hash' => $metadonnees['hash'],
362
					'mtime' => time(),
363
					'expiration' => $metadonnees['expiration'] + $supplement_duree_de_vie,
364
					'tags' => $metadonnees['tags']
365
				);
366
				$augmentation = $this->setMetadonnees($id, $metadonnees_nouvelle);
367
			}
246 jpm 368
		}
248 jpm 369
		return $augmentation;
246 jpm 370
	}
371
 
372
	/**
373
	 * Get a metadatas record
374
	 *
375
	 * @param  string $id  Cache id
376
	 * @return array|false Associative array of metadatas
377
	 */
378
	protected function getMetadonneesFichier($id) {
379
		$metadonnees = false;
380
		if (isset($this->metadonnees[$id])) {
381
			$metadonnees = $this->metadonnees[$id];
382
		} else {
383
			if ($metadonnees = $this->chargerMetadonnees($id)) {
384
				$this->setMetadonnees($id, $metadonnees, false);
385
			}
386
		}
387
		return $metadonnees;
388
	}
389
 
390
	/**
391
	 * Set a metadatas record
392
	 *
393
	 * @param  string $id		Cache id
394
	 * @param  array  $metadatas Associative array of metadatas
395
	 * @param  boolean $save	 optional pass false to disable saving to file
396
	 * @return boolean True if no problem
397
	 */
398
	protected function setMetadonnees($id, $metadonnees, $sauvegarde = true) {
399
		if (count($this->metadonnees) >= $this->options['metadonnees_max_taille']) {
400
			$n = (int) ($this->options['metadonnees_max_taille'] / 10);
401
			$this->metadonnees = array_slice($this->metadonnees, $n);
402
		}
403
 
404
		$resultat = true;
405
		if ($sauvegarde) {
406
			$resultat = $this->sauverMetadonnees($id, $metadonnees);
407
		}
408
		if ($resultat == true) {
409
			$this->metadonnees[$id] = $metadonnees;
410
		}
411
		return $resultat;
412
	}
413
 
414
	/**
415
	 * Drop a metadata record
416
	 *
417
	 * @param  string $id Cache id
418
	 * @return boolean True if no problem
419
	 */
420
	protected function supprimerMetadonnees($id) {
421
		if (isset($this->metadonnees[$id])) {
422
			unset($this->metadonnees[$id]);
423
		}
424
		$fichier_meta = $this->getNomFichierMeta($id);
425
		return $this->supprimerFichier($fichier_meta);
426
	}
427
 
428
	/**
429
	 * Clear the metadatas array
430
	 *
431
	 * @return void
432
	 */
433
	protected function nettoyerMetadonnees() {
434
		$this->metadonnees = array();
435
	}
436
 
437
	/**
438
	 * Load metadatas from disk
439
	 *
440
	 * @param  string $id Cache id
441
	 * @return array|false Metadatas associative array
442
	 */
443
	protected function chargerMetadonnees($id) {
444
		$fichier = $this->getNomFichierMeta($id);
445
		if ($resultat = $this->getContenuFichier($fichier)) {
446
			$resultat = @unserialize($resultat);
447
		}
448
		return $resultat;
449
	}
450
 
451
	/**
452
	 * Save metadatas to disk
453
	 *
454
	 * @param  string $id		Cache id
455
	 * @param  array  $metadatas Associative array
456
	 * @return boolean True if no problem
457
	 */
458
	protected function sauverMetadonnees($id, $metadonnees) {
459
		$fichier = $this->getNomFichierMeta($id);
460
		$resultat = $this->setContenuFichier($fichier, serialize($metadonnees));
461
		return $resultat;
462
	}
463
 
464
	/**
465
	 * Make and return a file name (with path) for metadatas
466
	 *
467
	 * @param  string $id Cache id
468
	 * @return string Metadatas file name (with path)
469
	 */
470
	protected function getNomFichierMeta($id) {
471
		$chemin = $this->getChemin($id);
472
		$fichier_nom = $this->transformaterIdEnNomFichier('internal-metadatas---'.$id);
473
		return $chemin.$fichier_nom;
474
	}
475
 
476
	/**
477
	 * Check if the given filename is a metadatas one
478
	 *
479
	 * @param  string $fileName File name
480
	 * @return boolean True if it's a metadatas one
481
	 */
482
	protected function etreFichierMeta($fichier_nom) {
483
		$id = $this->transformerNomFichierEnId($fichier_nom);
484
		return (substr($id, 0, 21) == 'internal-metadatas---') ? true : false;
485
	}
486
 
487
	/**
488
	 * Remove a file
489
	 *
490
	 * If we can't remove the file (because of locks or any problem), we will touch
491
	 * the file to invalidate it
492
	 *
493
	 * @param  string $file Complete file path
494
	 * @return boolean True if ok
495
	 */
496
	protected function supprimerFichier($fichier) {
497
		$resultat = false;
498
		if (is_file($fichier)) {
499
			if ($resultat = @unlink($fichier)) {
500
				// TODO : ajouter un log
501
			}
502
		}
503
		return $resultat;
504
	}
505
 
506
	/**
507
	 * Clean some cache records (protected method used for recursive stuff)
508
	 *
509
	 * Available modes are :
510
	 * Zend_Cache::CLEANING_MODE_ALL (default)	=> remove all cache entries ($tags is not used)
511
	 * Zend_Cache::CLEANING_MODE_OLD			  => remove too old cache entries ($tags is not used)
512
	 * Zend_Cache::CLEANING_MODE_MATCHING_TAG	 => remove cache entries matching all given tags
513
	 *											   ($tags can be an array of strings or a single string)
514
	 * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
515
	 *											   ($tags can be an array of strings or a single string)
516
	 * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
517
	 *											   ($tags can be an array of strings or a single string)
518
	 *
519
	 * @param  string $dir  Directory to clean
520
	 * @param  string $mode Clean mode
521
	 * @param  array  $tags Array of tags
522
	 * @throws Zend_Cache_Exception
523
	 * @return boolean True if no problem
524
	 */
525
	protected function nettoyerFichiers($dossier, $mode = Cache::NETTOYAGE_MODE_TOUS, $tags = array()) {
526
		if (!is_dir($dossier)) {
527
			return false;
528
		}
529
		$resultat = true;
530
		$prefixe = $this->options['fichier_prefixe'];
531
		$glob = @glob($dossier.$prefixe.'--*');
532
		if ($glob === false) {
533
			// On some systems it is impossible to distinguish between empty match and an error.
534
			return true;
535
		}
536
		foreach ($glob as $fichier)  {
537
			if (is_file($fichier)) {
538
				$fichier_nom = basename($fichier);
539
				if ($this->etreFichierMeta($fichier_nom)) {
248 jpm 540
					// Pour le mode Cache::NETTOYAGE_MODE_TOUS, nous essayons de tous supprimer même les vieux fichiers méta
246 jpm 541
					if ($mode != Cache::NETTOYAGE_MODE_TOUS) {
542
						continue;
543
					}
544
				}
545
				$id = $this->transformerNomFichierEnId($fichier_nom);
248 jpm 546
				$metadonnees = $this->getMetadonneesFichier($id);
547
				if ($metadonnees === FALSE) {
548
					$metadonnees = array('expiration' => 1, 'tags' => array());
246 jpm 549
				}
550
				switch ($mode) {
248 jpm 551
					case Cache::NETTOYAGE_MODE_TOUS :
552
						if ($resultat_suppression = $this->supprimer($id)) {
553
							// Dans ce cas seulement, nous acception qu'il y ait un problème avec la suppresssion du fichier meta
554
							$resultat_suppression = $this->supprimerFichier($fichier);
246 jpm 555
						}
248 jpm 556
						$resultat = $resultat && $resultat_suppression;
246 jpm 557
						break;
248 jpm 558
					case Cache::NETTOYAGE_MODE_EXPIRATION :
559
						if (time() > $metadonnees['expiration']) {
560
							$resultat = $this->supprimer($id) && $resultat;
246 jpm 561
						}
562
						break;
248 jpm 563
					case Cache::NETTOYAGE_MODE_AVEC_LES_TAGS :
564
						$correspondance = true;
246 jpm 565
						foreach ($tags as $tag) {
248 jpm 566
							if (!in_array($tag, $metadonnees['tags'])) {
567
								$correspondance = false;
246 jpm 568
								break;
569
							}
570
						}
248 jpm 571
						if ($correspondance) {
572
							$resultat = $this->supprimer($id) && $resultat;
246 jpm 573
						}
574
						break;
248 jpm 575
					case Cache::NETTOYAGE_MODE_SANS_LES_TAGS :
576
						$correspondance = false;
246 jpm 577
						foreach ($tags as $tag) {
248 jpm 578
							if (in_array($tag, $metadonnees['tags'])) {
579
								$correspondance = true;
246 jpm 580
								break;
581
							}
582
						}
248 jpm 583
						if (!$correspondance) {
584
							$resultat = $this->supprimer($id) && $resultat;
246 jpm 585
						}
586
						break;
248 jpm 587
					case Cache::NETTOYAGE_MODE_AVEC_UN_TAG :
588
						$correspondance = false;
246 jpm 589
						foreach ($tags as $tag) {
248 jpm 590
							if (in_array($tag, $metadonnees['tags'])) {
591
								$correspondance = true;
246 jpm 592
								break;
593
							}
594
						}
248 jpm 595
						if ($correspondance) {
596
							$resultat = $this->supprimer($id) && $resultat;
246 jpm 597
						}
598
						break;
599
					default:
248 jpm 600
						trigger_error("Mode de nettoyage invalide pour la méthode nettoyer()", E_USER_WARNING);
246 jpm 601
						break;
602
				}
603
			}
248 jpm 604
			if ((is_dir($fichier)) and ($this->options['dossier_niveau'] > 0)) {
605
				// Appel récursif
606
				$resultat = $this->nettoyerFichiers($fichier.DS, $mode, $tags) && $resultat;
607
				if ($mode == Cache::NETTOYAGE_MODE_TOUS) {
608
					// Si mode == Cache::NETTOYAGE_MODE_TOUS, nous essayons de supprimer la structure aussi
609
					@rmdir($fichier);
246 jpm 610
				}
611
			}
612
		}
613
		return $resultat;
614
	}
615
 
248 jpm 616
	protected function analyserCache($dossier, $mode, $tags = array()) {
617
		if (!is_dir($dossier)) {
246 jpm 618
			return false;
619
		}
248 jpm 620
		$resultat = array();
621
		$prefixe = $this->options['fichier_prefixe'];
622
		$glob = @glob($dossier.$prefixe.'--*');
246 jpm 623
		if ($glob === false) {
624
			// On some systems it is impossible to distinguish between empty match and an error.
625
			return array();
626
		}
248 jpm 627
		foreach ($glob as $fichier)  {
628
			if (is_file($fichier)) {
629
				$nom_fichier = basename($fichier);
630
				$id = $this->transformerNomFichierEnId($nom_fichier);
631
				$metadonnees = $this->getMetadonneesFichier($id);
632
				if ($metadonnees === FALSE) {
246 jpm 633
					continue;
634
				}
248 jpm 635
				if (time() > $metadonnees['expiration']) {
246 jpm 636
					continue;
637
				}
638
				switch ($mode) {
639
					case 'ids':
248 jpm 640
						$resultat[] = $id;
246 jpm 641
						break;
642
					case 'tags':
248 jpm 643
						$resultat = array_unique(array_merge($resultat, $metadonnees['tags']));
246 jpm 644
						break;
645
					case 'matching':
248 jpm 646
						$correspondance = true;
246 jpm 647
						foreach ($tags as $tag) {
248 jpm 648
							if (!in_array($tag, $metadonnees['tags'])) {
649
								$correspondance = false;
246 jpm 650
								break;
651
							}
652
						}
248 jpm 653
						if ($correspondance) {
654
							$resultat[] = $id;
246 jpm 655
						}
656
						break;
657
					case 'notMatching':
248 jpm 658
						$correspondance = false;
246 jpm 659
						foreach ($tags as $tag) {
248 jpm 660
							if (in_array($tag, $metadonnees['tags'])) {
661
								$correspondance = true;
246 jpm 662
								break;
663
							}
664
						}
248 jpm 665
						if (!$correspondance) {
666
							$resultat[] = $id;
246 jpm 667
						}
668
						break;
669
					case 'matchingAny':
248 jpm 670
						$correspondance = false;
246 jpm 671
						foreach ($tags as $tag) {
248 jpm 672
							if (in_array($tag, $metadonnees['tags'])) {
673
								$correspondance = true;
246 jpm 674
								break;
675
							}
676
						}
248 jpm 677
						if ($correspondance) {
678
							$resultat[] = $id;
246 jpm 679
						}
680
						break;
681
					default:
248 jpm 682
						trigger_error("Mode invalide pour la méthode analyserCache()", E_USER_WARNING);
246 jpm 683
						break;
684
				}
685
			}
248 jpm 686
			if ((is_dir($fichier)) and ($this->options['dossier_niveau'] > 0)) {
687
				// Appel récursif
688
				$resultat_analyse_recursive = $this->analyserCache($fichier.DS, $mode, $tags);
689
				if ($resultat_analyse_recursive === false) {
690
					// TODO : ajoute un log
246 jpm 691
				} else {
248 jpm 692
					$resultat = array_unique(array_merge($resultat, $resultat_analyse_recursive));
246 jpm 693
				}
694
			}
695
		}
248 jpm 696
		return array_unique($resultat);
246 jpm 697
	}
698
 
699
	/**
700
	 * Compute & return the expire time
701
	 *
702
	 * @return int expire time (unix timestamp)
703
	 */
248 jpm 704
	protected function getTimestampExpiration($duree_de_vie) {
705
		if ($duree_de_vie === false) {
706
			$duree_de_vie = 3600;
246 jpm 707
		}
248 jpm 708
		$timestamp = ($duree_de_vie === null) ? 9999999999 : (time() + $duree_de_vie);
709
		return $timestamp;
246 jpm 710
	}
711
 
712
	/**
713
	 * Make a control key with the string containing datas
714
	 *
715
	 * @param  string $data		Data
716
	 * @param  string $controlType Type of control 'md5', 'crc32' or 'strlen'
717
	 * @throws Zend_Cache_Exception
718
	 * @return string Control key
719
	 */
720
	protected function genererCleSecu($donnees, $type_de_controle) {
721
		switch ($type_de_controle) {
722
		case 'md5':
723
			return md5($donnees);
724
		case 'crc32':
725
			return crc32($donnees);
726
		case 'strlen':
727
			return strlen($donnees);
728
		case 'adler32':
729
			return hash('adler32', $donnees);
730
		default:
731
			trigger_error("Fonction de génération de clé de sécurité introuvable : $type_de_controle", E_USER_WARNING);
732
		}
733
	}
734
 
735
	/**
736
	 * Transform a cache id into a file name and return it
737
	 *
738
	 * @param  string $id Cache id
739
	 * @return string File name
740
	 */
741
	protected function transformaterIdEnNomFichier($id) {
742
		$prefixe = $this->options['fichier_prefixe'];
248 jpm 743
		$resultat = $prefixe.'---'.$id;
246 jpm 744
		return $resultat;
745
	}
746
 
747
	/**
748
	 * Make and return a file name (with path)
749
	 *
750
	 * @param  string $id Cache id
751
	 * @return string File name (with path)
752
	 */
753
	protected function getFichierNom($id) {
754
		$path = $this->getChemin($id);
755
		$fileName = $this->transformaterIdEnNomFichier($id);
756
		return $path . $fileName;
757
	}
758
 
759
	/**
760
	 * Return the complete directory path of a filename (including hashedDirectoryStructure)
761
	 *
762
	 * @param  string $id Cache id
763
	 * @param  boolean $decoupage if true, returns array of directory parts instead of single string
764
	 * @return string Complete directory path
765
	 */
766
	protected function getChemin($id, $decoupage = false) {
767
		$morceaux = array();
768
		$chemin = $this->options['stockage_chemin'];
769
		$prefixe = $this->options['fichier_prefixe'];
770
		if ($this->options['dossier_niveau'] > 0) {
771
			$hash = hash('adler32', $id);
772
			for ($i = 0 ; $i < $this->options['dossier_niveau'] ; $i++) {
248 jpm 773
				$chemin .= $prefixe.'--'.substr($hash, 0, $i + 1).DS;
246 jpm 774
				$morceaux[] = $chemin;
775
			}
776
		}
777
		return ($decoupage) ? 	$morceaux : $chemin;
778
	}
779
 
780
	/**
781
	 * Make the directory strucuture for the given id
782
	 *
783
	 * @param string $id cache id
784
	 * @return boolean true
785
	 */
786
	protected function lancerMkdirEtChmodRecursif($id) {
787
		$resultat = true;
788
		if ($this->options['dossier_niveau'] > 0) {
789
			$chemins = $this->getChemin($id, true);
790
			foreach ($chemins as $chemin) {
791
				if (!is_dir($chemin)) {
792
					@mkdir($chemin, $this->options['dossier_umask']);
793
					@chmod($chemin, $this->options['dossier_umask']); // see #ZF-320 (this line is required in some configurations)
794
				}
795
			}
796
		}
797
		return $resultat;
798
	}
799
 
800
	/**
801
	 * Test if the given cache id is available (and still valid as a cache record)
802
	 *
803
	 * @param  string  $id					 Cache id
804
	 * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
805
	 * @return boolean|mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
806
	 */
807
	protected function testerExistenceCache($id, $ne_pas_tester_validiter_du_cache) {
808
		$resultat = false;
809
		if ($metadonnees = $this->getMetadonnees($id)) {
810
			if ($ne_pas_tester_validiter_du_cache || (time() <= $metadonnees['expiration'])) {
811
				$resultat =  $metadonnees['mtime'];
812
			}
813
		}
814
		return $resultat;
815
	}
816
 
817
	/**
818
	 * Return the file content of the given file
819
	 *
820
	 * @param  string $file File complete path
821
	 * @return string File content (or false if problem)
822
	 */
823
	protected function getContenuFichier($fichier) {
824
		$resultat = false;
825
		if (is_file($fichier)) {
826
			$f = @fopen($fichier, 'rb');
827
			if ($f) {
828
				if ($this->options['fichier_verrou']) @flock($f, LOCK_SH);
829
				$resultat = stream_get_contents($f);
830
				if ($this->options['fichier_verrou']) @flock($f, LOCK_UN);
831
				@fclose($f);
832
			}
833
		}
834
		return $resultat;
835
	}
836
 
837
	/**
838
	 * Put the given string into the given file
839
	 *
840
	 * @param  string $file   File complete path
841
	 * @param  string $string String to put in file
842
	 * @return boolean true if no problem
843
	 */
844
	protected function setContenuFichier($fichier, $chaine) {
845
		$resultat = false;
846
		$f = @fopen($fichier, 'ab+');
847
		if ($f) {
848
			if ($this->options['fichier_verrou']) @flock($f, LOCK_EX);
849
			fseek($f, 0);
850
			ftruncate($f, 0);
851
			$tmp = @fwrite($f, $chaine);
852
			if (!($tmp === FALSE)) {
853
				$resultat = true;
854
			}
855
			@fclose($f);
856
		}
857
		@chmod($fichier, $this->options['fichier_umask']);
858
		return $resultat;
859
	}
860
 
861
	/**
862
	 * Transform a file name into cache id and return it
863
	 *
864
	 * @param  string $fileName File name
865
	 * @return string Cache id
866
	 */
867
	protected function transformerNomFichierEnId($nom_de_fichier) {
868
		$prefixe = $this->options['fichier_prefixe'];
869
		return preg_replace('~^' . $prefixe . '---(.*)$~', '$1', $nom_de_fichier);
870
	}
871
}
872
?>