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