1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2022 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <https://www.gnu.org/licenses/>. 16 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Services; 21 22use Fisharebest\Webtrees\Exceptions\FileUploadException; 23use Fisharebest\Webtrees\FlashMessages; 24use Fisharebest\Webtrees\I18N; 25use Fisharebest\Webtrees\Registry; 26use Fisharebest\Webtrees\Tree; 27use Fisharebest\Webtrees\Validator; 28use Illuminate\Database\Capsule\Manager as DB; 29use Illuminate\Database\Query\Expression; 30use Illuminate\Database\Query\JoinClause; 31use Illuminate\Support\Collection; 32use InvalidArgumentException; 33use League\Flysystem\FilesystemException; 34use League\Flysystem\FilesystemOperator; 35use League\Flysystem\FilesystemReader; 36use League\Flysystem\StorageAttributes; 37use Psr\Http\Message\ServerRequestInterface; 38use RuntimeException; 39 40use function array_combine; 41use function array_diff; 42use function array_intersect; 43use function dirname; 44use function explode; 45use function ini_get; 46use function intdiv; 47use function is_float; 48use function min; 49use function pathinfo; 50use function sha1; 51use function sort; 52use function str_contains; 53use function strlen; 54use function strtoupper; 55use function strtr; 56use function substr; 57use function trim; 58 59use const PATHINFO_EXTENSION; 60use const PHP_INT_MAX; 61use const UPLOAD_ERR_OK; 62 63/** 64 * Managing media files. 65 */ 66class MediaFileService 67{ 68 public const EXTENSION_TO_FORM = [ 69 'JPEG' => 'JPG', 70 'TIFF' => 'TIF', 71 ]; 72 73 private const IGNORE_FOLDERS = [ 74 // Old versions of webtrees 75 'thumbs', 76 'watermarks', 77 // Windows 78 'Thumbs.db', 79 // Synology 80 '@eaDir', 81 // QNAP, 82 '.@__thumb', 83 // WebDAV, 84 '_DAV', 85 ]; 86 87 /** 88 * What is the largest file a user may upload? 89 */ 90 public function maxUploadFilesize(): string 91 { 92 $sizePostMax = $this->parseIniFileSize((string) ini_get('post_max_size')); 93 $sizeUploadMax = $this->parseIniFileSize((string) ini_get('upload_max_filesize')); 94 95 $bytes = min($sizePostMax, $sizeUploadMax); 96 $kb = intdiv($bytes + 1023, 1024); 97 98 return I18N::translate('%s KB', I18N::number($kb)); 99 } 100 101 /** 102 * Returns the given size from an ini value in bytes. 103 * 104 * @param string $size 105 * 106 * @return int 107 */ 108 private function parseIniFileSize(string $size): int 109 { 110 $number = (int) $size; 111 112 $units = [ 113 'g' => 1073741824, 114 'G' => 1073741824, 115 'm' => 1048576, 116 'M' => 1048576, 117 'k' => 1024, 118 'K' => 1024, 119 ]; 120 121 $number *= $units[substr($size, -1)] ?? 1; 122 123 if (is_float($number)) { 124 // Probably a 32bit version of PHP, with an INI setting >= 2GB 125 return PHP_INT_MAX; 126 } 127 128 return $number; 129 } 130 131 /** 132 * A list of media files not already linked to a media object. 133 * 134 * @param Tree $tree 135 * 136 * @return array<string> 137 */ 138 public function unusedFiles(Tree $tree): array 139 { 140 $used_files = DB::table('media_file') 141 ->where('m_file', '=', $tree->id()) 142 ->where('multimedia_file_refn', 'NOT LIKE', 'http://%') 143 ->where('multimedia_file_refn', 'NOT LIKE', 'https://%') 144 ->pluck('multimedia_file_refn') 145 ->all(); 146 147 $media_filesystem = $tree->mediaFilesystem(); 148 $disk_files = $this->allFilesOnDisk($media_filesystem, '', FilesystemReader::LIST_DEEP)->all(); 149 $unused_files = array_diff($disk_files, $used_files); 150 151 sort($unused_files); 152 153 return array_combine($unused_files, $unused_files); 154 } 155 156 /** 157 * Store an uploaded file (or URL), either to be added to a media object 158 * or to create a media object. 159 * 160 * @param ServerRequestInterface $request 161 * 162 * @return string The value to be stored in the 'FILE' field of the media object. 163 * @throws FilesystemException 164 */ 165 public function uploadFile(ServerRequestInterface $request): string 166 { 167 $tree = Validator::attributes($request)->tree(); 168 $file_location = Validator::parsedBody($request)->string('file_location'); 169 170 switch ($file_location) { 171 case 'url': 172 $remote = Validator::parsedBody($request)->string('remote'); 173 174 if (str_contains($remote, '://')) { 175 return $remote; 176 } 177 178 return ''; 179 180 case 'unused': 181 $unused = Validator::parsedBody($request)->string('unused'); 182 183 if ($tree->mediaFilesystem()->fileExists($unused)) { 184 return $unused; 185 } 186 187 return ''; 188 189 case 'upload': 190 $folder = Validator::parsedBody($request)->string('folder'); 191 $auto = Validator::parsedBody($request)->string('auto'); 192 $new_file = Validator::parsedBody($request)->string('new_file'); 193 194 $uploaded_file = $request->getUploadedFiles()['file'] ?? null; 195 196 if ($uploaded_file === null || $uploaded_file->getError() !== UPLOAD_ERR_OK) { 197 throw new FileUploadException($uploaded_file); 198 } 199 200 // The filename 201 $new_file = strtr($new_file, ['\\' => '/']); 202 if ($new_file !== '' && !str_contains($new_file, '/')) { 203 $file = $new_file; 204 } else { 205 $file = $uploaded_file->getClientFilename(); 206 } 207 208 // The folder 209 $folder = strtr($folder, ['\\' => '/']); 210 $folder = trim($folder, '/'); 211 if ($folder !== '') { 212 $folder .= '/'; 213 } 214 215 // Generate a unique name for the file? 216 if ($auto === '1' || $tree->mediaFilesystem()->fileExists($folder . $file)) { 217 $folder = ''; 218 $extension = pathinfo($uploaded_file->getClientFilename(), PATHINFO_EXTENSION); 219 $file = sha1((string) $uploaded_file->getStream()) . '.' . $extension; 220 } 221 222 try { 223 $tree->mediaFilesystem()->writeStream($folder . $file, $uploaded_file->getStream()->detach()); 224 225 return $folder . $file; 226 } catch (RuntimeException | InvalidArgumentException $ex) { 227 FlashMessages::addMessage(I18N::translate('There was an error uploading your file.')); 228 229 return ''; 230 } 231 } 232 233 return ''; 234 } 235 236 /** 237 * Convert the media file attributes into GEDCOM format. 238 * 239 * @param string $file 240 * @param string $type 241 * @param string $title 242 * @param string $note 243 * 244 * @return string 245 */ 246 public function createMediaFileGedcom(string $file, string $type, string $title, string $note): string 247 { 248 $gedcom = '1 FILE ' . $file; 249 250 if (str_contains($file, '://')) { 251 $format = ''; 252 } else { 253 $format = strtoupper(pathinfo($file, PATHINFO_EXTENSION)); 254 $format = self::EXTENSION_TO_FORM[$format] ?? $format; 255 } 256 257 if ($format !== '' && strlen($format) <= 4) { 258 $gedcom .= "\n2 FORM " . $format; 259 } elseif ($type !== '') { 260 $gedcom .= "\n2 FORM"; 261 } 262 263 if ($type !== '') { 264 $gedcom .= "\n3 TYPE " . $type; 265 } 266 267 if ($title !== '') { 268 $gedcom .= "\n2 TITL " . $title; 269 } 270 271 if ($note !== '') { 272 // Convert HTML line endings to GEDCOM continuations 273 $gedcom .= "\n1 NOTE " . strtr($note, ["\r\n" => "\n2 CONT "]); 274 } 275 276 return $gedcom; 277 } 278 279 /** 280 * Fetch a list of all files on disk (in folders used by any tree). 281 * 282 * @param FilesystemOperator $filesystem $filesystem to search 283 * @param string $folder Root folder 284 * @param bool $subfolders Include subfolders 285 * 286 * @return Collection<int,string> 287 */ 288 public function allFilesOnDisk(FilesystemOperator $filesystem, string $folder, bool $subfolders): Collection 289 { 290 try { 291 $files = $filesystem 292 ->listContents($folder, $subfolders) 293 ->filter(fn (StorageAttributes $attributes): bool => $attributes->isFile()) 294 ->filter(fn (StorageAttributes $attributes): bool => !$this->ignorePath($attributes->path())) 295 ->map(fn (StorageAttributes $attributes): string => $attributes->path()) 296 ->toArray(); 297 } catch (FilesystemException $ex) { 298 $files = []; 299 } 300 301 return new Collection($files); 302 } 303 304 /** 305 * Fetch a list of all files on in the database. 306 * 307 * @param string $media_folder Root folder 308 * @param bool $subfolders Include subfolders 309 * 310 * @return Collection<int,string> 311 */ 312 public function allFilesInDatabase(string $media_folder, bool $subfolders): Collection 313 { 314 $query = DB::table('media_file') 315 ->join('gedcom_setting', 'gedcom_id', '=', 'm_file') 316 ->where('setting_name', '=', 'MEDIA_DIRECTORY') 317 //->where('multimedia_file_refn', 'LIKE', '%/%') 318 ->where('multimedia_file_refn', 'NOT LIKE', 'http://%') 319 ->where('multimedia_file_refn', 'NOT LIKE', 'https://%') 320 ->where(new Expression('setting_value || multimedia_file_refn'), 'LIKE', $media_folder . '%') 321 ->select(new Expression('setting_value || multimedia_file_refn AS path')) 322 ->orderBy(new Expression('setting_value || multimedia_file_refn')); 323 324 if (!$subfolders) { 325 $query->where(new Expression('setting_value || multimedia_file_refn'), 'NOT LIKE', $media_folder . '%/%'); 326 } 327 328 return $query->pluck('path'); 329 } 330 331 /** 332 * Generate a list of all folders used by a tree. 333 * 334 * @param Tree $tree 335 * 336 * @return Collection<int,string> 337 * @throws FilesystemException 338 */ 339 public function mediaFolders(Tree $tree): Collection 340 { 341 $folders = $tree->mediaFilesystem() 342 ->listContents('', FilesystemReader::LIST_DEEP) 343 ->filter(fn (StorageAttributes $attributes): bool => $attributes->isDir()) 344 ->filter(fn (StorageAttributes $attributes): bool => !$this->ignorePath($attributes->path())) 345 ->map(fn (StorageAttributes $attributes): string => $attributes->path()) 346 ->toArray(); 347 348 return new Collection($folders); 349 } 350 351 /** 352 * Generate a list of all folders in either the database or the filesystem. 353 * 354 * @param FilesystemOperator $data_filesystem 355 * 356 * @return Collection<array-key,string> 357 * @throws FilesystemException 358 */ 359 public function allMediaFolders(FilesystemOperator $data_filesystem): Collection 360 { 361 $db_folders = DB::table('media_file') 362 ->leftJoin('gedcom_setting', static function (JoinClause $join): void { 363 $join 364 ->on('gedcom_id', '=', 'm_file') 365 ->where('setting_name', '=', 'MEDIA_DIRECTORY'); 366 }) 367 ->where('multimedia_file_refn', 'NOT LIKE', 'http://%') 368 ->where('multimedia_file_refn', 'NOT LIKE', 'https://%') 369 ->select(new Expression("COALESCE(setting_value, 'media/') || multimedia_file_refn AS path")) 370 ->pluck('path') 371 ->map(static function (string $path): string { 372 return dirname($path) . '/'; 373 }); 374 375 $media_roots = DB::table('gedcom') 376 ->leftJoin('gedcom_setting', static function (JoinClause $join): void { 377 $join 378 ->on('gedcom.gedcom_id', '=', 'gedcom_setting.gedcom_id') 379 ->where('setting_name', '=', 'MEDIA_DIRECTORY'); 380 }) 381 ->where('gedcom.gedcom_id', '>', '0') 382 ->pluck(new Expression("COALESCE(setting_value, 'media/')")) 383 ->uniqueStrict(); 384 385 $disk_folders = new Collection($media_roots); 386 387 foreach ($media_roots as $media_folder) { 388 $tmp = $data_filesystem 389 ->listContents($media_folder, FilesystemReader::LIST_DEEP) 390 ->filter(fn (StorageAttributes $attributes): bool => $attributes->isDir()) 391 ->filter(fn (StorageAttributes $attributes): bool => !$this->ignorePath($attributes->path())) 392 ->map(fn (StorageAttributes $attributes): string => $attributes->path() . '/') 393 ->toArray(); 394 395 $disk_folders = $disk_folders->concat($tmp); 396 } 397 398 return $disk_folders->concat($db_folders) 399 ->uniqueStrict() 400 ->sort(I18N::comparator()) 401 ->mapWithKeys(static function (string $folder): array { 402 return [$folder => $folder]; 403 }); 404 } 405 406 /** 407 * Ignore special media folders. 408 * 409 * @param string $path 410 * 411 * @return bool 412 */ 413 private function ignorePath(string $path): bool 414 { 415 return array_intersect(self::IGNORE_FOLDERS, explode('/', $path)) !== []; 416 } 417} 418