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