forked from ben-xo/dir2cast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdir2cast.php
1457 lines (1232 loc) · 38.1 KB
/
dir2cast.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
/******************************************************************************
* Copyright (c) 2008-2010, Ben XO ([email protected]).
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of dir2cast nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
*
* USAGE:
*
* 1) edit dir2cast.ini and fill in the settings.
*
* 2) visit:
*
* http://www.yoursite.com/dir2cast.php
*
* or
*
* http://www.yoursite.com/dir2cast.php?dir=my_mp3_subdir
* ^-- check in the README.txt for a way to get pretty URLS using mod_rewrite
*
* or
*
* user$ php ./dir2cast.php my_mp3_dir
* ^-- from the command line
*
* If your MP3 dir is different from the dir the script is in, then you can have
* have a master dir2cast.ini in the same dir as dir2cast.php, and cast-specific
* configuration in another dir2cast.ini in the same dir as your MP3s.
*/
/* DEFAULTS *********************************************/
// error handler needs these, so let's set them now.
define('VERSION', '1.7.1');
define('DIR2CAST_HOMEPAGE', 'http://www.ben-xo.com/dir2cast/');
define('GENERATOR', 'dir2cast ' . VERSION . ' by Ben XO (' . DIR2CAST_HOMEPAGE . ')');
error_reporting(E_ALL);
set_error_handler( array('ErrorHandler', 'handle_error') );
set_exception_handler( array( 'ErrorHandler', 'handle_exception') );
// Best do everything in UTC.
date_default_timezone_set( 'UTC' );
/* EXTERNALS ********************************************/
function __autoload($class_name)
{
switch(strtolower($class_name))
{
case 'getid3':
ErrorHandler::prime('getid3');
if(file_exists('getID3/getid3.php'))
require_once('getID3/getid3.php');
else
require_once('getid3/getid3.php');
ErrorHandler::defuse();
break;
default:
require_once $class_name . '.php';
}
}
/* CLASSES **********************************************/
abstract class GetterSetter {
protected $parameters = array();
/**
* Missing Method Magic Accessor
*
* @param string $method Method to call (get* or set*)
* @param array $params array of parameters for the method
* @return mixed the result of the method
*/
public function __call($method, $params)
{
$var_name = substr($method, 3);
$var_name{0} = strtolower($var_name{0});
switch(strtolower(substr($method, 0, 3)))
{
case 'get':
if(isset($this->parameters[$var_name]))
return $this->parameters[$var_name];
break;
case 'set':
$this->parameters[$var_name] = $params[0];
break;
default:
throw new Exception("Unknown method '" . $method . "' called on " . __CLASS__);
}
}
}
interface Podcast_Helper {
public function appendToChannel(DOMElement $d, DOMDocument $doc);
public function appendToItem(DOMElement $d, DOMDocument $doc, RSS_Item $item);
public function addNamespaceTo(DOMElement $d, DOMDocument $doc);
}
/**
* Uses external getID3 lib to analyze MP3 files.
*
*/
class getID3_Podcast_Helper implements Podcast_Helper {
/**
* getID3 analyzer
*
* @var getid3
*/
protected $getid3;
public function appendToChannel(DOMElement $d, DOMDocument $doc) { /* nothing */ }
public function addNamespaceTo(DOMElement $d, DOMDocument $doc) { /* nothing */ }
/**
* Fills in a bunch of info on the Item by using getid3->Analyze()
*/
public function appendToItem(DOMElement $d, DOMDocument $doc, RSS_Item $item)
{
if($item instanceof MP3_RSS_Item && !$item->getAnalyzed())
{
if(!isset($this->getid3))
{
$this->getid3 = new getid3();
$this->getid3->option_tag_lyrics3 = false;
$this->getid3->option_tag_apetag = false;
$this->getid3->encoding = 'UTF-8';
}
try
{
$info = $this->getid3->Analyze($item->getFilename());
}
catch(getid3_exception $e)
{
// MP3 couldn't be analyzed.
return;
}
if(!empty($info['bitrate']))
$item->setBitrate($info['bitrate']);
if(!empty($info['comments']))
{
if(!empty($info['comments']['title'][0]))
$item->setID3Title( $info['comments']['title'][0] );
if(!empty($info['comments']['artist'][0]))
$item->setID3Artist( $info['comments']['artist'][0] );
if(!empty($info['comments']['album'][0]))
$item->setID3Album( $info['comments']['album'][0] );
if(!empty($info['comments']['comment'][0]))
$item->setID3Comment( $info['comments']['comment'][0] );
}
if(!empty($info['playtime_string']))
$item->setDuration( $info['playtime_string'] );
$item->setAnalyzed(true);
unset($this->getid3);
}
}
}
class Atom_Podcast_Helper extends GetterSetter implements Podcast_Helper {
protected $self_link;
public function __construct() { }
public function getNSURI()
{
return 'http://www.w3.org/2005/Atom';
}
public function addNamespaceTo(DOMElement $d, DOMDocument $doc)
{
$d->appendChild( $doc->createAttribute( 'xmlns:atom' ) )
->appendChild( new DOMText( $this->getNSURI() ) );
}
public function appendToChannel(DOMElement $channel, DOMDocument $doc)
{
foreach ($this->parameters as $name => $val)
{
$channel->appendChild( $doc->createElement('atom:' . $name) )
->appendChild( new DOMText($val) );
}
if(!empty($this->self_link))
{
$linkNode = $channel->appendChild( $doc->createElement('atom:link') );
$linkNode->setAttribute('href', $this->self_link);
$linkNode->setAttribute('rel', 'self');
$linkNode->setAttribute('type', ATOM_TYPE);
}
}
public function appendToItem(DOMElement $item_element, DOMDocument $doc, RSS_Item $item)
{
}
public function setSelfLink($link)
{
$this->self_link = $link;
}
}
class iTunes_Podcast_Helper extends GetterSetter implements Podcast_Helper {
protected $owner_name, $owner_email, $image_href;
public function __construct() { }
public function getNSURI()
{
return 'http://www.itunes.com/dtds/podcast-1.0.dtd';
}
public function addNamespaceTo(DOMElement $d, DOMDocument $doc)
{
$d->appendChild( $doc->createAttribute( 'xmlns:itunes' ) )
->appendChild( new DOMText( $this->getNSURI() ) );
}
public function appendToChannel(DOMElement $channel, DOMDocument $doc)
{
foreach ($this->parameters as $name => $val)
{
$channel->appendChild( $doc->createElement('itunes:' . $name) )
->appendChild( new DOMText($val) );
}
foreach ($this->categories as $category => $subcats)
{
$this->appendCategory($category, $subcats, $channel, $doc);
}
if(!empty($this->owner_name) || !empty($this->owner_email))
{
$owner = $channel->appendChild( $doc->createElement('itunes:owner') );
if(!empty($this->owner_name))
{
$owner->appendChild( $doc->createElement('itunes:name') )
->appendChild( new DOMText( $this->owner_name ) );
}
if(!empty($this->owner_email))
{
$owner->appendChild( $doc->createElement('itunes:email') )
->appendChild( new DOMText( $this->owner_email ) );
}
}
if(!empty($this->image_href))
{
$channel->appendChild( $doc->createElement('itunes:image') )
->setAttribute('href', $this->image_href);
}
}
public function appendToItem(DOMElement $item_element, DOMDocument $doc, RSS_Item $item)
{
/*
* <itunes:author>John Doe</itunes:author>
* <itunes:duration>7:04</itunes:duration>
* <itunes:subtitle>A short primer on table spices</itunes:subtitle>
* <itunes:summary>This week we talk about salt and pepper shakers,
* [...] Come and join the party!</itunes:summary>
* <itunes:keywords>salt, pepper, shaker, exciting</itunes:keywords>
*/
$elements = array(
'author' => $item->getID3Artist(),
'duration' => $item->getDuration(),
//'keywords' => 'not supported yet.'
);
// iTunes summary is excluded if it's empty, because the default is to
// duplicate what's in the "description field", but iTunes will fall back
// to showing the <description> if there is no summary anyway.
$itunes_summary = $item->getSummary();
if($itunes_summary !== '')
{
$elements['summary'] = $itunes_summary;
}
// iTunes subtitle is excluded if it's empty. iTunes will fall back to
// the itunes:summary or description if there's no subtitle.
$itunes_subtitle = $item->getSubtitle();
if($itunes_subtitle !== '')
{
$elements['subtitle'] = $itunes_subtitle . ITUNES_SUBTITLE_SUFFIX;
}
foreach($elements as $key => $val)
if(!empty($val))
$item_element->appendChild( $doc->createElement('itunes:' . $key) )
->appendChild( new DOMText($val) );
// Look to see if there is a item specific image and include it.
$item_image = $item->getImage();
if(!empty($item_image))
{
$item_element->appendChild( $doc->createElement('itunes:image') )
->setAttribute('href', $item_image);
}
}
public function appendCategory($category, $subcats, DOMElement $e, DOMDocument $doc)
{
$e->appendChild( $element = $doc->createElement('itunes:category') )
->setAttribute('text', $category);
if(is_array($subcats))
foreach($subcats as $subcategory => $subsubcats)
$this->appendCategory($subcategory, $subsubcats, $element, $doc);
}
/**
* Takes a category specification string and arrayifies it.
* e.g.
* 'Music | Technology > Gadgets '
* becomes
* array( 'Music' => true, 'Technology' => array( 'Gadgets' ) );
* @param string $category_string
*/
public function addCategories($category_string) {
$categories = array();
foreach(explode('|', $category_string) as $top_level_category)
{
$sub_categories = explode('>', $top_level_category);
$top_level_category = trim( array_shift($sub_categories) );
if('' != $top_level_category)
{
if(empty($sub_categories))
{
$categories[$top_level_category] = true;
}
else
{
foreach($sub_categories as $sub_category)
{
$sub_category = trim($sub_category);
if('' != $sub_category)
{
$categories[$top_level_category][$sub_category] = true;
}
}
}
}
}
$this->categories = $categories;
}
public function setOwnerName($name)
{
$this->owner_name = $name;
}
public function setOwnerEmail($email)
{
$this->owner_email = $email;
}
public function setImage($href)
{
$this->image_href = $href;
}
}
class RSS_Item extends GetterSetter {
protected $helpers = array();
public function __construct() { }
public function appendToChannel(DOMElement $channel, DOMDocument $doc)
{
$item_element = $channel->appendChild( new DOMElement('item') );
foreach($this->helpers as $helper)
{
// do helpers first; they may fill in the stuff we add down below.
$helper->appendToItem($item_element, $doc, $this);
}
$item_elements = array(
'title' => $this->getTitle(),
'link' => $this->getLink(),
'pubDate' => $this->getPubDate()
);
if(DESCRIPTION_SOURCE == 'file')
$description = $this->getSummary();
else
$description = $this->getDescription();
$cdata_item_elements = array(
'description' => $description
);
if(empty($item_elements['title']))
$item_elements['title'] = '(untitled)';
foreach($item_elements as $name => $val)
{
$item_element->appendChild( new DOMElement($name) )
->appendChild(new DOMText($val));
}
foreach($cdata_item_elements as $name => $val)
{
if($name == 'description')
if(!defined('DESCRIPTION_HTML'))
$val = htmlspecialchars($val);
$item_element->appendChild( new DOMElement($name) )
->appendChild( $doc->createCDATASection(
// reintroduce newlines as <br />.
nl2br($val))
);
}
// Look to see if there is a item specific image and include it.
$item_image = $this->getImage();
if(!empty($item_image))
{
$item_element->appendChild( $doc->createElement('image') )
->appendChild(new DOMText($item_image));
}
$enclosure = $item_element->appendChild(new DOMElement('enclosure'));
$enclosure->setAttribute('url', $this->getLink());
$enclosure->setAttribute('length', $this->getLength());
$enclosure->setAttribute('type', $this->getType());
}
public function addHelper(Podcast_Helper $helper)
{
$this->helpers[] = $helper;
return $helper;
}
}
class RSS_File_Item extends RSS_Item {
protected $filename;
protected $extension;
public function __construct($filename)
{
$this->filename = $filename;
$this->extension =
$this->setLinkFromFilename($filename);
parent::__construct();
}
public function setLinkFromFilename($filename)
{
$url = rtrim(MP3_URL, '/') . '/' . rawurlencode(basename($filename));
$this->setLink($url);
}
public function getType()
{
return 'application/octet-stream';
}
public function getFilename()
{
return $this->filename;
}
public function getExtension()
{
if(!isset($this->extension))
{
$pos = strrpos($this->getFilename(), '.');
if($pos !== false)
{
$this->extension = substr($this->getFilename(), $pos + 1);
}
else
{
$this->extension = '';
}
}
return $this->extension;
}
/**
* Place a file with the same name but .txt instead of .<whatever> and the contents will be used
* as the summary for the item in the podcast.
*
* The summary appears in iTunes when you click the 'more info' icon, and can be
* multiple lines long.
*
* @return String the summary, or null if there's no summary file
*/
public function getSummary()
{
$summary_file_name = dirname($this->getFilename()) . '/' . basename($this->getFilename(), '.' . $this->getExtension()) . '.txt';
if(file_exists( $summary_file_name ))
return file_get_contents($summary_file_name);
}
/**
* Place a file with the same name but _subtitle.txt instead of .<whatever> and the contents will be used
* as the subtitle for the item in the podcast.
*
* The subtitle appears inline with the podcast item in iTunes, and has a 'more info' icon next
* to it. It should be a single line.
*
* @return String the subtitle, or null if there's no subtitle file
*/
public function getSubtitle()
{
$summary_file_name = dirname($this->getFilename()) . '/' . basename($this->getFilename(), '.' . $this->getExtension()) . '_subtitle.txt';
if(file_exists( $summary_file_name ))
return file_get_contents($summary_file_name);
}
/**
* Place a file with the same name but .jpg or .png instead of .<whatever> and the contents will be used
* as the cover art for the item in the podcast.
*
* @return String the filename of the cover art or null if there's no subtitle file
*/
public function getImage()
{
$image_file_name = dirname($this->getFilename()) . '/' . basename($this->getFilename(), '.' . $this->getExtension()) . '.jpg';
if(file_exists( $image_file_name ))
return $image_file_name;
$image_file_name = dirname($this->getFilename()) . '/' . basename($this->getFilename(), '.' . $this->getExtension()) . '.png';
if(file_exists( $image_file_name ))
return $image_file_name;
}
}
class MP3_RSS_Item extends RSS_File_Item {
public function __construct($filename)
{
$this->setFromMP3File($filename);
parent::__construct($filename);
}
public function setFromMP3File($file)
{
// don't do any heavy-lifting here as this is called by the constructor, which
// is called once for every file in the dir (not just the ITEM_COUNT in the cast)
$this->setLength(filesize($file));
$this->setPubDate(date('r', filemtime($file)));
}
public function getTitle()
{
$title_parts = array();
if(LONG_TITLES)
{
if($this->getID3Album()) $title_parts[] = $this->getID3Album();
if($this->getID3Artist()) $title_parts[] = $this->getID3Artist();
}
if($this->getID3Title()) $title_parts[] = $this->getID3Title();
return implode(' - ', $title_parts);
}
public function getType()
{
return 'audio/mpeg';
}
public function getDescription()
{
return $this->getID3Comment();
}
public function getSummary()
{
$summary = parent::getSummary();
if(null == $summary && !LONG_TITLES)
{
// use description as summary if there's no file-based override
$summary = $this->getDescription();
}
return $summary;
}
public function getSubtitle()
{
$subtitle = parent::getSubtitle();
if(null == $subtitle && !LONG_TITLES)
{
// use artist as summary if there's no file-based override
$subtitle = $this->getID3Artist();
}
return $subtitle;
}
public function getImage()
{
$image = parent::getImage();
return $image;
}
}
abstract class Podcast extends GetterSetter
{
protected $max_mtime = 0;
protected $items = array();
protected $helpers = array();
public function addHelper(Podcast_Helper $helper)
{
$this->helpers[] = $helper;
// attach helper to items already added.
// new items will have the helper attacged when they are added.
foreach($this->items as $item)
$item->addHelper($helper);
return $helper;
}
// public function getNSURI()
// {
// return 'http://backend.userland.com/RSS2';
// }
public function http_headers()
{
header('Content-type: application/rss+xml');
header('Last-modified: ' . $this->getLastBuildDate());
}
/**
* Generates and returns the podcast RSS
*
* @return String the PodCast RSS
*/
public function generate()
{
$this->pre_generate();
$this->setLastBuildDate(date('r'));
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->formatOutput = true;
$rss = $doc->createElement('rss');
$doc->appendChild($rss);
$rss->setAttribute('version', '2.0');
// we do not show the default xmlns. Seems to break the validator.
// $rss->appendChild( $doc->createAttribute( 'xmlns' ) )
// ->appendChild( new DOMText( $this->getNSURI() ) );
foreach($this->helpers as $helper)
$helper->addNamespaceTo($rss, $doc);
// the channel
$channel = $rss->appendChild(new DOMElement('channel'));
$channel_elements = array(
'title' => $this->getTitle(),
'link' => $this->getLink(),
'description' => $this->getDescription(),
'lastBuildDate' => $this->getLastBuildDate(),
'language' => $this->getLanguage(),
'copyright' => $this->getCopyright(),
'generator' => $this->getGenerator(),
'webMaster' => $this->getWebMaster(),
'ttl' => $this->getTtl()
);
foreach($channel_elements as $name => $val)
{
$channel->appendChild( new DOMElement($name) )
->appendChild(new DOMText($val));
}
$this->appendImage($channel);
foreach($this->helpers as $helper)
{
$helper->appendToChannel($channel, $doc);
}
// channel item list
foreach($this->getItems() as $item)
{
/* @var $item RSS_Item */
$item->appendToChannel($channel, $doc);
}
$this->post_generate($doc);
$doc->normalizeDocument();
// see http://validator.w3.org/feed/docs/warning/CharacterData.html
return str_replace(
array('&', '<', '>'),
array('&', '<', '>'),
$doc->saveXML()
);
}
/**
* @return array of RSS_Item
*/
public function getItems()
{
return $this->items;
}
protected function appendImage(DOMElement $channel)
{
$image_url = $this->getImage();
if(strlen($image_url))
{
$image = $channel->appendChild( new DOMElement('image'));
$image->appendChild( new DOMElement('url') )
->appendChild(new DOMText($image_url));
$image->appendChild( new DOMElement('link') )
->appendChild(new DOMText($this->getLink()));
$image->appendChild( new DOMElement('title') )
->appendChild(new DOMText($this->getTitle()));
$channel->appendChild($image);
}
}
protected function pre_generate() { }
protected function post_generate(DOMDocument $doc) { }
}
class Dir_Podcast extends Podcast
{
protected $source_dir;
protected $scanned = false;
protected $unsorted_items = array();
/**
* Constructor
*
* @param string $source_dir
*/
public function __construct($source_dir)
{
$this->source_dir = $source_dir;
}
protected function scan()
{
if(!$this->scanned)
{
$this->pre_scan();
// scan the dir
$di = new DirectoryIterator($this->source_dir);
$item_count = 0;
foreach($di as $file)
{
$item_count = $this->addItem($file->getPath() . '/' . $file->getFileName());
}
if(0 == $item_count)
throw new Exception("No Items found in {$this->source_dir}");
$this->scanned = true;
$this->post_scan();
}
}
public function addItem($filename)
{
$pos = strrpos($filename, '.');
if(false === $pos)
$file_ext = '';
else
$file_ext = substr($filename, $pos + 1);
switch(strtolower($file_ext))
{
case 'mp3':
// skip 0-length mp3 files. getID3 chokes on them.
if(filesize($filename))
{
// one array per mtime, just in case several MP3s share the same mtime.
$filemtime = filemtime($filename);
$the_item = new MP3_RSS_Item($filename);
$this->unsorted_items[$filemtime][] = $the_item;
if($filemtime > $this->max_mtime)
$this->max_mtime = $filemtime;
}
break;
default:
}
return count($this->unsorted_items);
}
protected function pre_generate()
{
$this->scan();
$this->sort();
// Add helpers here, NOT during scan().
// scan() is also used just to get mtimes to see if we need to regenerate the feed.
foreach($this->helpers as $helper)
foreach($this->items as $the_item)
$the_item->addHelper($helper);
}
protected function sort() {
krsort($this->unsorted_items); // newest first
$this->items = array();
$i = 0;
foreach($this->unsorted_items as $item_list)
{
foreach($item_list as $item)
{
$this->items[$i++] = $item;
if($i >= ITEM_COUNT)
break 2;
}
}
unset($this->unsorted_items);
}
protected function pre_scan() { }
protected function post_scan() { }
}
/**
* Podcast with cached output. The cache file will be created and a file lock
* obtained at object construction time. The lock will be released in the object's
* destructor.
*/
class Cached_Dir_Podcast extends Dir_Podcast
{
protected $temp_dir;
protected $temp_file;
protected $cache_date;
protected $serve_from_cache;
/**
* Constructor
*
* @param string $source_dir
* @param string $temp_dir
*/
public function __construct($source_dir, $temp_dir)
{
$this->temp_dir = $temp_dir;
$safe_source_dir = str_replace(array('/', '\\'), '_', $source_dir);
// something unique, safe, stable and easily identifiable
$this->temp_file = rtrim($temp_dir, '/') . '/' . md5($source_dir) . '_' . $safe_source_dir . '.xml';
parent::__construct($source_dir);
$this->init();
}
/**
* Initialises the cache file
*/
public function init()
{
if($this->isCached()) // this call sets $this->serve_from_cache
{
$cache_date = filemtime($this->temp_file);
if( $cache_date < time() - MIN_CACHE_TIME )
{
$this->scan();
if( $cache_date < $this->max_mtime || $cache_date < filemtime($this->source_dir))
{
$this->uncache();
}
else
{
$this->renew();
}
}
}
}
public function renew()
{
touch($this->temp_file); // renew cache file life expectancy
}
public function uncache()
{
if($this->isCached())
{
unlink($this->temp_file);
$this->serve_from_cache = false;
}
}
public function generate()
{
if($this->serve_from_cache)
{
$output = file_get_contents($this->temp_file); // serve cached copy
}
else
{
$output = parent::generate();
file_put_contents($this->temp_file, $output); // save cached copy
$this->serve_from_cache = true;
}
return $output;
}
public function getLastBuildDate()
{
if(isset($this->cache_date))
return date('r', $this->cache_date);
else
return $this->__call('getLastBuildDate', array());
}
public function isCached()
{
if(!isset($this->serve_from_cache))
$this->serve_from_cache = file_exists($this->temp_file) && filesize($this->temp_file);
return $this->serve_from_cache;
}
}
class Locking_Cached_Dir_Podcast extends Cached_Dir_Podcast
{
protected $file_handle;
public function init()
{
$this->acquireLock();
parent::init();
}
/**
* acquireLock always creates the cache file.
*/
protected function acquireLock()
{
if (!file_exists($this->temp_dir))
{
mkdir($this->temp_dir, 0755, true);
}
$this->file_handle = fopen($this->temp_file, 'a');
if(!flock($this->file_handle, LOCK_EX))