Overview
Comment: | Servir les fichiers stockés |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | trunk |
Files: | files | file ages | folders |
SHA1: |
e86b32517db467417abdddebffd7694a |
User & Date: | bohwaz on 2015-03-31 20:16:56 |
Other Links: | manifest | tags |
Context
2015-04-01
| ||
02:54 | Affichage des images et fichiers dans le wiki + insertion d'image avec choix légende et alignement check-in: 152296c653 user: bohwaz tags: trunk | |
2015-03-31
| ||
20:16 | Servir les fichiers stockés check-in: e86b32517d user: bohwaz tags: trunk | |
2015-03-28
| ||
17:13 | Liste des membres liés à une opération check-in: b0edec6de7 user: bohwaz tags: trunk | |
Changes
Modified src/include/lib/Garradin/Fichiers.php from [bcab4fa050] to [a66301146d].
1 2 3 4 5 6 7 | <?php namespace Garradin; class Fichiers { public $type; | > > | | > > | > > | > > > > > < < > > | | < < < | | > > | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <?php namespace Garradin; class Fichiers { public $id; public $nom; public $type; public $image; public $datetime; public $hash; public $taille; public $id_contenu; const LIEN_COMPTA = 'compta_journal'; const LIEN_WIKI = 'wiki_pages'; const LIEN_MEMBRES = 'membres'; const TAILLE_MINIATURE = 200; public function __construct($id) { $data = DB::getInstance()->simpleQuerySingle('SELECT fichiers.*, fc.hash, fc.taille, strftime(\'%s\', datetime) AS datetime FROM fichiers INNER JOIN fichiers_contenu AS fc ON fc.id = fichiers.id_contenu WHERE fichiers.id = ?;', true, (int)$id); if (!$data) { throw new \InvalidArgumentException('Ce fichier n\'existe pas.'); } foreach ($data as $key=>$value) { $this->$key = $value; } } public function getURL($thumbnail = false) { $url = WWW_URL . 'f/' . base_convert((int)$this->id, 10, 36) . '/'; if ($thumbnail) { $url .= 't/'; } return $url . $this->nom; } /** * Lier un fichier à un contenu * @param string $type Type de contenu (constantes LIEN_*) * @param integer $foreign_id ID du contenu lié * @return boolean TRUE en cas de succès |
︙ | ︙ | |||
63 64 65 66 67 68 69 70 71 72 73 74 75 76 | throw new \LogicException('Ce fichier est déjà lié à un autre contenu : ' . $check_type); } } return $db->simpleExec('INSERT OR IGNORE INTO fichiers_' . $type . ' (fichier, id) VALUES (?, ?);', (int)$this->id, (int)$foreign_id); } /** * Supprime le fichier * @return boolean TRUE en cas de succès */ public function remove() { | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | throw new \LogicException('Ce fichier est déjà lié à un autre contenu : ' . $check_type); } } return $db->simpleExec('INSERT OR IGNORE INTO fichiers_' . $type . ' (fichier, id) VALUES (?, ?);', (int)$this->id, (int)$foreign_id); } /** * Vérifie que l'utilisateur a bien le droit d'accéder à ce fichier * @param mixed $user Tableau contenant les infos sur l'utilisateur connecté, provenant de Membres::getLoggedUser, ou false * @return boolean TRUE si l'utilisateur a le droit d'accéder au fichier, sinon FALSE */ public function checkAccess($user = false) { // On regarde déjà si le fichier n'est pas lié au wiki $wiki = DB::getInstance()->simpleQuerySingle('SELECT wp.droit_lecture FROM fichiers_' . self::LIEN_WIKI . ' AS link INNER JOIN wiki_pages AS wp ON wp.id = link.id WHERE link.fichier = ? LIMIT 1;', false, (int)$this->id); // Page wiki publique, aucune vérification à faire, seul cas d'accès à un fichier en dehors de l'espace admin if ($wiki !== false && $wiki == Wiki::LECTURE_PUBLIC) { return true; } // Pas d'utilisateur connecté, pas d'accès aux fichiers de l'espace admin if (empty($user['droits'])) { return false; } if ($wiki !== false) { // S'il n'a même pas droit à accéder au wiki c'est mort if ($user['droits']['wiki'] < Membres::DROIT_ACCES) { return false; } // On renvoie à l'objet Wiki pour savoir si l'utilisateur a le droit de lire ce fichier $_w = new Wiki; $_w->setRestrictionCategorie($user['id_categorie'], $user['droits']['wiki']); return $_w->canReadPage($wiki); } // On regarde maintenant si le fichier est lié à la compta $compta = DB::getInstance()->simpleQuerySingle('SELECT 1 FROM fichiers_' . self::LIEN_COMPTA . ' WHERE fichier = ? LIMIT 1;', false, (int)$this->id); if ($compta && $user['droits']['compta'] >= Membres::DROIT_ACCES) { // OK si accès à la compta return true; } // Enfin, si le fichier est lié à un membre $membre = DB::getInstance()->simpleQuerySingle('SELECT id FROM fichiers_' . self::LIEN_MEMBRES . ' WHERE fichier = ? LIMIT 1;', false, (int)$this->id); if ($membre !== false) { // De manière évidente, l'utilisateur a le droit d'accéder aux fichiers liés à son profil if ((int)$membre == $user['id']) { return true; } // Pour voir les fichiers des membres il faut pouvoir les gérer if ($user['droits']['membres'] >= Membres::DROIT_ECRITURE) { return true; } } return false; } /** * Supprime le fichier * @return boolean TRUE en cas de succès */ public function remove() { |
︙ | ︙ | |||
85 86 87 88 89 90 91 92 93 94 | ON f1.id_contenu = f2.id_contenu AND f1.id != f2.id WHERE f2.id = ?;', false, (int)$this->id))) { $db->simpleExec('DELETE FROM fichiers_contenu WHERE id = ?;', (int)$id_contenu); } $db->simpleExec('DELETE FROM fichiers WHERE id = ?;', (int)$this->id); return $db->exec('END;'); } | > > > > > < < < < | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | > | 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | ON f1.id_contenu = f2.id_contenu AND f1.id != f2.id WHERE f2.id = ?;', false, (int)$this->id))) { $db->simpleExec('DELETE FROM fichiers_contenu WHERE id = ?;', (int)$id_contenu); } $db->simpleExec('DELETE FROM fichiers WHERE id = ?;', (int)$this->id); $cache_id = 'fichiers.' . $this->id_contenu; Static_Cache::remove($cache_id); Static_Cache::remove($cache_id . '.thumb'); return $db->exec('END;'); } protected function getFilePathFromCache() { // Le cache est géré par ID contenu, pas ID fichier, pour minimiser l'espace disque utilisé $cache_id = 'fichiers.' . $this->id_contenu; // Le fichier n'existe pas dans le cache statique, on l'enregistre if (!Static_Cache::exists($cache_id)) { $blob = DB::getInstance()->openBlob('fichiers_contenu', 'contenu', (int)$this->id_contenu); Static_Cache::storeFromPointer($cache_id, $blob); fclose($blob); } return Static_Cache::getPath($cache_id); } /** * Envoie le fichier au client HTTP * @return void */ public function serve() { return $this->_serve($this->getFilePathFromCache(), $this->type, $this->nom, $this->taille); } /** * Envoie une miniature à la taille indiquée au client HTTP * @return void */ public function serveThumbnail() { if (!$this->image) { throw new \LogicException('Il n\'est pas possible de fournir une miniature pour un fichier qui n\'est pas une image.'); } $cache_id = 'fichiers.' . $this->id_contenu . '.thumb'; $path = Static_Cache::getPath($cache_id); // La miniature n'existe pas dans le cache statique, on la crée if (!Static_Cache::exists($cache_id)) { $source = $this->getFilePathFromCache(); \KD2\Image::resize($source, $path, self::TAILLE_MINIATURE); } return $this->_serve($path, $this->type); } /** * Servir un fichier local en HTTP * @param string $path Chemin vers le fichier local * @param string $type Type MIME du fichier * @param string $name Nom du fichier avec extension * @param integer $size Taille du fichier en octets (facultatif) * @return boolean TRUE en cas de succès */ protected function _serve($path, $type, $name = false, $size = null) { // Désactiver le cache header('Pragma: public'); header('Expires: -1'); header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0'); header('Content-Type: '.$type); if ($name) { header('Content-Disposition: attachment; filename="' . $name . '"'); } // Utilisation de XSendFile si disponible if (ENABLE_XSENDFILE && isset($_SERVER['SERVER_SOFTWARE'])) { if (stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) |
︙ | ︙ | |||
139 140 141 142 143 144 145 | if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', 1); } @ini_set('zlib.output_compression', 'Off'); | > > | > | | 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', 1); } @ini_set('zlib.output_compression', 'Off'); if ($size) { header('Content-Length: '. (int)$size); } ob_clean(); flush(); // Sinon on envoie le fichier à la mano return readfile($path); } /** * Vérifie si le hash fourni n'est pas déjà stocké * Utile pour par exemple reconnaître un ficher dont le contenu est déjà stocké, et éviter un nouvel upload * @param string $hash Hash SHA1 * @return boolean TRUE si le hash est déjà présent dans fichiers_contenu, FALSE sinon |
︙ | ︙ | |||
234 235 236 237 238 239 240 241 242 243 244 245 246 247 | } if (!is_uploaded_file($file['tmp_name'])) { throw new \RuntimeException('Le fichier n\'a pas été envoyé de manière conventionnelle.'); } $name = preg_replace('/[^\d\w._-]/ui', '', $file['name']); $bytes = file_get_contents($file['tmp_name'], false, null, -1, 1024); $type = \KD2\FileInfo::guessMimeType($bytes); if (!$type) { | > | 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | } if (!is_uploaded_file($file['tmp_name'])) { throw new \RuntimeException('Le fichier n\'a pas été envoyé de manière conventionnelle.'); } $name = preg_replace('/[ ]/', '_', $file['name']); $name = preg_replace('/[^\d\w._-]/ui', '', $file['name']); $bytes = file_get_contents($file['tmp_name'], false, null, -1, 1024); $type = \KD2\FileInfo::guessMimeType($bytes); if (!$type) { |
︙ | ︙ | |||
306 307 308 309 310 311 312 | ]); return new Fichiers($db->lastInsertRowID()); } static public function SkrivHTML($args, $content, $skriv) { | | | | > > > > > > > | > > > > > > > | > > > | > > | 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | ]); return new Fichiers($db->lastInsertRowID()); } static public function SkrivHTML($args, $content, $skriv) { if (empty($args['id']) && !empty($args[0])) { $args = ['id' => (int)$args[0]]; } if (empty($args['id'])) { return $skriv->parseError('/!\ Tag fichier : aucun numéro de fichier indiqué.'); } $db = DB::getInstance(); try { $file = new Fichiers($args['id']); } catch (\InvalidArgumentException $e) { return $skriv->parseError('/!\ Tag fichier : ' . $e->getMessage()); } if ($file->image) { return ' <figure class="image"> <a href="'.$file->getURL().'"><img src="'.$file->getURL(true).'" alt="'.htmlspecialchars($file->nom, ENT_QUOTES, 'UTF-8').'" /></a> </figure>'; } else { return '<a href="'.$file->getURL().'">'.htmlspecialchars($file->nom, ENT_QUOTES, 'UTF-8').'</a>'; } } } |
Modified src/include/lib/Garradin/Static_Cache.php from [80b1dfbb7b] to [1bdc82588f].
︙ | ︙ | |||
75 76 77 78 79 80 81 | { return file_exists(self::_getCachePath($id)); } static public function remove($id) { $path = self::_getCachePath($id); | | | 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | { return file_exists(self::_getCachePath($id)); } static public function remove($id) { $path = self::_getCachePath($id); return @unlink($path); } static public function clean($expire = self::CLEAN_EXPIRE) { $dir = self::_getCacheDir(); $d = dir($dir); |
︙ | ︙ |
Modified src/include/lib/Garradin/Utils.php from [07f19bdcc3] to [b300101854].
︙ | ︙ | |||
386 387 388 389 390 391 392 | * @return string Texte HTML */ static public function SkrivToHTML($str) { if (!self::$skriv) { self::$skriv = new \KD2\SkrivLite; | | | 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | * @return string Texte HTML */ static public function SkrivToHTML($str) { if (!self::$skriv) { self::$skriv = new \KD2\SkrivLite; self::$skriv->registerExtension('fichier', ['\\Garradin\\Fichiers', 'SkrivHTML']); } $str = self::$skriv->render($str); return $str; } |
︙ | ︙ |
Modified src/www/.htaccess from [fe5c9d563a] to [6bda533d32].
1 2 3 4 5 6 7 8 9 10 11 | <IfModule mod_rewrite.c> RewriteEngine on RewriteRule admin/plugin/(.*?)/(.*) /admin/plugin.php?_p=$1&_u=$2 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* /index.php [QSA,L] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 404 /index.php </IfModule> | > | 1 2 3 4 5 6 7 8 9 10 11 12 | <IfModule mod_rewrite.c> RewriteEngine on RewriteRule admin/plugin/(.*?)/(.*) /admin/plugin.php?_p=$1&_u=$2 [QSA,L] RewriteRule f/([\d\w]+)/(t/)?(.*) /file.php?id=$1&thumb=$2&file=$3 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* /index.php [QSA,L] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 404 /index.php </IfModule> |
Modified src/www/_route.php from [af38449459] to [7717833717].
︙ | ︙ | |||
19 20 21 22 23 24 25 26 27 28 29 30 | return false; } elseif (preg_match('!/admin/plugin/(.+)/(.*)!', $uri, $match)) { $_GET['_p'] = $match[1]; $_GET['_u'] = $match[2]; require __DIR__ . '/admin/plugin.php'; } else { require __DIR__ . '/index.php'; } | > > > > > > > | 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | return false; } elseif (preg_match('!/admin/plugin/(.+)/(.*)!', $uri, $match)) { $_GET['_p'] = $match[1]; $_GET['_u'] = $match[2]; require __DIR__ . '/admin/plugin.php'; } elseif (preg_match('!/f/([\d\w]+)/(t/)?(.+)!', $uri, $match)) { $_GET['id'] = $match[1]; $_GET['thumb'] = $match[2]; $_GET['file'] = $match[3]; require __DIR__ . '/file.php'; } else { require __DIR__ . '/index.php'; } |
Added src/www/file.php version [994f0ee89a].
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php namespace Garradin; require __DIR__ . '/_inc.php'; $id = isset($_GET['id']) ? $_GET['id'] : false; $thumb = !empty($_GET['thumb']) ? true : false; $filename = !empty($_GET['file']) ? $_GET['file'] : false; if (empty($id)) { throw new UserException('Fichier inconnu.'); } $id = base_convert($id, 36, 10); $file = new Fichiers((int)$id); $membres = new Membres; $is_logged = $membres->isLogged(); if (!$file->checkAccess($membres->getLoggedUser())) { header('HTTP/1.1 403 Forbidden', true, 403); throw new UserException('Vous n\'avez pas accès à ce fichier.'); } if ($thumb) { $file->serveThumbnail(); } else { $file->serve(); } |
Modified src/www/index.php from [9ff0d03ddb] to [36cb4b20f1].
1 2 3 4 5 6 7 | <?php namespace Garradin; require __DIR__ . '/_inc.php'; $squelette = new Squelette; $squelette->dispatchURI(); | > | 1 2 3 4 5 6 7 8 | <?php namespace Garradin; require __DIR__ . '/_inc.php'; $squelette = new Squelette; $squelette->dispatchURI(); |