/
Art.php
1611 lines (1437 loc) · 56 KB
/
Art.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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* vim:set softtabstop=4 shiftwidth=4 expandtab:
*
* LICENSE: GNU Affero General Public License, version 3 (AGPL-3.0-or-later)
* Copyright 2001 - 2022 Ampache.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
declare(strict_types=0);
namespace Ampache\Repository\Model;
use Ampache\Config\AmpConfig;
use Ampache\Module\Art\Collector\MetaTagCollectorModule;
use Ampache\Module\System\Dba;
use Ampache\Module\System\Session;
use Ampache\Module\Util\ObjectTypeToClassNameMapper;
use Ampache\Module\Util\Ui;
use Ampache\Module\Api\Ajax;
use Ampache\Module\Util\UtilityFactoryInterface;
use Ampache\Module\Util\InterfaceImplementationChecker;
use Ampache\Module\System\Core;
use Ampache\Repository\SongRepositoryInterface;
use Exception;
use getID3;
use PDOStatement;
use Requests;
use RuntimeException;
/**
* This class handles the images / artwork in ampache
* This was initially in the album class, but was pulled out
* to be more general and potentially apply to albums, artists, movies etc
*/
class Art extends database_object
{
protected const DB_TABLENAME = 'art';
public const VALID_TYPES = array('bmp', 'gif', 'jp2', 'jpeg', 'jpg', 'png', 'webp');
/**
* @var integer $id
*/
public $id;
/**
* @var string $type
*/
public $type;
/**
* @var integer $uid
*/
public $uid; // UID of the object not ID because it's not the ART.ID
/**
* @var string $raw
*/
public $raw; // Raw art data
/**
* @var string $raw_mime
*/
public $raw_mime;
/**
* @var string $kind
*/
public $kind;
/**
* @var string $thumb
*/
public $thumb;
/**
* @var string $thumb_mime
*/
public $thumb_mime;
/**
* Constructor
* Art constructor, takes the UID of the object and the
* object type.
* @param integer $uid
* @param string $type
* @param string $kind
*/
public function __construct($uid, $type = 'album', $kind = 'default')
{
if (Art::is_valid_type($type)) {
$this->type = $type;
$this->uid = (int)($uid);
$this->kind = $kind;
}
} // constructor
public function getId(): int
{
return (int)$this->id;
}
/**
* @param string $type
* @return boolean
*/
public static function is_valid_type($type)
{
if (!$type) {
return false;
}
return (InterfaceImplementationChecker::is_library_item($type) || $type == 'user');
}
/**
* build_cache
* This attempts to reduce # of queries by asking for everything in the
* browse all at once and storing it in the cache, this can help if the
* db connection is the slow point
* @param integer[] $object_ids
* @param string $type
* @return boolean
*/
public static function build_cache($object_ids, $type = null)
{
if (empty($object_ids)) {
return false;
}
$idlist = '(' . implode(',', $object_ids) . ')';
$sql = "SELECT `object_type`, `object_id`, `mime`, `size` FROM `image` WHERE `object_id` IN $idlist";
if ($type !== null) {
$sql .= " AND `object_type` = '$type'";
}
$db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
parent::add_to_cache('art', $row['object_type'] . $row['object_id'] . $row['size'], $row);
}
return true;
} // build_cache
/**
* extension
* This returns the file extension for the currently loaded art
* @param string $mime
* @return string
*/
public static function extension($mime)
{
if (empty($mime)) {
return '';
}
$data = explode('/', $mime);
$extension = $data['1'] ?? '';
if ($extension == 'jpeg') {
$extension = 'jpg';
}
return (string)$extension;
} // extension
/**
* test_image
* Runs some sanity checks on the putative image
* @param string $source
* @return boolean
* @throws RuntimeException
*/
public static function test_image($source)
{
if (strlen((string) $source) < 10) {
debug_event(self::class, 'Invalid image passed', 1);
return false;
}
$max_upload_size = (int)AmpConfig::get('max_upload_size', 0);
// Check image size doesn't exceed the limit
if ($max_upload_size > 0 && strlen((string) $source) > $max_upload_size) {
debug_event(self::class, 'Image size (' . strlen((string) $source) . ') exceed the limit (' . $max_upload_size . ').', 1);
return false;
}
// Check to make sure PHP:GD exists. Don't test things you can't change
if (!function_exists('imagecreatefromstring')) {
return true;
}
$test = false;
$image = false;
if (is_string($source)) {
$test = true;
$image = imagecreatefromstring($source);
if ($image == false || imagesx($image) < 5 || imagesy($image) < 5) {
debug_event(self::class, 'Image failed PHP-GD test', 1);
$test = false;
}
}
if ($test && $image != false) {
if (imagedestroy($image) === false) {
throw new RuntimeException('The image handle from source: ' . $source . ' could not be destroyed');
}
}
return $test;
} // test_image
/**
* get
* This returns the art for our current object, this can
* look in the database and will return the thumb if it
* exists, if it doesn't depending on settings it will try
* to create it.
* @param boolean $raw
* @param boolean $fallback
* @return string
*/
public function get($raw = false, $fallback = false)
{
// Get the data either way (allow forcing to fallback image)
if (!$this->has_db_info($fallback)) {
return '';
}
if ($raw || !$this->thumb) {
return $this->raw;
} else {
return $this->thumb;
}
} // get
/**
* has_db_info
* This pulls the information out from the database, depending
* on if we want to resize and if there is not a thumbnail go
* ahead and try to resize
* @return boolean
*/
public function has_db_info($fallback = false)
{
$sql = "SELECT `id`, `image`, `mime`, `size` FROM `image` WHERE `object_type` = ? AND `object_id` = ? AND `kind` = ?";
$db_results = Dba::read($sql, array($this->type, $this->uid, $this->kind));
$default_art = false;
while ($results = Dba::fetch_assoc($db_results)) {
if ($results['size'] == 'original') {
if (AmpConfig::get('album_art_store_disk')) {
$this->raw = self::read_from_dir($results['size'], $this->type, $this->uid, $this->kind, $results['mime']);
} else {
$this->raw = $results['image'];
}
$this->raw_mime = $results['mime'];
} elseif (AmpConfig::get('resize_images')) {
if (AmpConfig::get('album_art_store_disk')) {
$this->thumb = self::read_from_dir($results['size'], $this->type, $this->uid, $this->kind, $results['mime']);
} elseif ($results['size'] == '275x275') {
$this->thumb = $results['image'];
}
$this->raw_mime = $results['mime'];
}
$this->id = (int)$results['id'];
}
// return a default image if fallback is requested
if (!$this->raw && $fallback) {
$this->raw = self::read_from_images();
$this->raw_mime = 'image/png';
$default_art = true;
}
// If we get nothing return false
if (!$this->raw) {
return false;
}
// If there is no thumb and we want thumbs
if (!$this->thumb && AmpConfig::get('resize_images')) {
$size = array('width' => 275, 'height' => 275);
$data = $this->generate_thumb($this->raw, $size, $this->raw_mime);
// If it works save it!
if (!empty($data)) {
if (!$default_art) {
$this->save_thumb($data['thumb'], $data['thumb_mime'], $size);
}
$this->thumb = $data['thumb'];
$this->thumb_mime = $data['thumb_mime'];
} else {
debug_event(self::class, 'Art id {' . $this->id . '} Unable to generate thumbnail for ' . $this->type . ': ' . $this->uid, 1);
}
} // if no thumb, but art and we want to resize
return true;
} // has_db_info
/**
* This check if an object has an associated image in db.
* @param integer $object_id
* @param string $object_type
* @param string $kind
* @return boolean
*/
public static function has_db($object_id, $object_type, $kind = 'default')
{
$sql = "SELECT COUNT(`id`) AS `nb_img` FROM `image` WHERE `object_type` = ? AND `object_id` = ? AND `kind` = ?";
$db_results = Dba::read($sql, array($object_type, $object_id, $kind));
$nb_img = 0;
if ($results = Dba::fetch_assoc($db_results)) {
$nb_img = $results['nb_img'];
}
return ($nb_img > 0);
}
/**
* This insert art from url.
* @param string $url
*/
public function insert_url($url)
{
debug_event(self::class, 'Insert art from url ' . $url, 4);
$image = self::get_from_source(array('url' => $url), $this->type);
$rurl = pathinfo($url);
$mime = "image/" . $rurl['extension'];
$this->insert($image, $mime);
}
/**
* insert
* This takes the string representation of an image and inserts it into
* the database. You must also pass the mime type.
* @param string $source
* @param string $mime
* @return boolean
*/
public function insert($source, $mime = '')
{
// Disabled in demo mode cause people suck and upload porn
if (AmpConfig::get('demo_mode')) {
return false;
}
// Check to make sure we like this image
if (!self::test_image($source)) {
debug_event(self::class, 'Not inserting image for ' . $this->type . ' ' . $this->uid . ', invalid data passed', 1);
return false;
}
$dimensions = Core::image_dimensions($source);
$width = (int)($dimensions['width']);
$height = (int)($dimensions['height']);
$sizetext = 'original';
if (!self::check_dimensions($dimensions)) {
return false;
}
// Default to image/jpeg if they don't pass anything
$mime = $mime ?? 'image/jpeg';
// Blow it away!
$this->reset();
$current_picturetypeid = ($this->type == 'album') ? 3 : 8;
if (AmpConfig::get('write_tags', false)) {
$class_name = ObjectTypeToClassNameMapper::map($this->type);
$object = new $class_name($this->uid);
$songs = array();
debug_event(__CLASS__, 'Inserting ' . $this->type . ' image' . $object->name . ' for song files.', 5);
if ($this->type === 'album') {
/** Use special treatment for albums */
$songs = $this->getSongRepository()->getByAlbum($object->id);
} elseif ($this->type === 'artist') {
/** Use special treatment for artists */
$songs = $this->getSongRepository()->getByArtist($object->id);
}
global $dic;
$utilityFactory = $dic->get(UtilityFactoryInterface::class);
foreach ($songs as $song_id) {
$song = new Song($song_id);
$song->format();
$description = ($this->type == 'artist') ? $song->f_artist_full : $object->full_name;
$vainfo = $utilityFactory->createVaInfo(
$song->file
);
$ndata = array();
$data = $vainfo->read_id3();
$fileformat = $data['fileformat'];
if ($fileformat == 'flac' || $fileformat == 'ogg') {
$apics = $data['flac']['PICTURE'];
} else {
$apics = $data['id3v2']['APIC'];
}
/* is the file flac or mp3? */
$apic_typeid = ($fileformat == 'flac' || $fileformat == 'ogg') ? 'typeid' : 'picturetypeid';
$apic_mimetype = ($fileformat == 'flac' || $fileformat == 'ogg') ? 'image_mime' : 'mime';
$new_pic = array(
'data' => $source,
'mime' => $mime,
'picturetypeid' => $current_picturetypeid,
'description' => $description
);
if (is_null($apics)) {
$ndata['attached_picture'][] = $new_pic;
} else {
switch (count($apics)) {
case 1:
$idx = $this->check_for_duplicate($apics, $ndata, $new_pic, $apic_typeid);
if (is_null($idx)) {
$ndata['attached_picture'][] = $new_pic;
$ndata['attached_picture'][] = array(
'data' => $apics[0]['data'],
'description' => $apics[0]['description'],
'mime' => $apics[0]['mime'],
'picturetypeid' => $apics[0]['picturetypeid']
);
}
break;
case 2:
$idx = $this->check_for_duplicate($apics, $ndata, $new_pic, $apic_typeid);
/* If $idx is null, it means both images are of opposite types
* of the new image. Either image could be replaced to have
* one cover and one artist image.
*/
if (is_null($idx)) {
$ndata['attached_picture'][0] = $new_pic;
} else {
$apicsId = ($idx == 0) ? 1 : 0;
$ndata['attached_picture'][$apicsId] = array(
'data' => $apics[$apicsId]['data'],
'mime' => $apics[$apicsId][$apic_mimetype],
'picturetypeid' => $apics[$apicsId][$apic_typeid],
'description' => $apics[$apicsId]['description']
);
}
break;
}
}
unset($apics);
$tags = ($fileformat == 'flac' || $fileformat == 'ogg') ? 'vorbiscomment' : 'id3v2';
$ndata = array_merge($ndata, $vainfo->prepare_metadata_for_writing($data['tags'][$tags]));
$vainfo->write_id3($ndata);
} // foreach song
} // write_id3
if (AmpConfig::get('album_art_store_disk')) {
self::write_to_dir($source, $sizetext, $this->type, $this->uid, $this->kind, $mime);
$source = null;
}
// Insert it!
$sql = "INSERT INTO `image` (`image`, `mime`, `size`, `width`, `height`, `object_type`, `object_id`, `kind`) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
Dba::write($sql, array($source, $mime, $sizetext, $width, $height, $this->type, $this->uid, $this->kind));
return true;
} // insert
/**
* check_for_duplicate
* @param array $apics
* @param array $ndata
* @param array $new_pic
* @param string $apic_typeid
* @return int|null
*/
private function check_for_duplicate($apics, &$ndata, $new_pic, $apic_typeid)
{
$idx = null;
$cnt = count($apics);
for ($i=0; $i < $cnt; $i++) {
if ($new_pic['picturetypeid'] == $apics[$i][$apic_typeid]) {
$ndata['attached_picture'][$i]['description'] = $new_pic['description'];
$ndata['attached_picture'][$i]['data'] = $new_pic['data'];
$ndata['attached_picture'][$i]['mime'] = $new_pic['mime'];
$ndata['attached_picture'][$i]['picturetypeid'] = $new_pic['picturetypeid'];
$idx = $i;
break;
}
}
return $idx;
}
/**
* Prepares images to be written to file tag.
* @param array $pics
* @return array
*/
public static function prepare_pics($pics)
{
$ndata = array();
$i = 0;
foreach ($pics as $pic) {
$ndata['attached_picture'][$i]['description'] = $pic['description'];
$ndata['attached_picture'][$i]['data'] = $pic['data'];
$ndata['attached_picture'][$i]['picturetypeid'] = $pic['picturetypeid'];
$ndata['attached_picture'][$i]['mime'] = $pic['mime'];
$i++;
}
return $ndata;
}
/**
* check_dimensions
* @param array $dimensions
* @return boolean
*/
public static function check_dimensions($dimensions)
{
$width = (int)($dimensions['width']);
$height = (int)($dimensions['height']);
if ($width > 0 && $height > 0) {
$minw = AmpConfig::get('album_art_min_width', 0);
$maxw = AmpConfig::get('album_art_max_width', 0);
$minh = AmpConfig::get('album_art_min_height', 0);
$maxh = AmpConfig::get('album_art_max_height', 0);
// minimum width is set and current width is too low
if ($minw > 0 && $width < $minw) {
debug_event(self::class, "Image width not in range (min=$minw, max=$maxw, current=$width).", 1);
return false;
}
// max width is set and current width is too high
if ($maxw > 0 && $width > $maxw) {
debug_event(self::class, "Image width not in range (min=$minw, max=$maxw, current=$width).", 1);
return false;
}
if ($minh > 0 && $height < $minh) {
debug_event(self::class, "Image height not in range (min=$minh, max=$maxh, current=$height).", 1);
return false;
}
if ($maxh > 0 && $height > $maxh) {
debug_event(self::class, "Image height not in range (min=$minh, max=$maxh, current=$height).", 1);
return false;
}
}
return true;
}
/**
* clear_image
* Clear the image column (if you have the image on disk)
*/
public static function clear_image($image_id)
{
$sql = "UPDATE `image` SET `image` = NULL WHERE `id` = ?";
Dba::write($sql, array($image_id));
} // clear_image
/**
* get_dir_on_disk
* @param string $type
* @param string $uid
* @param string $kind
* @param boolean $autocreate
* @return false|string
*/
public static function get_dir_on_disk($type, $uid, $kind = '', $autocreate = false)
{
$path = AmpConfig::get('local_metadata_dir');
if (!$path) {
debug_event(self::class, 'local_metadata_dir setting is required to store art on disk.', 1);
return false;
}
// Correctly detect the slash we need to use here
if (strpos($path, '/') !== false) {
$slash_type = '/';
} else {
$slash_type = '\\';
}
$path .= $slash_type . $type;
if ($autocreate && !Core::is_readable($path)) {
mkdir($path);
}
$path .= $slash_type . $uid;
if ($autocreate && !Core::is_readable($path)) {
mkdir($path);
}
if (!empty($kind)) {
$path .= $slash_type . $kind;
if ($autocreate && !Core::is_readable($path)) {
mkdir($path);
}
}
$path .= $slash_type;
return $path;
}
/**
* write_to_dir
* @param string $source
* @param string $sizetext
* @param string $type
* @param integer $uid
* @param $kind
* @param $mime
* @return boolean
*/
private static function write_to_dir($source, $sizetext, $type, $uid, $kind, $mime)
{
$path = self::get_dir_on_disk($type, $uid, $kind, true);
if ($path === false) {
return false;
}
$path .= "art-" . $sizetext . "." . self::extension($mime);
if (Core::is_readable($path)) {
unlink($path);
}
$filepath = fopen($path, "wb");
fwrite($filepath, $source);
fclose($filepath);
return true;
}
/**
* read_from_images
*/
private static function read_from_images()
{
$path = __DIR__ . '/../../../public/images/blankalbum.png';
if (!Core::is_readable($path)) {
debug_event(self::class, 'read_from_images ' . $path . ' cannot be read.', 1);
return null;
}
$image = '';
$filepath = fopen($path, "rb");
do {
$image .= fread($filepath, 2048);
} while (!feof($filepath));
fclose($filepath);
return $image;
}
/**
* read_from_dir
* @param $sizetext
* @param string $type
* @param integer $uid
* @param string $kind
* @param $mime
* @return string|null
*/
private static function read_from_dir($sizetext, $type, $uid, $kind, $mime)
{
$path = self::get_dir_on_disk($type, $uid, $kind);
if ($path === false) {
return null;
}
$path .= "art-" . $sizetext . '.' . self::extension($mime);
if (!Core::is_readable($path)) {
debug_event(self::class, 'Local image art ' . $path . ' cannot be read.', 1);
return null;
}
$image = '';
$filepath = fopen($path, "rb");
do {
$image .= fread($filepath, 2048);
} while (!feof($filepath));
fclose($filepath);
return $image;
}
/**
* delete_from_dir
* @param string $type
* @param string $uid
* @param string $kind
*/
private static function delete_from_dir($type, $uid, $kind = '')
{
if ($type && $uid) {
$path = self::get_dir_on_disk($type, $uid, $kind);
if ($path !== false) {
self::delete_rec_dir(rtrim($path, '/'));
}
}
}
/**
* delete_rec_dir
* @param string $path
*/
private static function delete_rec_dir($path)
{
debug_event(self::class, 'Deleting ' . (string) $path . ' directory...', 5);
if (Core::is_readable($path)) {
foreach (scandir($path) as $file) {
if ('.' === $file || '..' === $file) {
continue;
} elseif (is_dir($path . '/' . $file)) {
self::delete_rec_dir(rtrim($path, '/') . '/' . $file);
} else {
unlink($path . '/' . $file);
}
}
rmdir($path);
}
}
/**
* reset
* This resets the art in the database
*/
public function reset()
{
if (AmpConfig::get('album_art_store_disk')) {
self::delete_from_dir($this->type, $this->uid, $this->kind);
}
$sql = "DELETE FROM `image` WHERE `object_id` = ? AND `object_type` = ? AND `kind` = ?";
Dba::write($sql, array($this->uid, $this->type, $this->kind));
} // reset
/**
* save_thumb
* This saves the thumbnail that we're passed
* @param string $source
* @param string $mime
* @param array $size
* @return boolean
*/
public function save_thumb($source, $mime, $size)
{
// Quick sanity check
if (!self::test_image($source)) {
debug_event(self::class, 'Not inserting thumbnail, invalid data passed', 1);
return false;
}
$width = $size['width'];
$height = $size['height'];
$sizetext = $width . 'x' . $height;
$sql = "DELETE FROM `image` WHERE `object_id` = ? AND `object_type` = ? AND `size` = ? AND `kind` = ?";
Dba::write($sql, array($this->uid, $this->type, $sizetext, $this->kind));
if (AmpConfig::get('album_art_store_disk')) {
self::write_to_dir($source, $sizetext, $this->type, $this->uid, $this->kind, $mime);
$source = null;
}
$sql = "INSERT INTO `image` (`image`, `mime`, `size`, `width`, `height`, `object_type`, `object_id`, `kind`) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
Dba::write($sql, array($source, $mime, $sizetext, $width, $height, $this->type, $this->uid, $this->kind));
return true;
} // save_thumb
/**
* get_thumb
* Returns the specified resized image. If the requested size doesn't
* already exist, create and cache it.
* @param array $size
* @return array
*/
public function get_thumb($size)
{
$sizetext = $size['width'] . 'x' . $size['height'];
$sql = "SELECT `image`, `mime` FROM `image` WHERE `size` = ? AND `object_type` = ? AND `object_id` = ? AND `kind` = ?";
$db_results = Dba::read($sql, array($sizetext, $this->type, $this->uid, $this->kind));
$results = Dba::fetch_assoc($db_results);
if (count($results)) {
if (AmpConfig::get('album_art_store_disk')) {
$image = self::read_from_dir($sizetext, $this->type, $this->uid, $this->kind, $results['mime']);
} else {
$image = $results['image'];
}
if ($image != null) {
return array(
'thumb' => (AmpConfig::get('album_art_store_disk'))
? self::read_from_dir($sizetext, $this->type, $this->uid, $this->kind, $results['mime'])
: $results['image'],
'thumb_mime' => $results['mime']
);
} else {
debug_event(self::class, 'Thumb entry found in database but associated data cannot be found.', 3);
}
}
// If we didn't get a result try again
$results = array();
if (!$this->raw && $this->thumb) {
$results = $this->generate_thumb($this->thumb, $size, $this->raw_mime);
}
if ($this->raw) {
$results = $this->generate_thumb($this->raw, $size, $this->raw_mime);
}
if (!empty($results)) {
$this->save_thumb($results['thumb'], $results['thumb_mime'], $size);
}
return $results;
} // get_thumb
/**
* generate_thumb
* Automatically resizes the image for thumbnail viewing.
* Only works on gif/jpg/png/bmp. Fails if PHP-GD isn't available
* or lacks support for the requested image type.
* @param string $image
* @param array $size
* @param string $mime
* @return array
*/
public function generate_thumb($image, $size, $mime)
{
$data = explode('/', (string) $mime);
$type = ((string)($data[1] ?? '') !== '') ? strtolower((string) $data[1]) : 'jpg';
if (!self::test_image($image)) {
debug_event(self::class, 'Not trying to generate thumbnail, invalid data passed', 1);
return array();
}
if (!function_exists('gd_info')) {
debug_event(self::class, 'PHP-GD Not found - unable to resize art', 1);
return array();
}
// Check and make sure we can resize what you've asked us to
if (($type == 'jpg' || $type == 'jpeg' || $type == 'jpg?v=2') && !(imagetypes() & IMG_JPG)) {
debug_event(self::class, 'PHP-GD Does not support JPGs - unable to resize', 1);
return array();
}
if ($type == 'png' && !imagetypes() & IMG_PNG) {
debug_event(self::class, 'PHP-GD Does not support PNGs - unable to resize', 1);
return array();
}
if ($type == 'gif' && !imagetypes() & IMG_GIF) {
debug_event(self::class, 'PHP-GD Does not support GIFs - unable to resize', 1);
return array();
}
if ($type == 'bmp' && !imagetypes() & IMG_WBMP) {
debug_event(self::class, 'PHP-GD Does not support BMPs - unable to resize', 1);
return array();
}
$source = imagecreatefromstring($image);
if (!$source) {
debug_event(self::class, 'Failed to create Image from string - Source Image is damaged / malformed', 2);
return array();
}
$source_size = array('height' => imagesy($source), 'width' => imagesx($source));
// Create a new blank image of the correct size
$thumbnail = imagecreatetruecolor((int) $size['width'], (int) $size['height']);
if ($source_size['width'] > $source_size['height']) {
// landscape
$new_height = $size['height'];
$new_width = floor($source_size['width'] * ($new_height / $source_size['height']));
$crop_x = ceil(($source_size['width'] - $source_size['height']) / 2);
$crop_y = 0;
} elseif ($source_size['height'] > $source_size['width']) {
// portrait
$new_width = $size['width'];
$new_height = floor($source_size['height'] * ($new_width / $source_size['width']));
$crop_x = 0;
$crop_y = ceil(($source_size['height'] - $source_size['width']) / 3); // assuming most portrait images would have faces closer to the top
} else {
// square
$new_width = $size['width'];
$new_height = $size['height'];
$crop_x = 0;
$crop_y = 0;
}
if (!imagecopyresampled($thumbnail, $source, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $source_size['width'], $source_size['height'])) {
debug_event(self::class, 'Unable to create resized image', 1);
imagedestroy($source);
imagedestroy($thumbnail);
return array();
}
imagedestroy($source);
// Start output buffer
ob_start();
// Generate the image to our OB
switch ($type) {
case 'jpg':
case 'jpeg':
case 'jpg?v=2':
case '(null)':
imagejpeg($thumbnail, null, 75);
$mime_type = image_type_to_mime_type(IMAGETYPE_JPEG);
break;
case 'gif':
imagegif($thumbnail);
$mime_type = image_type_to_mime_type(IMAGETYPE_GIF);
break;
// Turn bmps into pngs
case 'bmp':
case 'png':
imagepng($thumbnail);
$mime_type = image_type_to_mime_type(IMAGETYPE_PNG);
break;
case 'webp':
imagewebp($thumbnail);
$mime_type = image_type_to_mime_type(IMAGETYPE_WEBP);
break;
default:
$mime_type = null;
} // resized
if ($mime_type === null) {
debug_event(self::class, 'Error: No mime type found using: ' . $mime, 2);
return array();
}
$data = ob_get_contents();
ob_end_clean();
imagedestroy($thumbnail);
if (!strlen((string) $data)) {
debug_event(self::class, 'Unknown Error resizing art', 1);
return array();
}
return array('thumb' => $data, 'thumb_mime' => $mime_type);
} // generate_thumb
/**
* get_from_source
* This gets an image for the album art from a source as
* defined in the passed array. Because we don't know where
* it's coming from we are a passed an array that can look like
* ['url'] = URL *** OPTIONAL ***
* ['file'] = FILENAME *** OPTIONAL ***
* ['raw'] = Actual Image data, already captured
* @param array $data
* @param string $type
* @return string
*/
public static function get_from_source($data, $type)
{
if (!isset($type)) {
$type = (AmpConfig::get('show_song_art')) ? 'song' : 'album';
}
if (empty($data) || !is_array($data)) {
return '';
}
// Already have the data, this often comes from id3tags
if (isset($data['raw'])) {
return $data['raw'];
}
// If it came from the database
if (isset($data['db'])) {
$sql = "SELECT * FROM `image` WHERE `object_type` = ? AND `object_id` = ? AND `size`='original'";
$db_results = Dba::read($sql, array($type, $data['db']));
$row = Dba::fetch_assoc($db_results);