summaryrefslogtreecommitdiffstats
path: root/lib/class/art.class.php
blob: d4cdea942f216d74d2202208494a1b8f2e706d8c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
<?php
/* vim:set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab: */
/**
 * Art Class
 *
 *
 * LICENSE: GNU General Public License, version 2 (GPLv2)
 * Copyright (c) 2001 - 2011 Ampache.org 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 v2
 * as published by the Free Software Foundation.
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * @package	Ampache
 * @copyright	2001 - 2011 Ampache.org
 * @license	http://opensource.org/licenses/gpl-2.0 GPLv2
 * @link	http://www.ampache.org/
 */

/**
 * Art Class
 *
 * This class handles the images / artwork in ampache
 * This was initially in the album class, but was pulled out
 * to be more general, and apply to albums, artists, movies etc
 *
 * @package	Ampache
 * @copyright	2001 - 2011 Ampache.org
 * @license	http://opensource.org/licenses/gpl-2.0 GPLv2
 * @link	http://www.ampache.org/
 */
class Art extends database_object {

	public $type;
	public $uid; // UID of the object not ID because it's not the ART.ID
	public $raw; // Raw art data
	public $raw_mime;

	public $thumb;
	public $thumb_mime;

	private static $enabled;

	/**
	 * Constructor
	 * Art constructor, takes the UID of the object and the
	 * object type.
	 */
	public function __construct($uid, $type = 'album') {

		$this->type = Art::validate_type($type);
		$this->uid = $uid;

	} // constructor

	/**
	 * 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
	 */
	public static function build_cache($object_ids) {

		if (!is_array($object_ids) || !count($object_ids)) { return false; }
		$uidlist = '(' . implode(',', $object_ids) . ')';
		$sql = "SELECT `object_type`, `object_id`, `mime`, `size` FROM `image` WHERE `object_id` IN $uidlist";
		$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


	/**
	 * _auto_init
	 * Called on creation of the class
	 */
	public static function _auto_init() {
		if (!isset($_SESSION['art_enabled'])) {
			$_SESSION['art_enabled'] = (Config::get('bandwidth') > 25);
		}
		self::$enabled = make_bool($_SESSION['art_enabled']);
	}

	/**
	 * is_enabled
	 * Checks whether the user currently wants art
	 */
	public static function is_enabled() {
		if (self::$enabled) {
			return true;
		}

		return false;
	}

	/**
	 * set_enabled
	 * Changes the value of enabled
	 */
	public static function set_enabled($value = null) {
		if (is_null($value)) {
			self::$enabled = self::$enabled ? false : true;
		}
		else {
			self::$enabled = make_bool($value);
		}

		$_SESSION['art_enabled'] = self::$enabled;
	}

	/**
	 * validate_type
	 * This validates the type
	 */
	public static function validate_type($type) {

		switch ($type) {
			case 'album':
			case 'artist':
			case 'video':
				return $type;
			break;
			default:
				return 'album';
			break;
		}

	} // validate_type

	/**
	 * extension
	 * This returns the file extension for the currently loaded art
	 */
	public static function extension($mime) {

		$data = explode("/", $mime);
		$extension = $data['1'];

		if ($extension == 'jpeg') { $extension = 'jpg'; }

		return $extension;

	} // extension

	/**
	 * test_image
	 * Runs some sanity checks on the putative image
	 */
	public static function test_image($source) {
		if (strlen($source) < 10) {
			debug_event('Art', 'Invalid image passed', 1);
			return false;
		}

		// Check to make sure PHP:GD exists.  If so, we can sanity check
		// the image.
		if (function_exists('ImageCreateFromString')) {
			 $image = ImageCreateFromString($source);
			 if (!$image || imagesx($image) < 5 || imagesy($image) < 5) {
				debug_event('Art', 'Image failed PHP-GD test',1);
				return false;
			}
		}

		return true;
	} //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.
	 */
	public function get($raw=false) {

		// Get the data either way
		if (!$this->get_db()) {
			return false;
		}

		if ($raw || !$this->thumb) {
			return $this->raw;
		}
		else {
			return $this->thumb;
		}

	} // get


	/**
	 * get_db
	 * 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
	 */
	public function get_db() {

		$type = Dba::escape($this->type);
		$id = Dba::escape($this->uid);

		$sql = "SELECT `image`, `mime`, `size` FROM `image` WHERE `object_type`='$type' AND `object_id`='$id'";
		$db_results = Dba::read($sql);

		while ($results = Dba::fetch_assoc($db_results)) {
			if ($results['size'] == 'original') {
				$this->raw = $results['image'];
				$this->raw_mime = $results['mime'];
			}
			else if (Config::get('resize_images') &&
					$results['size'] == '275x275') {
				$this->thumb = $results['image'];
				$this->raw_mime = $results['mime'];
			}
		}
		// If we get nothing return false
		if (!$this->raw) { return false; }

		// If there is no thumb and we want thumbs
		if (!$this->thumb && Config::get('resize_images')) {
			$data = $this->generate_thumb($this->raw, array('width' => 275, 'height' => 275), $this->raw_mime);
			// If it works save it!
			if ($data) {
				$this->save_thumb($data['thumb'], $data['thumb_mime'], '275x275');
				$this->thumb = $data['thumb'];
				$this->thumb_mime = $data['thumb_mime'];
			}
			else {
				debug_event('Art','Unable to retrieve or generate thumbnail for ' . $type . '::' . $id,1);
			}
		} // if no thumb, but art and we want to resize

		return true;

	} // get_db

	/**
	 * insert
	 * This takes the string representation of an image and inserts it into
	 * the database. You must also pass the mime type.
	 */
	public function insert($source, $mime) {

		// Disabled in demo mode cause people suck and upload porn
		if (Config::get('demo_mode')) { return false; }

		// Check to make sure we like this image
		if (!self::test_image($source)) {
			debug_event('Art', 'Not inserting image, invalid data passed', 1);
			return false;
		}

		// Default to image/jpeg if they don't pass anything
		$mime = $mime ? $mime : 'image/jpeg';

		$image = Dba::escape($source);
		$mime = Dba::escape($mime);
		$uid = Dba::escape($this->uid);
		$type = Dba::escape($this->type);

		// Blow it away!
		$this->reset();

		// Insert it!
		$sql = "INSERT INTO `image` (`image`, `mime`, `size`, `object_type`, `object_id`) VALUES('$image', '$mime', 'original', '$type', '$uid')";
		$db_results = Dba::write($sql);

		return true;

	} // insert

	/**
	 * reset
	 * This resets the art in the database
	 */
	public function reset() {

		$type = Dba::escape($this->type);
		$uid = Dba::escape($this->uid);

		$sql = "DELETE FROM `image` WHERE `object_id`='$uid' AND `object_type`='$type'";
		$db_results = Dba::write($sql);

	} // reset

	/**
	 * save_thumb
	 * This saves the thumbnail that we're passed
	 */
	public function save_thumb($source, $mime, $size) {

		// Quick sanity check
		if (!self::test_image($source)) {
			debug_event('Art', 'Not inserting thumbnail, invalid data passed', 1);
			return false;
		}

		$source = Dba::escape($source);
		$mime = Dba::escape($mime);
		$size = Dba::escape($size);
		$uid = Dba::escape($this->uid);
		$type = Dba::escape($this->type);

		$sql = "DELETE FROM `image` WHERE `object_id`='$uid' AND `object_type`='$type' AND `size`='$size'";
		$db_results = Dba::write($sql);

		$sql = "INSERT INTO `image` (`image`, `mime`, `size`, `object_type`, `object_id`) VALUES('$source', '$mime', '$size', '$type', '$uid')";
		$db_results = Dba::write($sql);

	} // save_thumb

	/**
	 * get_thumb
	 * Returns the specified resized image.  If the requested size doesn't
	 * already exist, create and cache it.
	 */
	public function get_thumb($size) {
		$sizetext = $size['width'] . 'x' . $size['height'];
		$sizetext = Dba::escape($sizetext);
		$type = Dba::escape($this->type);
		$uid = Dba::escape($this->uid);

		$sql = "SELECT `image`, `mime` FROM `image` WHERE `size`='$sizetext' AND `object_type`='$type' AND `object_id`='$uid'";
		$db_results = Dba::read($sql);

		$results = Dba::fetch_assoc($db_results);
		if (count($results)) {
			return array('thumb' => $results['image'],
				'thumb_mime' => $results['mime']);
		}

		// If we didn't get a result
		$results = $this->generate_thumb($this->raw, $size, $this->raw_mime);
		if ($results) {
			$this->save_thumb($results['thumb'], $results['thumb_mime'], $sizetext);
		}

		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.
	 */
	public function generate_thumb($image,$size,$mime) {

		$data = explode("/",$mime);
		$type = strtolower($data['1']);

		if (!self::test_image($image)) {
			debug_event('Art', 'Not trying to generate thumbnail, invalid data passed', 1);
			return false;
		}

		if (!function_exists('gd_info')) {
			debug_event('Art','PHP-GD Not found - unable to resize art',1);
			return false;
		}

		// Check and make sure we can resize what you've asked us to
		if (($type == 'jpg' OR $type == 'jpeg') AND !(imagetypes() & IMG_JPG)) {
			debug_event('Art','PHP-GD Does not support JPGs - unable to resize',1);
			return false;
		}
		if ($type == 'png' AND !imagetypes() & IMG_PNG) {
			debug_event('Art','PHP-GD Does not support PNGs - unable to resize',1);
			return false;
		}
		if ($type == 'gif' AND !imagetypes() & IMG_GIF) {
			debug_event('Art','PHP-GD Does not support GIFs - unable to resize',1);
			return false;
		}
		if ($type == 'bmp' AND !imagetypes() & IMG_WBMP) {
			debug_event('Art','PHP-GD Does not support BMPs - unable to resize',1);
			return false;
		}

		$source = imagecreatefromstring($image);

		if (!$source) {
			debug_event('Art','Failed to create Image from string - Source Image is damaged / malformed',1);
			return false;
		}

		$source_size = array('height' => imagesy($source), 'width' => imagesx($source));

		// Create a new blank image of the correct size
		$thumbnail = imagecreatetruecolor($size['width'], $size['height']);

		if (!imagecopyresampled($thumbnail, $source, 0, 0, 0, 0, $size['width'], $size['height'], $source_size['width'], $source_size['height'])) {
			debug_event('Art','Unable to create resized image',1);
			return false;
		}

		// Start output buffer
		ob_start();

		// Generate the image to our OB
		switch ($type) {
			case 'jpg':
			case 'jpeg':
				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':
				$type = 'png';
			case 'png':
				imagepng($thumbnail);
				$mime_type = image_type_to_mime_type(IMAGETYPE_PNG);
			break;
		} // resized

		$data = ob_get_contents();
		ob_end_clean();

		if (!strlen($data)) {
			debug_event('Art', 'Unknown Error resizing art', 1);
			return false;
		}

		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
	 */
	public static function get_from_source($data, $type = 'album') {

		// 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'])) {
			// Repull it
			$uid = Dba::escape($data['db']);
			$type = Dba::escape($type);

			$sql = "SELECT * FROM `image` WHERE `object_type`='$type' AND `object_id`='$uid' AND `size`='original'";
			$db_results = Dba::read($sql);
			$row = Dba::fetch_assoc($db_results);
			return $row['art'];
		} // came from the db

		// Check to see if it's a URL
		if (isset($data['url'])) {
			$snoopy = new Snoopy();
					if(Config::get('proxy_host') AND Config::get('proxy_port')) {
						$snoopy->proxy_user = Config::get('proxy_host');
						$snoopy->proxy_port = Config::get('proxy_port');
						$snoopy->proxy_user = Config::get('proxy_user');
						$snoopy->proxy_pass = Config::get('proxy_pass');
					}
			$snoopy->fetch($data['url']);
			return $snoopy->results;
		}

		// Check to see if it's a FILE
		if (isset($data['file'])) {
			$handle = fopen($data['file'],'rb');
			$image_data = fread($handle,filesize($data['file']));
			fclose($handle);
			return $image_data;
		}

		// Check to see if it is embedded in id3 of a song
		if (isset($data['song'])) {
			// If we find a good one, stop looking
			$getID3 = new getID3();
			$id3 = $getID3->analyze($data['song']);

			if ($id3['format_name'] == "WMA") {
				return $id3['asf']['extended_content_description_object']['content_descriptors']['13']['data'];
			}
			elseif (isset($id3['id3v2']['APIC'])) {
				// Foreach incase they have more then one
				foreach ($id3['id3v2']['APIC'] as $image) {
					return $image['data'];
				}
			}
		} // if data song

		return false;

	} // get_from_source

	/**
	 * url
	 * This returns the constructed URL for the art in question
	 */
	public static function url($uid,$type,$sid=false) {

		$sid = $sid ? scrub_out($sid) : scrub_out(session_id());
		$type = self::validate_type($type);

		$key = $type . $uid;
		if (parent::is_cached('art', $key . '275x275') && Config::get('resize_images')) {
			$row = parent::get_from_cache('art', $key . '275x275');
			$mime = $row['mime'];
		}
		if (parent::is_cached('art', $key . 'original')) {
			$row = parent::get_from_cache('art', $key . 'original');
			$thumb_mime = $row['mime'];
		}
		if (!$mime && !$thumb_mime) {

			$type = Dba::escape($type);
			$uid = Dba::escape($uid);

			$sql = "SELECT `object_type`, `object_id`, `mime`, `size` FROM `image` WHERE `object_type`='$type' AND `object_id`='$uid'";
			$db_results = Dba::read($sql);

			while ($row = Dba::fetch_assoc($db_results)) {
				parent::add_to_cache('art', $key . $row['size'], $row);
				if ($row['size'] == 'original') {
					$mime = $row['mime'];
				}
				else if ($row['size'] == '275x275' && Config::get('resize_images')) {
					$thumb_mime = $row['mime'];
				}
			}
		}

		$mime = $thumb_mime ? $thumb_mime : $mime;
		$extension = self::extension($mime);

		$name = 'art.' . $extension;
		$url = Config::get('web_path') . '/image.php?id=' . scrub_out($uid) . '&object_type=' . scrub_out($type) . '&auth=' . $sid . '&name=' . $name;

		return $url;

	} // url


	/**
	 * clean
	 * This cleans up art that no longer has a corresponding object
	 */
	public static function clean() {
		// iterate over our types and delete the images
		foreach (array('album', 'artist') as $type) {
			$sql = "DELETE FROM `image` USING `image` LEFT JOIN `" .
				$type . "` ON `" . $type . "`.`id`=" .
				"`image`.`object_id` WHERE `object_type`='" .
				$type . "' AND `" . $type . "`.`id` IS NULL";
			$db_results = Dba::write($sql);
		} // foreach
	} // clean

	/**
	 * gather
	 * This tries to get the art in question
	 */
	public function gather($options = array(), $limit = false) {

		// Define vars
		$results = array();

		switch ($this->type) {
			case 'album':
				$allowed_methods = array('db','lastfm','folder','amazon','google','musicbrainz','tags');
			break;
			case 'artist':
				$allowed_methods = array();
			break;
			case 'video':
				$allowed_methods = array();
			break;
		}

		$config = Config::get('art_order');
		$methods = get_class_methods('Art');

		/* If it's not set */
		if (empty($config)) {
			// They don't want art!
			debug_event('Art', 'art_order is empty, skipping art gathering', 3);
			return array();
		}
		elseif (!is_array($config)) {
			$config = array($config);
		}

		debug_event('Art','Searching using:' . json_encode($config), 3);

		foreach ($config as $method) {

			$data = array();

			if (!in_array($method, $allowed_methods)) {
				debug_event('Art', "$method not in allowed_methods, skipping", 3);
				continue;
			}

			$method_name = "gather_" . $method;

			if (in_array($method_name, $methods)) {
				debug_event('Art', "Method used: $method_name", 3);
				// Some of these take options!
				switch ($method_name) {
					case 'gather_amazon':
						$data = $this->{$method_name}($limit, $options['keyword']);
					break;
					case 'gather_lastfm':
						$data = $this->{$method_name}($limit, $options);
					break;
					default:
						$data = $this->{$method_name}($limit);
					break;
				}

				// Add the results we got to the current set
				$results = array_merge($results, (array)$data);

				if ($limit && count($results) >= $limit) {
					return array_slice($results, 0, $limit);
				}

			} // if the method exists
			else {
				debug_event("Art", "$method_name not defined", 1);
			}

		} // end foreach

		return $results;

	} // gather


	///////////////////////////////////////////////////////////////////////
	// Art Methods
	///////////////////////////////////////////////////////////////////////

	/**
	 * gather_db
	 * This function retrieves art that's already in the database
	 */
	public function gather_db($limit = null) {
		if ($this->get_db()) {
			return array('db' => true);
		}
		return array();
	}

	/**
	 * gather_musicbrainz
	 * This function retrieves art based on MusicBrainz' Advanced
	 * Relationships
	 */
	public function gather_musicbrainz($limit = 5) {
		$images	= array();
		$num_found = 0;

		if ($this->type == 'album') {
			$album = new Album($this->uid);
		}
		else {
			return $images;
		}

		if ($album->mbid) {
			debug_event('mbz-gatherart', "Album MBID: " . $album->mbid, '5');
		}
		else {
			return $images;
		}

		$mbquery = new MusicBrainzQuery();
		$includes = new mbReleaseIncludes();
		try {
			$release = $mbquery->getReleaseByID($album->mbid, $includes->urlRelations());
		} catch (Exception $e) {
			return $images;
		}

		$asin = $release->getAsin();

		if ($asin) {
			debug_event('mbz-gatherart', "Found ASIN: " . $asin, '5');
			$base_urls = array(
				"01" => "ec1.images-amazon.com",
				"02" => "ec1.images-amazon.com",
				"03" => "ec2.images-amazon.com",
				"08" => "ec1.images-amazon.com",
				"09" => "ec1.images-amazon.com",
			);
			foreach ($base_urls as $server_num => $base_url) {
				// to avoid complicating things even further, we only look for large cover art
				$url = 'http://' . $base_url . '/images/P/' . $asin . '.' . $server_num . '.LZZZZZZZ.jpg';
				debug_event('mbz-gatherart', "Evaluating Amazon URL: " . $url, '5');
				$snoopy = new Snoopy();
				if(Config::get('proxy_host') AND Config::get('proxy_port')) {
					$snoopy->proxy_user = Config::get('proxy_host');
					$snoopy->proxy_port = Config::get('proxy_port');
					$snoopy->proxy_user = Config::get('proxy_user');
					$snoopy->proxy_pass = Config::get('proxy_pass');
				}
				if ($snoopy->fetch($url)) {
					$num_found++;
					debug_event('mbz-gatherart', "Amazon URL added: " . $url, '5');
					$images[] = array(
						'url'  => $url,
						'mime' => 'image/jpeg',
					);
					if ($num_found >= $limit) {
						return $images;
					}
				}
			}
		}
		// The next bit is based directly on the MusicBrainz server code
		// that displays cover art.
		// I'm leaving in the releaseuri info for the moment, though
		// it's not going to be used.
		$coverartsites[] = array(
			'name' => "CD Baby",
			'domain' => "cdbaby.com",
			'regexp' => '@http://cdbaby\.com/cd/(\w)(\w)(\w*)@',
			'imguri' => 'http://cdbaby.name/$matches[1]/$matches[2]/$matches[1]$matches[2]$matches[3].jpg',
			'releaseuri' => 'http://cdbaby.com/cd/$matches[1]$matches[2]$matches[3]/from/musicbrainz',
		);
		$coverartsites[] = array(
			'name' => "CD Baby",
			'domain' => "cdbaby.name",
			'regexp' => "@http://cdbaby\.name/([a-z0-9])/([a-z0-9])/([A-Za-z0-9]*).jpg@",
			'imguri' => 'http://cdbaby.name/$matches[1]/$matches[2]/$matches[3].jpg',
			'releaseuri' => 'http://cdbaby.com/cd/$matches[3]/from/musicbrainz',
		);
		$coverartsites[] = array(
			'name' => 'archive.org',
			'domain' => 'archive.org',
			'regexp' => '/^(.*\.(jpg|jpeg|png|gif))$/',
			'imguri' => '$matches[1]',
			'releaseuri' => '',
		);
		$coverartsites[] = array(
			'name' => "Jamendo",
			'domain' => "www.jamendo.com",
			'regexp' => '/http://www\.jamendo\.com/(\w\w/)?album/(\d+)/',
			'imguri' => 'http://img.jamendo.com/albums/$matches[2]/covers/1.200.jpg',
			'releaseuri' => 'http://www.jamendo.com/album/$matches[2]',
		);
		$coverartsites[] = array(
			'name' => '8bitpeoples.com',
			'domain' => '8bitpeoples.com',
			'regexp' => '/^(.*)$/',
			'imguri' => '$matches[1]',
			'releaseuri' => '',
		);
		$coverartsites[] = array(
			'name' => 'Encyclopédisque',
			'domain' => 'encyclopedisque.fr',
			'regexp' => '/http://www.encyclopedisque.fr/images/imgdb/(thumb250|main)/(\d+).jpg/',
			'imguri' => 'http://www.encyclopedisque.fr/images/imgdb/thumb250/$matches[2].jpg',
			'releaseuri' => 'http://www.encyclopedisque.fr/',
		);
		$coverartsites[] = array(
			'name' => 'Thastrom',
			'domain' => 'www.thastrom.se',
			'regexp' => '/^(.*)$/',
			'imguri' => '$matches[1]',
			'releaseuri' => '',
		);
		$coverartsites[] = array(
			'name' => 'Universal Poplab',
			'domain' => 'www.universalpoplab.com',
			'regexp' => '/^(.*)$/',
			'imguri' => '$matches[1]',
			'releaseuri' => '',
		);
		foreach ($release->getRelations(mbRelation::TO_URL) as $ar) {
			$arurl = $ar->getTargetId();
			debug_event('mbz-gatherart', "Found URL AR: " . $arurl , '5');
			foreach ($coverartsites as $casite) {
				if (strpos($arurl, $casite['domain']) !== false) {
					debug_event('mbz-gatherart', "Matched coverart site: " . $casite['name'], '5');
					if (preg_match($casite['regexp'], $arurl, $matches)) {
						$num_found++;
						eval("\$url = \"$casite[imguri]\";");
						debug_event('mbz-gatherart', "Generated URL added: " . $url, '5');
						$images[] = array(
							'url'  => $url,
							'mime' => 'image/jpeg',
						);
						if ($num_found >= $limit) {
							return $images;
						}
					}
				}
			} // end foreach coverart sites
		} // end foreach

		return $images;

	} // gather_musicbrainz

	/**
	 * gather_amazon
	 * This takes keywords and performs a search of the Amazon website
	 * for the art. It returns an array of found objects with mime/url keys
	 */
	public function gather_amazon($limit = 5, $keywords = '') {

		$images	 = array();
		$final_results  = array();
		$possible_keys = array(
			'LargeImage',
			'MediumImage',
			'SmallImage'
		);

		// Prevent the script from timing out
		set_time_limit(0);

		if (empty($keywords)) {
			$keywords = $this->full_name;
			/* If this isn't a various album combine with artist name */
			if ($this->artist_count == '1') { $keywords .= ' ' . $this->artist_name; }
		}

		/* Attempt to retrieve the album art order */
		$amazon_base_urls = Config::get('amazon_base_urls');

		/* If it's not set */
		if (!count($amazon_base_urls)) {
			$amazon_base_urls = array('http://webservices.amazon.com');
		}

		/* Foreach through the base urls that we should check */
		foreach ($amazon_base_urls as $amazon_base) {

			// Create the Search Object
			$amazon = new AmazonSearch(Config::get('amazon_developer_public_key'), Config::get('amazon_developer_private_key'), $amazon_base);
				if(Config::get('proxy_host') AND Config::get('proxy_port')) {
					$proxyhost = Config::get('proxy_host');
					$proxyport = Config::get('proxy_port');
					$proxyuser = Config::get('proxy_user');
					$proxypass = Config::get('proxy_pass');
					debug_event('amazon', 'setProxy', 5);
					$amazon->setProxy($proxyhost, $proxyport, $proxyuser, $proxypass);
				}

			$search_results = array();

			/* Set up the needed variables */
			$max_pages_to_search = max(Config::get('max_amazon_results_pages'),$amazon->_default_results_pages);
			$pages_to_search = $max_pages_to_search; //init to max until we know better.
			// while we have pages to search
			do {
				$raw_results = $amazon->search(array('artist'=>$artist,'album'=>$albumname,'keywords'=>$keywords));

				$total = count($raw_results) + count($search_results);

				// If we've gotten more then we wanted
				if ($limit && $total > $limit) {
					$raw_results = array_slice($raw_results, 0, -($total - $limit), true);

					debug_event('amazon-xml', "Found $total, limit $limit; reducing and breaking from loop", 5);
					// Merge the results and BREAK!
					$search_results = array_merge($search_results,$raw_results);
					break;
				} // if limit defined

				$search_results = array_merge($search_results,$raw_results);
				$pages_to_search = min($max_pages_to_search, $amazon->_maxPage);
				debug_event('amazon-xml', "Searched results page " . ($amazon->_currentPage+1) . "/" . $pages_to_search,'5');
				$amazon->_currentPage++;

			} while ($amazon->_currentPage < $pages_to_search);


			// Only do the second search if the first actually returns something
			if (count($search_results)) {
				$final_results = $amazon->lookup($search_results);
			}

			/* Log this if we're doin debug */
			debug_event('amazon-xml',"Searched using $keywords with " . Config::get('amazon_developer_key') . " as key, results: " . count($final_results), 5);

			// If we've hit our limit
			if (!empty($limit) && count($final_results) >= $limit) {
				break;
			}

		} // end foreach

		/* Foreach through what we've found */
		foreach ($final_results as $result) {

			/* Recurse through the images found */
			foreach ($possible_keys as $key) {
				if (strlen($result[$key])) {
					break;
				}
			} // foreach

			// Rudimentary image type detection, only JPG and GIF allowed.
			if (substr($result[$key], -4 == '.jpg')) {
				$mime = "image/jpeg";
			}
			elseif (substr($result[$key], -4 == '.gif')) {
				$mime = "image/gif";
			}
			elseif (substr($result[$key], -4 == '.png')) {
				$mime = "image/png";
			}
			else {
				/* Just go to the next result */
				continue;
			}

			$data['url']    = $result[$key];
			$data['mime']   = $mime;

			$images[] = $data;

			if (!empty($limit)) {
				if (count($images) >= $limit) {
					return $images;
				}
			}

		} // if we've got something

		return $images;

	} // gather_amazon

	/**
	 * gather_folder
	 * This returns the art from the folder of the files
	 * If a limit is passed or the preferred filename is found the current
	 * results set is returned
	 */
	public function gather_folder($limit = 5) {

		$media = new Album($this->uid);
		$songs = $media->get_songs();
		$results = array();
		$preferred = false;
		// For storing which directories we've already done
		$processed = array();

		/* See if we are looking for a specific filename */
		$preferred_filename = Config::get('album_art_preferred_filename');

		// Array of valid extensions
		$image_extensions = array(
			'bmp',
			'gif',
			'jp2',
			'jpeg',
			'jpg',
			'png'
		);

		foreach ($songs as $song_id) {
			$data = array();
			$song = new Song($song_id);
			$dir = dirname($song->file);

			if (isset($processed[$dir])) {
				continue;
			}

			debug_event('folder_art', "Opening $dir and checking for Album Art", 3);

			/* Open up the directory */
			$handle = opendir($dir);

			if (!$handle) {
				Error::add('general', T_('Error: Unable to open') . ' ' . $dir);
				debug_event('folder_art', "Error: Unable to open $dir for album art read", 2);
				continue;
			}

			$processed[$dir] = true;

			// Recurse through this dir and create the files array
			while ($file = readdir($handle)) {
				$extension = pathinfo($file);
				$extension = $extension['extension'];

				// Make sure it looks like an image file
				if (!in_array($extension, $image_extensions)) {
					continue;
				}

				$full_filename = $dir . '/' . $file;

				// Make sure it's got something in it
				if (!filesize($full_filename)) {
					debug_event('folder_art', "Empty file, rejecting $file", 5);
					continue;
				}

				// Regularise for mime type
				if ($extension == 'jpg') {
					$extension = 'jpeg';
				}

				// Take an md5sum so we don't show duplicate
				// files.
				$index = md5($full_filename);

				if ($file == $preferred_filename) {
					// We found the preferred filename and
					// so we're done.
					debug_event('folder_art', "Found preferred image file: $file", 5);
					$preferred[$index] = array(
						'file' => $full_filename,
						'mime' => 'image/' . $extension
					);
					break;	
				}

				debug_event('folder_art', "Found image file: $file", 5);
				$results[$index] = array(
					'file' => $full_filename,
					'mime' => 'image/' . $extension
				);

			} // end while reading dir
			closedir($handle);

		} // end foreach songs

		if (is_array($preferred)) {
			// We found our favourite filename somewhere, so we need
			// to dump the other, less sexy ones.
			$results = $preferred;
		}

		debug_event('folder_art', 'Results: ' . json_encode($results), 5);
		if ($limit && count($results) > $limit) {
			$results = array_slice($results, 0, $limit);
		}

		return array_values($results);

	} // gather_folder

	/**
	 * gather_tags
	 * This looks for the art in the meta-tags of the file
	 * itself
	 */
	public function gather_tags($limit = 5) {

		// We need the filenames
		$album = new Album($this->uid);

		// grab the songs and define our results
		$songs = $album->get_songs();
		$data = array();

		// Foreach songs in this album
		foreach ($songs as $song_id) {
			$song = new Song($song_id);
			// If we find a good one, stop looking
			$getID3 = new getID3();
			try { $id3 = $getID3->analyze($song->file); }
			catch (Exception $error) {
				debug_event('getid3', $error->message, 1);
			}

			if (isset($id3['asf']['extended_content_description_object']['content_descriptors']['13'])) {
				$image = $id3['asf']['extended_content_description_object']['content_descriptors']['13'];
				$data[] = array(
					'song' => $song->file,
					'raw' => $image['data'],
					'mime' => $image['mime']);
			}

			if (isset($id3['id3v2']['APIC'])) {
				// Foreach incase they have more then one
				foreach ($id3['id3v2']['APIC'] as $image) {
					$data[] = array(
						'song' => $song->file,
						'raw' => $image['data'],
						'mime' => $image['mime']);
				}
			}

			if ($limit && count($data) >= $limit) {
				return array_slice($data, 0, $limit);
			}

		} // end foreach

		return $data;

	} // gather_tags

	/**
	 * gather_google
	 * Raw google search to retrieve the art, not very reliable
	 */
	public function gather_google($limit = 5) {

		$images = array();
		$media = new $this->type($this->uid);
		$media->format();

		$search = $media->full_name;

		if ($media->artist_count == '1')
			$search = $media->artist_name . ', ' . $search;

		$search = rawurlencode($search);

		$size = '&imgsz=m'; // Medium
		//$size = '&imgsz=l'; // Large

		$html = file_get_contents("http://images.google.com/images?source=hp&q=$search&oq=&um=1&ie=UTF-8&sa=N&tab=wi&start=0&tbo=1$size");

		if(preg_match_all("|\ssrc\=\"(http.+?)\"|", $html, $matches, PREG_PATTERN_ORDER))
			foreach ($matches[1] as $match) {
				$extension = "image/jpeg";

				if (strrpos($extension, '.') !== false) $extension = substr($extension, strrpos($extension, '.') + 1);

				$images[] = array('url' => $match, 'mime' => $extension);
			}

		return $images;

	} // gather_google

	/**
	 * gather_lastfm
	 * This returns the art from lastfm. It doesn't currently require an
	 * account but may in the future.
	 */
	public function gather_lastfm($limit, $options = false) {

		// Create the parser object
		$lastfm = new LastFMSearch();

		switch ($this->type) {
			case 'album':
				if (is_array($options)) {
					$artist = $options['artist'];
					$album  = $options['album_name'];
				}
				else {
					$media = new Album($this->uid);
					$media->format();
					$artist = $media->artist_name;
					$album = $media->full_name;
				}
			break;
		}

		if(Config::get('proxy_host') AND Config::get('proxy_port')) {
			$proxyhost = Config::get('proxy_host');
			$proxyport = Config::get('proxy_port');
			$proxyuser = Config::get('proxy_user');
			$proxypass = Config::get('proxy_pass');
			debug_event('LastFM', 'proxy set', 5);
			$lastfm->setProxy($proxyhost, $proxyport, $proxyuser, $proxypass);
		}

		$raw_data = $lastfm->album_search($artist, $album);

		if (!count($raw_data)) { return array(); }

		$coverart = $raw_data['coverart'];
		if (!is_array($coverart)) { return array(); }

		ksort($coverart);
		foreach ($coverart as $url) {
			// We need to check the URL for the /noimage/ stuff
			if (strpos($url, '/noimage/') !== false) {
				debug_event('LastFM', 'Detected as noimage, skipped ' . $url, 3);
				continue;
			}
			
			// HACK: we shouldn't rely on the extension to determine file type
	        	$results = pathinfo($url);
			$mime = 'image/' . $results['extension'];
			$data[] = array('url' => $url, 'mime' => $mime);
			if ($limit && count($data) >= $limit) {
				return $data;
			}
		} // end foreach

		return $data;

	} // gather_lastfm

} // Art