68d133ce057f4dd34e581b39b852689bc7d7978d
[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[] = getEpisodeItem(
32             $title,
33             $host1 . 'play-url?url=' . urlencode($url),
34             $desc,
35             'MP3'
36         );
37     }
38     sendListItems($listItems);
39 }
40
41
42 function downloadIfNewer($url, $file)
43 {
44     $lastModified = 0;
45     if (file_exists($file)) {
46         $lastModified = filemtime($file);
47     }
48
49     $ctx = stream_context_create(
50         array(
51             'http' => array(
52                 'header' => 'If-Modified-Since: ' . date('r', $lastModified)
53             )
54         )
55     );
56     $content = file_get_contents($url, false, $ctx);
57     //unfortunately, redirects require manual parsing of this array
58     for ($n = count($http_response_header) - 1; $n >= 0; --$n) {
59         if (substr($http_response_header[$n], 0, 5) == 'HTTP/') {
60             list(, $code) = explode(' ', $http_response_header[$n]);
61             break;
62         }
63     }
64     if ($code == 200) {
65         file_put_contents($file, $content);
66     }
67 }
68
69 ?>