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