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