1756ed5ad426c501568ba5f60cf90859c3017343
[noxon-gateway.git] / src / podcasts.php
1 <?php
2 function sendPodcast($path)
3 {
4     global $varDir, $host1;
5
6     $file = urldecode($path);
7     if (strpos($file, '..') !== false) {
8         sendMessage('No');
9         return;
10     }
11
12     $fullPath = $varDir . $path;
13     if (!file_exists($fullPath)) {
14         return sendMessage('File does not exist: ' . $path);
15     }
16
17     $url = trim(file_get_contents($fullPath));
18
19     $cacheFile = '/tmp/podcast-' . md5($path) . '.xml';
20     downloadIfNewer($url, $cacheFile);
21     
22     $sx = simplexml_load_file($cacheFile);
23     $listItems = array();
24     addPreviousItem($listItems, $path);
25
26     foreach ($sx->channel->item as $item) {
27         $title = (string) $item->title;
28         $desc = (string) $item->description;
29         $url = $item->enclosure['url'];
30
31         $listItems[] = '<Item>'
32             . '<ItemType>ShowEpisode</ItemType>'
33             . '<ShowEpisodeName>' . utf8_decode(htmlspecialchars($title)) . '</ShowEpisodeName>'
34             . '<ShowEpisodeURL>' . $host1 . 'play-url?url=' . urlencode($url) . '</ShowEpisodeURL>'
35             . '<ShowDesc>' . utf8_decode(htmlspecialchars($desc)) . '</ShowDesc>'
36             . '<ShowMime>MP3</ShowMime>' 
37             . '</Item>';
38     }
39     sendListItems($listItems);
40 }
41
42
43 function downloadIfNewer($url, $file)
44 {
45     $lastModified = 0;
46     if (file_exists($file)) {
47         $lastModified = filemtime($file);
48     }
49
50     $ctx = stream_context_create(
51         array(
52             'http' => array(
53                 'header' => 'If-Modified-Since: ' . date('r', $lastModified)
54             )
55         )
56     );
57     $content = file_get_contents($url, false, $ctx);
58     //unfortunately, redirects require manual parsing of this array
59     for ($n = count($http_response_header) - 1; $n >= 0; --$n) {
60         if (substr($http_response_header[$n], 0, 5) == 'HTTP/') {
61             list(, $code) = explode(' ', $http_response_header[$n]);
62             break;
63         }
64     }
65     if ($code == 200) {
66         file_put_contents($file, $content);
67     }
68 }
69
70 ?>