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