xref: /webtrees/app/Media.php (revision 6bdf767435631ad1dc27ec1ffd855d43dbdce907)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2017 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18use Exception;
19use Fisharebest\Webtrees\Functions\FunctionsMedia;
20use Fisharebest\Webtrees\Functions\FunctionsPrintFacts;
21
22/**
23 * A GEDCOM media (OBJE) object.
24 */
25class Media extends GedcomRecord {
26	const RECORD_TYPE = 'OBJE';
27	const URL_PREFIX  = 'mediaviewer.php?mid=';
28
29	/** @var string The "TITL" value from the GEDCOM */
30	private $title = '';
31
32	/** @var string The "FILE" value from the GEDCOM */
33	private $file = '';
34
35	/**
36	 * Create a GedcomRecord object from raw GEDCOM data.
37	 *
38	 * @param string      $xref
39	 * @param string      $gedcom  an empty string for new/pending records
40	 * @param string|null $pending null for a record with no pending edits,
41	 *                             empty string for records with pending deletions
42	 * @param Tree        $tree
43	 */
44	public function __construct($xref, $gedcom, $pending, $tree) {
45		parent::__construct($xref, $gedcom, $pending, $tree);
46
47		if (preg_match('/\n1 FILE (.+)/', $gedcom . $pending, $match)) {
48			$this->file = $match[1];
49		}
50		if (preg_match('/\n\d TITL (.+)/', $gedcom . $pending, $match)) {
51			$this->title = $match[1];
52		}
53	}
54
55	/**
56	 * Each object type may have its own special rules, and re-implement this function.
57	 *
58	 * @param int $access_level
59	 *
60	 * @return bool
61	 */
62	protected function canShowByType($access_level) {
63		// Hide media objects if they are attached to private records
64		$linked_ids = Database::prepare(
65			"SELECT l_from FROM `##link` WHERE l_to = ? AND l_file = ?"
66		)->execute([
67			$this->xref, $this->tree->getTreeId(),
68		])->fetchOneColumn();
69		foreach ($linked_ids as $linked_id) {
70			$linked_record = GedcomRecord::getInstance($linked_id, $this->tree);
71			if ($linked_record && !$linked_record->canShow($access_level)) {
72				return false;
73			}
74		}
75
76		// ... otherwise apply default behaviour
77		return parent::canShowByType($access_level);
78	}
79
80	/**
81	 * Fetch data from the database
82	 *
83	 * @param string $xref
84	 * @param int    $tree_id
85	 *
86	 * @return null|string
87	 */
88	protected static function fetchGedcomRecord($xref, $tree_id) {
89		return Database::prepare(
90			"SELECT m_gedcom FROM `##media` WHERE m_id = :xref AND m_file = :tree_id"
91		)->execute([
92			'xref'    => $xref,
93			'tree_id' => $tree_id,
94		])->fetchOne();
95	}
96
97	/**
98	 * Get the first note attached to this media object
99	 *
100	 * @return null|string
101	 */
102	public function getNote() {
103		$note = $this->getFirstFact('NOTE');
104		if ($note) {
105			$text = $note->getValue();
106			if (preg_match('/^@' . WT_REGEX_XREF . '@$/', $text)) {
107				$text = $note->getTarget()->getNote();
108			}
109
110			return $text;
111		} else {
112			return '';
113		}
114	}
115
116	/**
117	 * Get the main media filename
118	 *
119	 * @return string
120	 */
121	public function getFilename() {
122		return $this->file;
123	}
124
125	/**
126	 * Get the media's title (name)
127	 *
128	 * @return string
129	 */
130	public function getTitle() {
131		return $this->title;
132	}
133
134	/**
135	 * Get the filename on the server - for those (very few!) functions which actually
136	 * need the filename, such as mediafirewall.php and the PDF reports.
137	 *
138	 * @param string $which
139	 *
140	 * @return string
141	 */
142	public function getServerFilename($which = 'main') {
143		$MEDIA_DIRECTORY = $this->tree->getPreference('MEDIA_DIRECTORY');
144		$THUMBNAIL_WIDTH = $this->tree->getPreference('THUMBNAIL_WIDTH');
145
146		if ($this->isExternal() || !$this->file) {
147			// External image, or (in the case of corrupt GEDCOM data) no image at all
148			return $this->file;
149		} elseif ($which == 'main') {
150			// Main image
151			return WT_DATA_DIR . $MEDIA_DIRECTORY . $this->file;
152		} else {
153			// Thumbnail
154			$file = WT_DATA_DIR . $MEDIA_DIRECTORY . 'thumbs/' . $this->file;
155			// Does the thumbnail exist?
156			if (file_exists($file)) {
157				return $file;
158			}
159			// Does a user-generated thumbnail exist?
160			$user_thumb = preg_replace('/\.[a-z0-9]{3,5}$/i', '.png', $file);
161			if (file_exists($user_thumb)) {
162				return $user_thumb;
163			}
164			// Does the folder exist for this thumbnail?
165			if (!is_dir(dirname($file)) && !File::mkdir(dirname($file))) {
166				Log::addMediaLog('The folder ' . dirname($file) . ' could not be created for ' . $this->getXref());
167
168				return $file;
169			}
170			// Is there a corresponding main image?
171			$main_file = WT_DATA_DIR . $MEDIA_DIRECTORY . $this->file;
172			if (!file_exists($main_file)) {
173				Log::addMediaLog('The file ' . $main_file . ' does not exist for ' . $this->getXref());
174
175				return $file;
176			}
177			// Try to create a thumbnail automatically
178
179			try {
180				$imgsize = getimagesize($main_file);
181				// Image small enough to be its own thumbnail?
182				if ($imgsize[0] > 0 && $imgsize[0] <= $THUMBNAIL_WIDTH) {
183					try {
184						copy($main_file, $file);
185						Log::addMediaLog('Thumbnail created for ' . $main_file . ' (copy of main image)');
186					} catch (\ErrorException $ex) {
187						Log::addMediaLog('Thumbnail could not be created for ' . $main_file . ' (copy of main image)');
188					}
189				} else {
190					if (FunctionsMedia::hasMemoryForImage($main_file)) {
191						try {
192							switch ($imgsize['mime']) {
193							case 'image/png':
194								$main_image = imagecreatefrompng($main_file);
195								break;
196							case 'image/gif':
197								$main_image = imagecreatefromgif($main_file);
198								break;
199							case 'image/jpeg':
200								$main_image = imagecreatefromjpeg($main_file);
201								break;
202							default:
203								return $file; // Nothing else we can do :-(
204							}
205							if ($main_image) {
206								// How big should the thumbnail be?
207								$width       = $THUMBNAIL_WIDTH;
208								$height      = round($imgsize[1] * ($width / $imgsize[0]));
209								$thumb_image = imagecreatetruecolor($width, $height);
210								// Create a transparent background, instead of the default black one
211								imagesavealpha($thumb_image, true);
212								imagefill($thumb_image, 0, 0, imagecolorallocatealpha($thumb_image, 0, 0, 0, 127));
213								// Shrink the image
214								imagecopyresampled($thumb_image, $main_image, 0, 0, 0, 0, $width, $height, $imgsize[0], $imgsize[1]);
215								switch ($imgsize['mime']) {
216								case 'image/png':
217									imagepng($thumb_image, $file);
218									break;
219								case 'image/gif':
220									imagegif($thumb_image, $file);
221									break;
222								case 'image/jpeg':
223									imagejpeg($thumb_image, $file);
224									break;
225								}
226								imagedestroy($main_image);
227								imagedestroy($thumb_image);
228								Log::addMediaLog('Thumbnail created for ' . $main_file);
229							}
230						} catch (\ErrorException $ex) {
231							Log::addMediaLog('Failed to create thumbnail for ' . $main_file . ' (' . $ex . ')');
232						}
233					} else {
234						Log::addMediaLog('Not enough memory to create thumbnail for ' . $main_file);
235					}
236				}
237			} catch (\ErrorException $ex) {
238				// Not an image, or not a valid image?
239			}
240
241			return $file;
242		}
243	}
244
245	/**
246	 * check if the file exists on this server
247	 *
248	 * @param string $which specify either 'main' or 'thumb'
249	 *
250	 * @return bool
251	 */
252	public function fileExists($which = 'main') {
253		return file_exists($this->getServerFilename($which));
254	}
255
256	/**
257	 * Determine if the file is an external url
258	 *
259	 * @return bool
260	 */
261	public function isExternal() {
262		return strpos($this->file, '://') !== false;
263	}
264
265	/**
266	 * get the media file size in KB
267	 *
268	 * @param string $which specify either 'main' or 'thumb'
269	 *
270	 * @return string
271	 */
272	public function getFilesize($which = 'main') {
273		$size = $this->getFilesizeraw($which);
274		// Round up to the nearest KB.
275		$size = (int) (($size + 1023) / 1024);
276
277		return /* I18N: size of file in KB */ I18N::translate('%s KB', I18N::number($size));
278	}
279
280	/**
281	 * get the media file size, unformatted
282	 *
283	 * @param string $which specify either 'main' or 'thumb'
284	 *
285	 * @return int
286	 */
287	public function getFilesizeraw($which = 'main') {
288		try {
289			return filesize($this->getServerFilename($which));
290		} catch (\ErrorException $ex) {
291			return 0;
292		}
293	}
294
295	/**
296	 * get filemtime for the media file
297	 *
298	 * @param string $which specify either 'main' or 'thumb'
299	 *
300	 * @return int
301	 */
302	public function getFiletime($which = 'main') {
303		try {
304			return filemtime($this->getServerFilename($which));
305		} catch (\ErrorException $ex) {
306			return 0;
307		}
308	}
309
310	/**
311	 * Generate an etag specific to this media item and the current user
312	 *
313	 * @param string $which - specify either 'main' or 'thumb'
314	 *
315	 * @return string
316	 */
317	public function getEtag($which = 'main') {
318		if ($this->isExternal()) {
319			// etag not really defined for external media
320
321			return '';
322		}
323		$etag_string = basename($this->getServerFilename($which)) . $this->getFiletime($which) . $this->tree->getName() . Auth::accessLevel($this->tree) . $this->tree->getPreference('SHOW_NO_WATERMARK');
324		$etag_string = dechex(crc32($etag_string));
325
326		return $etag_string;
327	}
328
329	/**
330	 * Deprecated? This does not need to be a function here.
331	 *
332	 * @return string
333	 */
334	public function getMediaType() {
335		if (preg_match('/\n\d TYPE (.+)/', $this->gedcom, $match)) {
336			return strtolower($match[1]);
337		} else {
338			return '';
339		}
340	}
341
342	/**
343	 * Is this object marked as a highlighted image?
344	 *
345	 * @return string
346	 */
347	public function isPrimary() {
348		if (preg_match('/\n\d _PRIM ([YN])/', $this->getGedcom(), $match)) {
349			return $match[1];
350		} else {
351			return '';
352		}
353	}
354
355	/**
356	 * get image properties
357	 *
358	 * @param string $which     specify either 'main' or 'thumb'
359	 * @param int    $addWidth  amount to add to width
360	 * @param int    $addHeight amount to add to height
361	 *
362	 * @return array
363	 */
364	public function getImageAttributes($which = 'main', $addWidth = 0, $addHeight = 0) {
365		$THUMBNAIL_WIDTH = $this->tree->getPreference('THUMBNAIL_WIDTH');
366
367		$var = $which . 'imagesize';
368		if (!empty($this->$var)) {
369			return $this->$var;
370		}
371		$imgsize = [];
372		if ($this->fileExists($which)) {
373
374			try {
375				$imgsize = getimagesize($this->getServerFilename($which));
376				if (is_array($imgsize) && !empty($imgsize['0'])) {
377					// this is an image
378					$imgsize[0]      = $imgsize[0] + 0;
379					$imgsize[1]      = $imgsize[1] + 0;
380					$imgsize['adjW'] = $imgsize[0] + $addWidth; // adjusted width
381					$imgsize['adjH'] = $imgsize[1] + $addHeight; // adjusted height
382					$imageTypes      = ['', 'GIF', 'JPG', 'PNG', 'SWF', 'PSD', 'BMP', 'TIFF', 'TIFF', 'JPC', 'JP2', 'JPX', 'JB2', 'SWC', 'IFF', 'WBMP', 'XBM'];
383					$imgsize['ext']  = $imageTypes[0 + $imgsize[2]];
384					// this is for display purposes, always show non-adjusted info
385					$imgsize['WxH']   =
386						/* I18N: image dimensions, width × height */
387						I18N::translate('%1$s × %2$s pixels', I18N::number($imgsize['0']), I18N::number($imgsize['1']));
388					$imgsize['imgWH'] = ' width="' . $imgsize['adjW'] . '" height="' . $imgsize['adjH'] . '" ';
389					if (($which == 'thumb') && ($imgsize['0'] > $THUMBNAIL_WIDTH)) {
390						// don’t let large images break the dislay
391						$imgsize['imgWH'] = ' width="' . $THUMBNAIL_WIDTH . '" ';
392					}
393				}
394			} catch (\ErrorException $ex) {
395				// Not an image, or not a valid image?
396				$imgsize = false;
397			}
398		}
399
400		if (!is_array($imgsize) || empty($imgsize['0'])) {
401			// this is not an image, OR the file doesn’t exist OR it is a url
402			$imgsize[0]       = 0;
403			$imgsize[1]       = 0;
404			$imgsize['adjW']  = 0;
405			$imgsize['adjH']  = 0;
406			$imgsize['ext']   = '';
407			$imgsize['mime']  = '';
408			$imgsize['WxH']   = '';
409			$imgsize['imgWH'] = '';
410			if ($this->isExternal()) {
411				// don’t let large external images break the dislay
412				$imgsize['imgWH'] = ' width="' . $THUMBNAIL_WIDTH . '" ';
413			}
414		}
415
416		if (empty($imgsize['mime'])) {
417			// this is not an image, OR the file doesn’t exist OR it is a url
418			// set file type equal to the file extension - can’t use parse_url because this may not be a full url
419			$exp            = explode('?', $this->file);
420			$imgsize['ext'] = strtoupper(pathinfo($exp[0], PATHINFO_EXTENSION));
421			// all mimetypes we wish to serve with the media firewall must be added to this array.
422			$mime = [
423				'DOC' => 'application/msword',
424				'MOV' => 'video/quicktime',
425				'MP3' => 'audio/mpeg',
426				'PDF' => 'application/pdf',
427				'PPT' => 'application/vnd.ms-powerpoint',
428				'RTF' => 'text/rtf',
429				'SID' => 'image/x-mrsid',
430				'TXT' => 'text/plain',
431				'XLS' => 'application/vnd.ms-excel',
432				'WMV' => 'video/x-ms-wmv',
433			];
434			if (empty($mime[$imgsize['ext']])) {
435				// if we don’t know what the mimetype is, use something ambiguous
436				$imgsize['mime'] = 'application/octet-stream';
437				if ($this->fileExists($which)) {
438					// alert the admin if we cannot determine the mime type of an existing file
439					// as the media firewall will be unable to serve this file properly
440					Log::addMediaLog('Media Firewall error: >Unknown Mimetype< for file >' . $this->file . '<');
441				}
442			} else {
443				$imgsize['mime'] = $mime[$imgsize['ext']];
444			}
445		}
446		$this->$var = $imgsize;
447
448		return $this->$var;
449	}
450
451	/**
452	 * Generate a URL directly to the media file
453	 *
454	 * @param string $which
455	 * @param bool   $download
456	 *
457	 * @return string
458	 */
459	public function getHtmlUrlDirect($which = 'main', $download = false) {
460		// “cb” is “cache buster”, so clients will make new request if anything significant about the user or the file changes
461		// The extension is there so that image viewers (e.g. colorbox) can do something sensible
462		$thumbstr    = ($which == 'thumb') ? '&amp;thumb=1' : '';
463		$downloadstr = ($download) ? '&dl=1' : '';
464
465		return
466			'mediafirewall.php?mid=' . $this->getXref() . $thumbstr . $downloadstr .
467			'&amp;ged=' . $this->tree->getNameUrl() .
468			'&amp;cb=' . $this->getEtag($which);
469	}
470
471	/**
472	 * What file extension is used by this file?
473	 *
474	 * @return string
475	 */
476	public function extension() {
477		if (preg_match('/\.([a-zA-Z0-9]+)$/', $this->file, $match)) {
478			return strtolower($match[1]);
479		} else {
480			return '';
481		}
482	}
483
484	/**
485	 * What is the mime-type of this object?
486	 * For simplicity and efficiency, use the extension, rather than the contents.
487	 *
488	 * @return string
489	 */
490	public function mimeType() {
491		// Themes contain icon definitions for some/all of these mime-types
492		switch ($this->extension()) {
493		case 'bmp':
494			return 'image/bmp';
495		case 'doc':
496			return 'application/msword';
497		case 'docx':
498			return 'application/msword';
499		case 'ged':
500			return 'text/x-gedcom';
501		case 'gif':
502			return 'image/gif';
503		case 'htm':
504			return 'text/html';
505		case 'html':
506			return 'text/html';
507		case 'jpeg':
508			return 'image/jpeg';
509		case 'jpg':
510			return 'image/jpeg';
511		case 'mov':
512			return 'video/quicktime';
513		case 'mp3':
514			return 'audio/mpeg';
515		case 'ogv':
516			return 'video/ogg';
517		case 'pdf':
518			return 'application/pdf';
519		case 'png':
520			return 'image/png';
521		case 'rar':
522			return 'application/x-rar-compressed';
523		case 'swf':
524			return 'application/x-shockwave-flash';
525		case 'svg':
526			return 'image/svg';
527		case 'tif':
528			return 'image/tiff';
529		case 'tiff':
530			return 'image/tiff';
531		case 'xls':
532			return 'application/vnd-ms-excel';
533		case 'xlsx':
534			return 'application/vnd-ms-excel';
535		case 'wmv':
536			return 'video/x-ms-wmv';
537		case 'zip':
538			return 'application/zip';
539		default:
540			return 'application/octet-stream';
541		}
542	}
543
544	/**
545	 * Display an image-thumbnail or a media-icon, and add markup for image viewers such as colorbox.
546	 *
547	 * @return string
548	 */
549	public function displayImage() {
550		// Default image for external, missing or corrupt images.
551		$image =
552			'<i' .
553			' dir="' . 'auto' . '"' . // For the tool-tip
554			' class="' . 'icon-mime-' . str_replace('/', '-', $this->mimeType()) . '"' .
555			' title="' . strip_tags($this->getFullName()) . '"' .
556			'></i>';
557
558		// Use a thumbnail image.
559		if (!$this->isExternal()) {
560			try {
561				$imgsize = getimagesize($this->getServerFilename('thumb'));
562				$image   =
563					'<img' .
564					' dir="' . 'auto' . '"' . // For the tool-tip
565					' src="' . $this->getHtmlUrlDirect('thumb') . '"' .
566					' alt="' . strip_tags($this->getFullName()) . '"' .
567					' title="' . strip_tags($this->getFullName()) . '"' .
568					' ' . $imgsize[3] . // height="yyy" width="xxx"
569					'>';
570			} catch (Exception $ex) {
571				// Image file unreadable or Corrupt.
572			}
573		}
574
575		return
576			'<a' .
577			' class="' . 'gallery' . '"' .
578			' href="' . $this->getHtmlUrlDirect('main') . '"' .
579			' type="' . $this->mimeType() . '"' .
580			' data-obje-url="' . $this->getHtmlUrl() . '"' .
581			' data-obje-note="' . Filter::escapeHtml($this->getNote()) . '"' .
582			' data-title="' . Filter::escapeHtml($this->getFullName()) . '"' .
583			'>' . $image . '</a>';
584	}
585
586	/**
587	 * If this object has no name, what do we call it?
588	 *
589	 * @return string
590	 */
591	public function getFallBackName() {
592		if ($this->canShow()) {
593			return basename($this->file);
594		} else {
595			return $this->getXref();
596		}
597	}
598
599	/**
600	 * Extract names from the GEDCOM record.
601	 */
602	public function extractNames() {
603		// Earlier gedcom versions had level 1 titles
604		// Later gedcom versions had level 2 titles
605		$this->extractNamesFromFacts(2, 'TITL', $this->getFacts('FILE'));
606		$this->extractNamesFromFacts(1, 'TITL', $this->getFacts('TITL'));
607	}
608
609	/**
610	 * This function should be redefined in derived classes to show any major
611	 * identifying characteristics of this record.
612	 *
613	 * @return string
614	 */
615	public function formatListDetails() {
616		ob_start();
617		FunctionsPrintFacts::printMediaLinks('1 OBJE @' . $this->getXref() . '@', 1);
618
619		return ob_get_clean();
620	}
621}
622