-
Notifications
You must be signed in to change notification settings - Fork 6
/
FancyImagebarModule.php
679 lines (576 loc) · 23 KB
/
FancyImagebarModule.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
<?php
declare(strict_types=1);
namespace JustCarmen\Webtrees\Module\FancyImagebar;
use Exception;
use Throwable;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\View;
use Fisharebest\Webtrees\Media;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Webtrees;
use Illuminate\Support\Collection;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\GedcomRecord;
use Fisharebest\Webtrees\FlashMessages;
use Psr\Http\Message\ResponseInterface;
use Fisharebest\Localization\Translation;
use Psr\Http\Message\ServerRequestInterface;
use Fisharebest\Webtrees\Services\TreeService;
use Illuminate\Database\Capsule\Manager as DB;
use Fisharebest\Webtrees\Module\AbstractModule;
use Fisharebest\Webtrees\Module\ModuleConfigTrait;
use Fisharebest\Webtrees\Module\ModuleCustomTrait;
use Fisharebest\Webtrees\Module\ModuleGlobalTrait;
use Fisharebest\Webtrees\Services\MediaFileService;
use Fisharebest\Webtrees\Module\ModuleConfigInterface;
use Fisharebest\Webtrees\Module\ModuleCustomInterface;
use Fisharebest\Webtrees\Module\ModuleGlobalInterface;
use Fisharebest\Webtrees\Services\LinkedRecordService;
use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
class FancyImagebarModule extends AbstractModule implements ModuleCustomInterface, ModuleConfigInterface, ModuleGlobalInterface
{
use ModuleCustomTrait;
use ModuleConfigTrait;
use ModuleGlobalTrait;
// Module constants
public const CUSTOM_AUTHOR = 'JustCarmen';
public const CUSTOM_VERSION = '2.3.1';
public const GITHUB_REPO = 'webtrees-fancy-imagebar';
public const AUTHOR_WEBSITE = 'https://justcarmen.nl';
public const CUSTOM_SUPPORT_URL = self::AUTHOR_WEBSITE . '/modules-webtrees-2/fancy-imagebar/';
// Image cache dir
private const CACHE_DIR = Webtrees::DATA_DIR . 'fib-cache/';
/** @var MediaFileService */
private $media_file_service;
/** @var TreeService */
private $tree_service;
/** @var LinkedRecordService */
private $linked_record_service;
/**
* FancyImagebar constructor.
*
* @param MediaFileService $media_file_service
* @param TreeService $tree_service
*/
public function __construct(MediaFileService $media_file_service, TreeService $tree_service, LinkedRecordService $linked_record_service)
{
$this->media_file_service = $media_file_service;
$this->tree_service = $tree_service;
$this->linked_record_service = $linked_record_service;
}
/**
* How should this module be identified in the control panel, etc.?
*
* @return string
*/
public function title(): string
{
return I18N::translate('Fancy Imagebar');
}
/**
* A sentence describing what this module does.
*
* @return string
*/
public function description(): string
{
return I18N::translate('An imagebar with small images between header and content.');
}
/**
* {@inheritDoc}
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleAuthorName()
*/
public function customModuleAuthorName(): string
{
return self::CUSTOM_AUTHOR;
}
/**
* {@inheritDoc}
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
*/
public function customModuleVersion(): string
{
return self::CUSTOM_VERSION;
}
/**
* A URL that will provide the latest stable version of this module.
*
* @return string
*/
public function customModuleLatestVersionUrl(): string
{
return 'https://raw.githubusercontent.com/' . self::CUSTOM_AUTHOR . '/' . self::GITHUB_REPO . '/main/latest-version.txt';
}
/**
* {@inheritDoc}
* @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleSupportUrl()
*/
public function customModuleSupportUrl(): string
{
return self::CUSTOM_SUPPORT_URL;
}
/**
* Bootstrap. This function is called on *enabled* modules.
* It is a good place to register routes and views.
*
* @return void
*/
public function boot(): void
{
// Register a namespace for our views.
View::registerNamespace($this->name(), $this->resourcesFolder() . 'views/');
// Add the javascript used by this module in a separate view
View($this->name() . '::script');
}
/**
* Where does this module store its resources
*
* @return string
*/
public function resourcesFolder(): string
{
return __DIR__ . '/resources/';
}
/**
* @param ServerRequestInterface $request
*
* @return ResponseInterface
*/
public function getAdminAction(ServerRequestInterface $request): ResponseInterface
{
$this->layout = 'layouts/administration';
$tree_id = $this->getPreference('last-tree-id', '');
try {
$tree = $this->tree_service->find((int)$tree_id);
} catch (Exception $ex) {
// the last tree saved doesn't exist anymore. Use the first tree instead.
$tree = $this->tree_service->all()->first();
$tree_id = $tree->id();
// remove settings from non existing tree from the database
DB::table('module_setting')
->where('module_name', '=', $this->name())
->where('setting_name', 'LIKE', '' . $this->getPreference('last-tree-id') . '-%' )
->delete();
// reset the last tree id
$this->setPreference('last-tree-id', '');
}
$data_filesystem = Registry::filesystem()->data();
$media_folders = $this->media_file_service->allMediaFolders($data_filesystem);
$media_types = Registry::elementFactory()->make('OBJE:FILE:FORM:TYPE')->values();
$media_folder = $this->getPreference($tree_id . '-media-folder');
$media_type = $this->getPreference($tree_id . '-media-type');
$subfolders = $this->getPreference($tree_id . '-subfolders');
$xrefs = $this->getMediaXrefs($tree, str_replace($tree->getPreference('MEDIA_DIRECTORY', 'media/'), "", $media_folder), $subfolders, $media_type);
return $this->viewResponse($this->name() . '::settings', [
'all_trees' => $this->tree_service->all(),
'canvas_height' => $this->getPreference($tree_id . '-canvas-height', '80'),
'display_all' => $this->getPreference($tree_id . '-display-all'),
'homepage_only' => $this->getPreference($tree_id . '-homepage-only'),
'media_folder' => $media_folder,
'media_folders' => $media_folders,
'media_list' => $this->getMediaList($tree),
'media_type' => $media_type,
'media_types' => $media_types,
'square_thumbs' => $this->getPreference($tree_id . '-square-thumbs'),
'subfolders' => $subfolders,
'title' => $this->title(),
'tree_id' => $tree_id,
'xrefs' => $xrefs
]);
}
/**
* Save the user preference.
*
* @param ServerRequestInterface $request
*
* @return ResponseInterface
*/
public function postAdminAction(ServerRequestInterface $request): ResponseInterface
{
$params = (array) $request->getParsedBody();
// store the preferences in the database when editing the form
$tree_id = $params['tree-id'];
$this->setPreference('last-tree-id', $tree_id);
if ($params['switch'] === '1') {
$this->setPreference($tree_id . '-media-folder', $params['media-folder']);
$this->setPreference($tree_id . '-subfolders', $params['subfolders'] ?? '0');
$this->setPreference($tree_id . '-media-type', $params['media-type']);
$this->setPreference($tree_id . '-display-all', $params['display-all']);
}
if ($params['save'] === '1') {
$this->setPreference($tree_id . '-canvas-height', $params['canvas-height']);
$this->setPreference($tree_id . '-square-thumbs', $params['square-thumbs']);
$this->setPreference($tree_id . '-homepage-only', $params['homepage-only']);
$this->setPreference($tree_id . '-media-list', $params['media-list']);
// remove previously cached images. The cache is recreated the first time the imagebar is loaded after the settings are changed
$tree = $this->tree_service->find((int)$tree_id);
$this->emptyCache($tree);
$message = I18N::translate('The preferences for the module “%s” have been updated.', $this->title());
FlashMessages::addMessage($message, 'success');
}
return redirect($this->getConfigLink());
}
/**
* Raw content, to be added at the end of the <body> element.
* Typically, this will be <script> elements.
*
* Script to put the fancy imagebar in place once it is created
*
* @return string
*/
public function bodyContent(): string
{
$body = $this->fancyImagebar();
$body .= '<script>';
$body .= '$(".wt-main-wrapper").prepend($(".jc-fancy-imagebar"))';
$body .= '</script>';
return $body;
}
/**
* Raw content, to be added at the end of the <head> element.
* Typically, this will be <link> and <meta> elements.
*
* @return string
*/
public function headContent(): string
{
$request = app(ServerRequestInterface::class);
$tree = $request->getAttribute('tree');
if ($tree === null) {
return '';
}
$canvas_height = $this->getPreference($tree->id() . '-canvas-height', '80');
$canvas_height_md = 0.85 * $canvas_height;
$canvas_height_sm = 0.75 * $canvas_height;
$url = $this->assetUrl('css/style.css');
return '
<style>
.jc-fancy-imagebar img {
height: ' . $canvas_height . 'px;
}
@media screen and (max-width: 992px) {
.jc-fancy-imagebar img {
height: ' . $canvas_height_md . 'px;
}
}
@media screen and (max-width: 768px) {
.jc-fancy-imagebar img {
height: ' . $canvas_height_sm . 'px;
}
}
</style>
<link rel="stylesheet" href="' . e($url) . '">';
}
/**
* Additional/updated translations.
*
* @param string $language
*
* @return string[]
*/
public function customTranslations(string $language): array
{
$lang_dir = $this->resourcesFolder() . 'lang/';
$file = $lang_dir . $language . '.mo';
if (file_exists($file)) {
return (new Translation($file))->asArray();
} else {
return [];
}
}
/**
* Generate the html for the Fancy imagebar
*
* @return string
*/
public function fancyImagebar(): string
{
$request = app(ServerRequestInterface::class);
$tree = $request->getAttribute('tree');
if ($tree === null) {
return '';
}
$route = $request->getAttribute('route');
$homepage_only = $this->getPreference($tree->id() . '-homepage-only', '0');
if ($homepage_only === '1' && $route->name !== TreePage::class) {
return '';
}
$data_filesystem = Registry::filesystem()->data();
$data_folder = Registry::filesystem()->dataName();
$wt_media_folder = $tree->getPreference('MEDIA_DIRECTORY', 'media/');
if (!file_exists(self::CACHE_DIR)) {
mkdir(self::CACHE_DIR);
}
// Set default values in case the settings are not stored in the database yet
$subfolders = $this->getPreference($tree->id() . '-subfolders', '1');
$media_type = $this->getPreference($tree->id() . '-media-type');
$square_thumbs = $this->getPreference($tree->id() . '-square-thumbs', '0');
$canvas_height = (int)$this->getPreference($tree->id() . '-canvas-height', '80');
// strip out the default media directory from the folder path. It is not stored in the database
$folder = str_replace($wt_media_folder, "", $this->getPreference($tree->id() . '-media-folder'));
// include or exclude subfolders
$subfolders = $subfolders === '1' ? 'include' : 'exclude';
// Pull the user defined medialist from the database module settings
$media_list = $this->getMediaList($tree);
// Get the collection of xrefs to work with
if ($media_list->isEmpty()) {
$xrefs = $this->getMediaXrefs($tree, $folder, $subfolders, $media_type);
} else {
$xrefs = $media_list->map(function ($xref) {
return substr($xref, 0, (int)strpos($xref, "["));
})->unique();
}
// randomize the collection
$xrefs = $xrefs->shuffle();
// We need to set a limit due to performance. We use a cookie based on the user's screen width to achieve that.
// The default value (3840) is equal to a 4K screen.
$canvas_width = (int)isset($_COOKIE["FIB_WIDTH"]) ? $_COOKIE["FIB_WIDTH"] : "3840";
// add support for small screens (to be in sync with smaller height - see function HeadContent())
switch ($canvas_width) {
case $canvas_width < 768:
$canvas_width = $canvas_width / 0.75;
break;
case $canvas_width < 992:
$canvas_width = $canvas_width / 0.85;
break;
}
// Get the thumbnail resources
$resources = array();
$calculated_width = 0;
foreach ($xrefs as $xref) {
$media = Registry::mediaFactory()->make($xref, $tree);
if ($media && $media->canShow()) {
$i = 0; // counter for multiple media files in a media object
foreach ($media->mediaFiles() as $media_file) {
$i++;
$media_id = $xref . '[' . $i. ']';
$process_image = $media->mediaFiles()->count() > 1 ? $media_list->contains($media_id) : true;
if ($process_image && $media_file->fileExists($data_filesystem)) {
$file = $data_folder . $wt_media_folder . $media_file->filename();
$cache_file = $this->cacheFile($tree, $media_id, $file);
if (is_file($cache_file)) {
$fancy_thumb = $this->loadImage($cache_file);
} else {
$fancy_thumb = $this->fancyThumb($file, $canvas_height, $square_thumbs);
if (!is_null($fancy_thumb)) {
imagejpeg($fancy_thumb, $cache_file);
}
}
if (!is_null($fancy_thumb)) {
$calculated_width = $calculated_width + imagesx($fancy_thumb);
$resources[] = [
'image' => $fancy_thumb,
'linked' => $this->getLinkedObject($media)
];
}
}
}
}
// Stop when we have enough thumbnails to fill the entire width of the screen with the Fancy Imagebar.
if ($calculated_width >= $canvas_width) {
break;
}
}
if (count($resources) === 0) {
return '';
}
// prevent media files from one media object always stick together
shuffle($resources);
// Repeat items if neccessary to fill up the Fancy Imagebar
if ($calculated_width < $canvas_width) {
$average_thumb_width = (float)$calculated_width / count($resources);
$num_thumbs = (int)ceil($canvas_width / $average_thumb_width);
// see: https://stackoverflow.com/questions/2963777/how-to-repeat-an-array-in-php
$resources = array_merge(...array_fill(0, (int)ceil($num_thumbs/count($resources)), $resources));
}
return $this->createFancyImagebar($resources, $canvas_width, $canvas_height);
}
private function getMediaList(Tree $tree): Collection
{
return collect(explode(',', $this->getPreference($tree->id() . '-media-list')))->filter(function (string $value) {
return $value <> "";
});
}
/**
* @param Tree $tree
* @param string $folder
* @param string $subfolders
* @param string $type
*
* @return Collection
*/
private function getMediaXrefs(Tree $tree, string $folder, string $subfolders, string $type): Collection
{
$query = DB::table('media_file')
->where('m_file', '=', $tree->id())
->where('multimedia_file_refn', 'LIKE', $folder . '%')
->whereIn('multimedia_format', ['jpg', 'jpeg', 'png']);
if ($subfolders === 'exclude') {
$query->where('multimedia_file_refn', 'NOT LIKE', $folder . '%/%');
}
if ($type) {
$query->where('source_media_type', '=', $type);
}
return $query->pluck('m_id')->unique();
}
/**
* Create the Fancy Imagebar + html output
*
* @param array $source_images
* @param string $canvas_width
* @param string $canvas_height
*
* @return string
*/
private function createFancyImagebar($source_images, $canvas_width, $canvas_height): string
{
// create the FancyImagebar canvas to put the thumbs on
$fancy_imagebar_canvas = imagecreatetruecolor((int) $canvas_width, (int) $canvas_height);
$fancy_map = [];
$pos = 0;
foreach ($source_images as $source) {
$image = $source['image'];
$linked = $source['linked'];
$x1 = $pos;
$x2 = $x1 + imagesx($image);
$pos = $pos + imagesx($image);
// copy the images (thumbnails) to the canvas
// imagecopy (resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h)
imagecopy($fancy_imagebar_canvas, $image, $x1, 0, 0, 0, imagesx($image), (int) $canvas_height);
// prepare the map
if ($linked !== null) {
$lifespan = $linked instanceof Individual ? ' (' . $linked->lifespan() . ')' : '';
$fancy_map[] = [
'coords' => [
'x1' => $x1,
'y1' => '0',
'x2' => $x2,
'y2' => $canvas_height
],
'title' => strip_tags($linked->fullName() . $lifespan),
'url' => e($linked->url())
];
}
}
// Output
ob_start();
imagejpeg($fancy_imagebar_canvas);
$fancy_imagebar = ob_get_clean();
return view($this->name() . '::fancy-imagebar', [
'fancy_imagebar' => $fancy_imagebar,
'fancy_map' => $fancy_map,
'canvas_height' => $canvas_height
]);
}
/**
* Create a thumbnail
*
* @param string $file
* @param string $canvas_height
* @param string $canvas_width
*
* https://www.jveweb.net/en/archives/2010/09/how-to-create-cropped-and-scaled-thumbnails-in-php.html
*/
private function fancyThumb($file, $canvas_height, $square_thumbs)
{
// error handling to prevent bad images from loading
try {
$source_image = $this->loadImage($file);
list($source_width, $source_height) = getimagesize($file);
$source_ratio = $source_width / $source_height;
} catch (Throwable $exception) {
return null;
}
// Cases have been reported where a false source image produces a fatal error at
// the imagecopyresampled function: imagecopyresampled() expects parameter 2 to be resource, bool given
// This source image got through the try/catch section
if ($source_image === false) {
return null;
}
$source_x = 0;
$source_y = 0;
// if square thumbnails are wanted then resize and crop the original image
if ($square_thumbs) {
$thumb_width = $thumb_height = $canvas_height;
if ($source_ratio < 1) {
$source_y = ceil(($source_height - $source_width) / 2);
$source_height = $source_width;
}
if ($source_ratio > 1) {
$source_x = ceil(($source_width - $source_height) / 2);
$source_width = $source_height;
}
} else {
$thumb_width = $canvas_height * $source_ratio;
$thumb_height = $canvas_height;
}
$thumb = ImageCreateTrueColor((int)$thumb_width, (int)$thumb_height);
imagecopyresampled($thumb, $source_image, 0, 0, (int)$source_x, (int)$source_y, (int)$thumb_width, (int)$thumb_height, (int)$source_width, (int)$source_height);
imagedestroy($source_image);
return $thumb; // resource
}
/**
* load image from file
* return false if image could not be loaded
*
* @param string $file
*/
private function loadImage($file)
{
$size = getimagesize($file);
switch ($size["mime"]) {
case "image/jpeg":
$image = imagecreatefromjpeg($file);
break;
case "image/png":
$image = imagecreatefrompng($file);
break;
default:
$image = false;
break;
}
return $image;
}
/**
* Get the filename of the cached image
*
* @param Tree $tree
* @param string $media_id
* @param string $file
*
* @return string
*/
private function cacheFile(Tree $tree, string $media_id, string $file) {
return self::CACHE_DIR . $tree->id() . '-' . $media_id . '-' . filemtime($file) . '.jpg';
}
/**
* remove all old cached files for this tree after changing settings in control panel
*/
protected function emptyCache(Tree $tree): void {
foreach (glob(self::CACHE_DIR . '*') as $cache_file) {
if (is_file($cache_file)) {
$tmp = explode('-', basename($cache_file));
$tree_id = intval($tmp[0]);
if ($tree_id === $tree->id()) {
unlink($cache_file);
}
}
}
}
/**
* Which objects are linked to this file?
* return the first linked object (indi, fam or source)
*
* @param Media $media
* @return GedcomRecord|null
*/
private function getLinkedObject(Media $media): ?GedcomRecord
{
// return the first link found
return
$this->linked_record_service->linkedIndividuals($media)->first() ??
$this->linked_record_service->linkedFamilies($media)->first() ??
$this->linked_record_service->linkedSources($media)->first();
}
};