Overview
Comment: | Migrate more from Fichiers to File and Files |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | dev |
Files: | files | file ages | folders |
SHA1: |
332a8b64949a1f330a218c9617602e43 |
User & Date: | bohwaz on 2020-12-10 20:01:47 |
Other Links: | branch diff | manifest | tags |
Context
2020-12-11
| ||
01:11 | Some kind of progress, or not check-in: cd88e798f2 user: bohwaz tags: dev | |
2020-12-10
| ||
20:01 | Migrate more from Fichiers to File and Files check-in: 332a8b6494 user: bohwaz tags: dev | |
18:21 | Merge with trunk check-in: ab8bff586d user: bohwaz tags: dev | |
Changes
Modified src/include/data/1.1.0_schema.sql from [d979d9fd8b] to [28445b9f61].
︙ | ︙ | |||
259 260 261 262 263 264 265 266 267 | -- Files metadata ( id INTEGER NOT NULL PRIMARY KEY, path TEXT NOT NULL, name TEXT NOT NULL, -- file name (eg. image1234.jpeg) type TEXT NULL, -- MIME type image INTEGER NOT NULL DEFAULT 0, -- 1 = image reconnue created TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(created) IS NOT NULL AND datetime(created) = created), modified TEXT NULL CHECK (datetime(modified) IS NULL OR datetime(modified) = modified), | > > > > > > | > < | < < | > | | | | 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | -- Files metadata ( id INTEGER NOT NULL PRIMARY KEY, path TEXT NOT NULL, name TEXT NOT NULL, -- file name (eg. image1234.jpeg) type TEXT NULL, -- MIME type image INTEGER NOT NULL DEFAULT 0, -- 1 = image reconnue size INTEGER NOT NULL DEFAULT 0, hash TEXT NOT NULL, -- Hash SHA1 du contenu du fichier storage TEXT NULL, -- Storage medium, NULL means stored in content BLOB storage_path TEXT NULL, created TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(created) IS NOT NULL AND datetime(created) = created), modified TEXT NULL CHECK (datetime(modified) IS NULL OR datetime(modified) = modified), author_id INTEGER NULL REFERENCES membres (id) ON DELETE SET NULL ); CREATE INDEX IF NOT EXISTS files_path ON files (path); CREATE INDEX IF NOT EXISTS files_date ON files (datetime); CREATE INDEX IF NOT EXISTS files_hash ON files (hash); CREATE TABLE IF NOT EXISTS files_contents -- Contenu des fichiers ( id INTEGER NOT NULL PRIMARY KEY, hash TEXT NOT NULL, -- Hash SHA1 du contenu du fichier content BLOB NULL ); CREATE UNIQUE INDEX IF NOT EXISTS files_contents_hash ON files_contents (hash); CREATE TABLE IF NOT EXISTS files_folders ( id INTEGER NOT NULL PRIMARY KEY, parent_id INTEGER NULL REFERENCES files_folders(id) ON DELETE CASCADE, name TEXT NOT NULL ); CREATE VIRTUAL TABLE IF NOT EXISTS files_search USING fts4 -- Search inside files content ( id INT PRIMARY KEY NOT NULL REFERENCES files_contents(id), content TEXT NULL -- Text content ); CREATE TABLE IF NOT EXISTS files_links -- This references use of a file outside of the documents module -- One file can only be linked to one thing ( id INTEGER NOT NULL PRIMARY KEY REFERENCES fichiers (id) ON DELETE CASCADE, file_id INTEGER NULL REFERENCES fichiers (id) ON DELETE CASCADE, user_id INTEGER NULL REFERENCES membres (id) ON DELETE CASCADE, transaction_id INTEGER NULL REFERENCES acc_transactions (id) ON DELETE CASCADE, config TEXT NULL REFERENCES config (valeur) ON DELETE CASCADE, web INTEGER NULL, -- Make sure that only one is filled CHECK ((user_id IS NULL) + (transaction_id IS NULL) + (config IS NULL) + (web IS NULL) + (file_id IS NULL) = 1) ); CREATE UNIQUE INDEX files_links_unique ON files_links (file_id, user_id, transaction_id, config, web); -- FIXME: rename to english CREATE TABLE IF NOT EXISTS recherches -- Recherches enregistrées |
︙ | ︙ |
Modified src/include/lib/Garradin/Entities/Files/File.php from [4fd57e6360] to [dee3022a27].
︙ | ︙ | |||
8 9 10 11 12 13 14 15 16 17 | use Garradin\UserException; class File extends Entity { const TABLE = 'files'; protected $id; protected $name; protected $_types = [ | > > > > > > > > > > > > > | > > > > > > | > > > > > > > > > > > > > > > > > > > > > > > > | | > > > | 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | use Garradin\UserException; class File extends Entity { const TABLE = 'files'; protected $id; protected $path; protected $name; protected $type; protected $image; protected $size; protected $hash; protected $storage; protected $storage_path; protected $created; protected $modified; protected $author_id; protected $_types = [ 'id' => 'int', 'path' => 'string', 'name' => 'string', 'type' => '?string', 'image' => 'int', 'size' => 'int', 'hash' => 'string', 'storage' => '?string', 'storage_path' => '?string', 'created' => 'DateTime', 'modified' => 'DateTime', 'author_id' => '?int', ]; protected $_public; /** * Tailles de miniatures autorisées, pour ne pas avoir 500 fichiers générés avec 500 tailles différentes * @var array */ const ALLOWED_THUMB_SIZES = [200, 500, 1200]; const LINK_USER = 'user_id'; const LINK_TRANSACTION = 'transaction_id'; const LINK_CONFIG = 'config'; const LINK_WEB = 'web'; const PATH_USER = 'users/%d'; const PATH_TRANSACTION = 'accounting/transactions/%d'; const PATH_CONFIG = 'config'; const PATH_WEB = 'web/%s'; const THUMB_CACHE_ID = 'file.thumb.%d.%d'; public function selfCheck(): void { parent::selfCheck(); } public function delete(): bool { $return = parent::delete(); // clean up thumbs foreach (self::ALLOWED_THUMB_SIZES as $size) { Static_Cache::remove(sprintf(self::THUMB_CACHE_ID, $this->id(), $size)); } return $return; } static protected function store(?string $path, string $name, string $source_path = null, $source_content = null): self { assert($path || $content); |
︙ | ︙ | |||
146 147 148 149 150 151 152 | $name = preg_replace('/\s+/', '_', $file['name']); $name = preg_replace('/[^\d\w._-]/ui', '', $name); return self::store($path, $name, $file['tmp_name']); } | | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 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 482 483 484 485 | $name = preg_replace('/\s+/', '_', $file['name']); $name = preg_replace('/[^\d\w._-]/ui', '', $name); return self::store($path, $name, $file['tmp_name']); } /** * Récupération du message d'erreur * @param integer $error Code erreur du $_FILE * @return string Message d'erreur */ static public function getErrorMessage($error) { switch ($error) { case UPLOAD_ERR_INI_SIZE: return 'Le fichier excède la taille permise par la configuration du serveur.'; case UPLOAD_ERR_FORM_SIZE: return 'Le fichier excède la taille permise par le formulaire.'; case UPLOAD_ERR_PARTIAL: return 'L\'envoi du fichier a été interrompu.'; case UPLOAD_ERR_NO_FILE: return 'Aucun fichier n\'a été reçu.'; case UPLOAD_ERR_NO_TMP_DIR: return 'Pas de répertoire temporaire pour stocker le fichier.'; case UPLOAD_ERR_CANT_WRITE: return 'Impossible d\'écrire le fichier sur le disque du serveur.'; case UPLOAD_ERR_EXTENSION: return 'Une extension du serveur a interrompu l\'envoi du fichier.'; default: return 'Erreur inconnue: ' . $error; } } public function url(?int $size = null): string { return self::getFileURL($this->id, $this->name, $this->hash, $size); } /** * Renvoie l'URL vers un fichier * @param integer $id Numéro du fichier * @param string $name Nom de fichier avec extension * @param integer $size Taille de la miniature désirée (pour les images) * @return string URL du fichier */ static public function getFileURL(int $id, string $name, string $hash, ?int $size = null): string { $url = sprintf('%sf/%s/%s?', WWW_URL, base_convert((int)$id, 10, 36), $name); if ($size) { $url .= self::_findNearestThumbSize($size) . 'px&'; } $url .= substr($hash, 0, 10); return $url; } /** * Renvoie la taille de miniature la plus proche de la taille demandée * @param integer $size Taille demandée * @return integer Taille possible */ static protected function _findNearestThumbSize($size) { $size = (int) $size; if (in_array($size, self::ALLOWED_THUMB_SIZES)) { return $size; } foreach (self::ALLOWED_THUMB_SIZES as $s) { if ($s >= $size) { return $s; } } return max(self::ALLOWED_THUMB_SIZES); } /** * Lier un fichier à un contenu * @param string $type Type de contenu (constantes LINK_*) * @param integer $foreign_id ID du contenu lié * @return boolean TRUE en cas de succès */ public function linkTo(string $type, int $foreign_id): bool { $db = DB::getInstance(); static $types = [self::LINK_WEB, self::LINK_FILE, self::LINK_TRANSACTION, self::LINK_USER, self::LINK_CONFIG]; if (!in_array($type, $types)) { throw new \InvalidArgumentException('Unknown file link type.'); } if ($db->test('files_links', 'id = ?', $this->id())) { throw new \LogicException('This file is already linked to something else'); } $sql = sprintf('INSERT OR IGNORE INTO files_links (id, %s) VALUES (?, ?);', $type); return $db->preparedQuery($sql, [$this->id, $foreign_id]); } public function getLinkedId(string $type): ?int { static $types = [self::LINK_WEB, self::LINK_FILE, self::LINK_TRANSACTION, self::LINK_USER, self::LINK_CONFIG]; if (!in_array($type, $types)) { throw new \InvalidArgumentException('Unknown file link type.'); } return DB::getInstance()->firstColumn(sprintf('SELECT %s FROM files_links WHERE id = %d;', $type, $this->id())); } /** * Envoie le fichier au client HTTP */ public function serve(?Session $session = null): void { if (!$this->checkAccess($session)) { header('HTTP/1.1 403 Forbidden', true, 403); throw new UserException('Accès interdit'); return; } $path = Files::callStorage('getPath', $this); $content = null === $path ? Files::callStorage('fetch', $this) : null; $this->_serve($session, $path, $content); } /** * Envoie une miniature à la taille indiquée au client HTTP */ public function serveThumbnail(?Session $session = null, ?int $width = null): void { if (!$this->checkAccess($session)) { header('HTTP/1.1 403 Forbidden', true, 403); throw new UserException('Accès interdit'); return; } if (!$this->image) { throw new UserException('Il n\'est pas possible de fournir une miniature pour un fichier qui n\'est pas une image.'); } if (!$width) { $width = reset(self::ALLOWED_THUMB_SIZES); } if (!in_array($width, self::ALLOWED_THUMB_SIZES)) { throw new UserException('Cette taille de miniature n\'est pas autorisée.'); } $cache_id = sprintf(self::THUMB_CACHE_ID, $this->id(), $width); $destination = Static_Cache::getPath($cache_id); // La miniature n'existe pas dans le cache statique, on la crée if (!Static_Cache::exists($cache_id)) { try { if ($path = Files::callStorage('getPath', $file)) { (new Image($source))->resize($width)->save($destination); } elseif ($content = Files::callStorage('fetch', $file)) { Image::createFromBlob($content)->resize($width)->save($destination); } else { throw new \RuntimeException('Unable to fetch file'); } } catch (\RuntimeException $e) { throw new UserException('Impossible de créer la miniature'); } } $this->_serve($session, $path, null); } /** * 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(?string $path, ?string $content): void { if ($this->isPublic()) { Utils::HTTPCache($this->hash, $this->datetime); } else { // Disable browser cache header('Pragma: private'); header('Expires: -1'); header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0'); } header(sprintf('Content-Type: %s', $this->type)); header(sprintf('Content-Disposition: inline; filename="%s"', $this->name)); // Utilisation de XSendFile si disponible if (null !== $path && ENABLE_XSENDFILE && isset($_SERVER['SERVER_SOFTWARE'])) { if (stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) { header('X-Sendfile: ' . $path); return; } else if (stristr($_SERVER['SERVER_SOFTWARE'], 'lighttpd')) { header('X-Sendfile: ' . $path); return; } } // Désactiver gzip if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', 1); } @ini_set('zlib.output_compression', 'Off'); header(sprintf('Content-Length: %d', $this->size)); if (@ob_get_length()) { @ob_clean(); } flush(); if (null !== $path) { readfile($path); } else { echo $content; } } public function isPublic(): bool { if (null === $this->_public) { throw new \RuntimeException('_public is unset'); } return $this->_public; } public function checkAccess(Session $session): bool { $link = DB::getInstance()->first('SELECT * FROM files_links WHERE id = ?;', $this->id()); $this->_public = false; // Everyone has access to web content as long it's not draft (0) if ($link->{LINK_WEB} == 1) { $this->_public = true; return true; } elseif ($link->{LINK_WEB} == 0) { return false; } // Everyone has access to config files (logo etc.) else if ($link->{LINK_CONFIG}) { $this->_public = true; return true; } else if ($link->{LINK_TRANSACTION} && $session->canAccess('compta', Membres::DROIT_ACCES)) { return true; } // The user can access his own profile files else if ($link->{LINK_USER} && $link->{LINK_USER} == $session->getUser()->id) { return true; } // Only users able to manage users can see their profile files else if ($link->{LINK_USER} && $session->canAccess('membres', Membres::DROIT_ECRITURE)) { return true; } return $session->canAccess(Session::SECTION_DOCUMENTS, Membres::DROIT_ACCES); } } |
Modified src/include/lib/Garradin/Fichiers.php from [9ff6c36622] to [b460df65f5].
1 2 3 4 5 6 7 8 9 | <?php namespace Garradin; use KD2\Graphics\Image; use Garradin\Membres\Session; class Fichiers { | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php namespace Garradin; use KD2\Graphics\Image; use Garradin\Membres\Session; class Fichiers { /** * 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 */ |
︙ | ︙ | |||
457 458 459 460 461 462 463 | $a = $db->quote($a); }); $query = sprintf('SELECT hash, 1 FROM fichiers_contenu WHERE hash IN (%s);', implode(', ', $list)); return $db->getAssoc($query); } | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | $a = $db->quote($a); }); $query = sprintf('SELECT hash, 1 FROM fichiers_contenu WHERE hash IN (%s);', implode(', ', $list)); return $db->getAssoc($query); } /** * Envoie un fichier déjà stocké * * @param string $name Nom du fichier * @param string $hash Hash SHA1 du contenu du fichier |
︙ | ︙ | |||
518 519 520 521 522 523 524 | 'type' => $file->type, 'image' => (int)$file->image, ]); return new Fichiers($db->lastInsertRowID()); } | < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 'type' => $file->type, 'image' => (int)$file->image, ]); return new Fichiers($db->lastInsertRowID()); } /** * Enlève d'une liste de fichiers ceux qui sont mentionnés dans un texte wiki * @param array $files Liste de fichiers * @param string $text texte wiki * @return array Un tableau qui ne contient pas les fichiers mentionnés dans $text */ |
︙ | ︙ |
Modified src/include/lib/Garradin/Files/Files.php from [9ec11674dc] to [c115561b4c].
︙ | ︙ | |||
24 25 26 27 28 29 30 31 32 33 34 35 36 37 | $to = get_class(__NAMESPACE__ . '\\Backend\\' . $to); foreach ($res as $file) { $from_path = call_user_func([$from, 'path'], $file); call_user_func([$to, 'store'], $file, $from_path); } } static public function generatePathsIndex(): void { $all = DB::getInstance()->getAssoc('SELECT path, path FROM files GROUP BY path;'); $paths = []; foreach ($all as $path) { | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 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 57 58 59 60 61 62 63 64 65 66 67 68 | $to = get_class(__NAMESPACE__ . '\\Backend\\' . $to); foreach ($res as $file) { $from_path = call_user_func([$from, 'path'], $file); call_user_func([$to, 'store'], $file, $from_path); } } static public function deleteOrphanFiles() { $db = DB::getInstance(); $sql = 'SELECT f.* FROM files f LEFT JOIN files_links l ON f.id = l.id WHERE l.id IS NULL;'; foreach ($db->iterate($sql) as $file) { $f = new Fichiers($file->id, (array) $file); $f->remove(); } // Remove any left-overs $db->exec('DELETE FROM files_contents WHERE hash NOT IN (SELECT DISTINCT hash FROM files);'); } static public function deleteLinkedFiles(string $type, ?int $value = null) { foreach (self::iterateLinkedTo($type, $value) as $file) { $file->delete(); } self::deleteOrphanFiles(); } static public function iterateLinkedTo(string $type, ?int $value = null) { $where = $value ? sprintf('l.%s = %d', $value) : sprintf('l.%s IS NOT NULL'); $sql = sprintf('SELECT f.* FROM @TABLE f INNER JOIN files_links l ON l.id = f.id WHERE %s;', $where); return EM::getInstance(File::class)->iterate($sql); } static public function generatePathsIndex(): void { $all = DB::getInstance()->getAssoc('SELECT path, path FROM files GROUP BY path;'); $paths = []; foreach ($all as $path) { |
︙ | ︙ |
Modified src/include/lib/Garradin/Files/Storage/SQLite.php from [09143891cd] to [e6d2cf42a4].
︙ | ︙ | |||
47 48 49 50 51 52 53 | static public function list(string $path): ?array { return null; } static public function getPath(File $file): ?string { | | | 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | static public function list(string $path): ?array { return null; } static public function getPath(File $file): ?string { return self::_getFilePathFromCache($file); } static public function display(File $file): void { readfile(self::getFilePathFromCache($file)); } |
︙ | ︙ |