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