Tv.php
[lib.XML_Tv] / Tv.php
1 <?php
2 /* 
3 Usage: 
4
5 make a weekly cronjob (/etc/cron.weekly/filltv) 
6 #!/bin/sh
7 /usr/bin/php /path/to/application/Tv.php /path/to/application/hongkong.ini > /tmp/hongkong.xml
8 /usr/bin/mythfilldatabase --file 1 1 /tmp/hongkong.xml
9
10 make sure the filltv file is chmod +x
11
12
13
14 Quick hack to generate xmltv listings from TVxb style .ini files.
15
16 */
17
18
19 if (!extension_loaded('mbstring')) {
20     dl('mbstring.so');
21 }
22
23 define ('QUOTE', '"');
24 class XML_Tv
25 {
26     var $config; // configuration array.
27     var $date; // date we are fetching
28     var $channels; // details on the channels.
29
30
31     function start($ini)
32     {
33         // load the ini file.
34         require_once 'JSON.php';
35         $j = new Services_JSON();
36         $conf = (array)($j->decode(file_get_contents($ini)));
37         //$conf = (array)json_decode(file_get_contents($ini));
38         //print_r($conf);
39         foreach($conf as $k=>$v) {
40             $conf[$k] = (array)$v;
41         }
42         $this->channels = $conf;
43         $this->config = $conf['global'];
44         unset($this->channels['global']);
45         //print_r($this->channels);
46         
47         $this->date = time();
48         
49         
50         foreach($this->channels as $k=>$v) {
51             
52             for ($i=0;$i< (isset($v['days']) ? $v['days'] : $conf['days']);$i++) {
53                 $this->grabChannel($k,$i);
54                    // break;
55             }
56                 
57             
58             
59             //break;
60         }
61         
62         echo $this->toXML();
63         
64     }
65     
66     function grabChannel($k,$dayoffset) 
67     {
68         $cinfo = $this->channels[$k];
69         
70         //print_r($cinfo);
71        // exit;
72         $date = $this->date + ($dayoffset * 24 * 60 * 60 );
73        
74         $url =  strftime( $cinfo['url'], $date);
75         $this->debug($url );
76         //echo "GET $url\n";
77         $data = @file_get_contents($url);
78         if (empty($data)) {
79             $this->debug("NO  DATA");
80              
81             // something went wrong..
82             return;
83         }
84         
85         $odata = $data;
86         $map = array(
87                 array("0x22", "0x09", "0x0a"),
88                 array('"', "\t", "\n")
89              );
90         
91
92         $hs = $cinfo['htmlstart'] === false ? false  : str_replace($map[0],$map[1],$cinfo['htmlstart']);
93         //echo $hs;
94         $he= str_replace($map[0],$map[1],$cinfo['htmlend']);
95         //echo $he;
96         if ($hs !== false) {
97             list( , $data) = explode($hs,$data);
98         }
99         
100         if (!empty($he)) {
101             list($data,) =  explode($he ,$data);
102         }
103         
104         
105         //$this->debug("DATA:".$data); 
106          
107         $method = 'parse'.$cinfo['htmlparsetype'];
108         
109         $chid = isset($cinfo['id']) ? $cinfo['id'] : $k;
110         // for multiday html layout of atv:
111         if (!empty($cinfo['htmldaysep'])) {
112             $days = explode($cinfo['htmldaysep'], $data);
113             // kludge. = first monday of current week..
114             // loook for... <BR>2007-12-31 Mon
115             $start = preg_match('/<BR>([0-9]{4}-[0-9]{2}-[0-9]{2}) Mon/i', $odata, $matches);
116             $start = $matches[1]; // first monday..
117             
118             $use_cols = 1;
119             foreach($days as $i=>$ddata) {
120                 
121                 
122                 
123                 $cols = explode(',',$cinfo['htmlcols']);
124                 $dn = strtotime($start) + (($i * $use_cols) * 24 * 60 * 60 );
125                 $res =  $this->$method($ddata,$cols,date('Y-m-d',$dn));
126                 if (is_string($res)) {
127                     $start = $res;
128                      $use_cols =0;
129                     continue;
130                 }
131                 $this->schedule[$chid][strtotime($start) + (($i *  $use_cols ) * 24 * 60 * 60 )]  = $res;
132             }
133             return;
134             
135             
136         }
137         
138         $cols = explode(',',$cinfo['htmlcols']);
139         
140         //print_r(array($data,$cols));
141         
142         $this->schedule[$k][$this->date + ($dayoffset * 24 * 60 * 60 )]  = $this->$method($data,$cols);
143         //print_r($this->schedule);
144     }
145     //tvb +???
146     function parseTable($data,$colnames) 
147     {
148         $rows = preg_split('/<tr[^>]*>/i', $data);
149        // print_r($rows);exit;
150         array_shift($rows);
151         
152         
153         foreach($rows as $r) {
154             //print_r($r);
155             $cols = preg_split('/\<td[^>]*\>/i', trim($r));
156             $rdata = array();
157             array_shift($cols);
158             //var_dump(count(array_values($cols)));
159             //print_r($r);
160             //    print_r($cols);exit;
161             
162             foreach($cols as $i=>$c) {
163                 if (count(array_values($cols)) != count(array_values($colnames))) {
164                     continue;
165                 }
166                 if (preg_match('/<table/i', $c)) {
167                     continue;
168                 }
169                 //var_dump($c);
170                 $c = str_ireplace('<br>',' ', $c);
171                 $c = str_ireplace('&nbsp;',' ', $c);
172                 $c = str_replace("\n",' ', $c);
173                 $c = str_replace("\r",' ', $c);
174                 //var_dump($c);
175                 $rdata[$colnames[$i]] = trim(strip_tags($c));
176             }
177             
178           //  print_r($rdata);
179             if (count(array_values($rdata)) != count(array_values($colnames))) {
180                 continue;
181             }
182            // print_R($rdata);
183             $ret[] = $rdata;
184         }
185         
186         $this->debug(print_r($ret,true));
187         
188         return $ret;
189         
190     
191     }
192     
193     function parseJade($data, $colnames)
194     {
195         
196         $rows = preg_split('#</li>#i', $data);
197         //print_r($rows);
198         $ret = array();
199         foreach($rows as $r) {
200             $r = str_ireplace('&nbsp;',' ', $r);
201             $rdata = array();
202             
203             list($time,$r) = explode('</span>', $r, 2);
204             
205             $rdata['hour'] = trim(strip_tags($time));
206             if (!strlen($rdata['hour'])) {
207                 continue;
208                }
209             //list($title,$r) = explode('</em>', $r, 2);
210             list($title,$r) = explode('</p>', $r, 2);
211             $rdata['description'] = trim(strip_tags($title));
212             $rdata['description2'] = trim(strip_tags($r));
213             $rdata['day'] = $day;
214             $ret[] = $rdata;
215         }
216         //print_R($ret);
217        return $ret;
218     }
219     
220     
221     function parseatv($data,$colnames, $day) 
222     {
223         
224         // if it's a day row..
225         
226         if (preg_match('/<div/', trim($data))) {
227             preg_match('/<BR>([0-9]{4}-[0-9]{2}-[0-9]{2})/i', $data, $matches);
228              return $matches[1];
229             
230         }
231         $rows = preg_split('/<tr[^>]*>/i', $data);
232         //$this->debug(print_r($rows,true));
233     //return; 
234         array_shift($rows);
235         
236         
237         $day = false;
238         foreach($rows as $r) {
239             //print_r($r);
240             $cols = preg_split('/<td[^>]*>/i', $r);
241             $rdata = array();
242             
243             
244             //PRINT_r($cols);
245             $c= $cols[2];
246              //var_dump($c);
247             // look for time..
248             if (!preg_match('/^[0-9]+:[0-9]+/', $c)) {
249                 continue;
250             }
251             //$this->debug("GOT HOUR: $c");
252             $rdata['hour'] = trim(array_shift(explode('<', $c)));  
253             $c =  $cols[3];
254             
255             $kv = preg_split('/<br>/',$c);
256             
257             $c = $kv[0];
258             $c = str_ireplace('<br>',' ', $c);
259             $c = str_ireplace('&nbsp;',' ', $c);
260             $c = str_replace("\n",' ', $c);
261             $c = str_replace("\r",' ', $c);
262             $c = preg_replace('/\<[^>]+\>/', ' ', $c);
263             $rdata['description2']  = trim($c); 
264             
265             
266             
267             $c = $kv[1];
268             $c = str_ireplace('<br>',' ', $c);
269             $c = str_ireplace('&nbsp;',' ', $c);
270             $c = str_replace("\n",' ', $c);
271             $c = str_replace("\r",' ', $c);
272             $c = preg_replace('/\<[^>]+\>/', ' ', $c);
273             $rdata['description']  = trim($c); 
274             
275             
276             $rdata['day'] = $day;
277             
278             
279             //print_R($rdata);
280             $ret[] = $rdata;
281         }
282         //print_r($ret); exit;
283         return $ret;
284         
285     
286     }
287     
288     
289 /*
290     function parseTableCells($data,$colnames, $day) 
291     {
292         $rows = preg_split('/<tr[^>]*>/i', $data);
293         //$this->debug(print_r($rows,true));
294         //exit;
295         //exit;
296         array_shift($rows);
297         
298         
299         $day = false;
300         foreach($rows as $r) {
301             //print_r($r);
302             $cols = preg_split('/<td[^>]*>/i', $r);
303             $rdata = array();
304             $c= $cols[1];
305              //var_dump($c);
306             // look for time..
307             if (!preg_match('/^[0-9]+:[0-9]+\s/', $c)) {
308                 continue;
309             }
310             
311             $c = str_ireplace('<br>',' ', $c);
312             $c = str_ireplace('&nbsp;',' ', $c);
313             $c = str_replace("\n",' ', $c);
314             $c = str_replace("\r",' ', $c);
315             
316             
317             $c = preg_replace('/\<[^>]+\>/', ' ', $c);
318             $c = trim($c); 
319             $kv = preg_split("/\s+/", $c, 2);
320             
321             $rdata[$colnames[0]] = trim($kv[0]);
322             $rdata[$colnames[1]] = trim($kv[1]);
323             
324             
325             //print_r($kv);
326             if (count(array_values($rdata)) != count(array_values($colnames))) {
327                 continue;
328             }
329             $rdata['day'] = $day;
330             $ret[] = $rdata;
331         }
332         //print_r($ret);
333         return $ret;
334         
335     
336     }
337 */
338     /*
339     
340        <tv generator-info-name="tv_grab_uk">
341           <channel id="bbc2.bbc.co.uk">
342             <display-name lang="en">BBC2</display-name>
343           </channel>
344           <channel id="channel4.com">
345             <display-name lang="en">Channel 4</display-name>
346           </channel>
347         
348           <programme channel="bbc2.bbc.co.uk" start="20010829000500 +0100">
349             <title lang="en">The Phil Silvers Show</title>
350             <desc lang="en">
351               Bilko claims he's had a close encounter with an alien in order
352               to be given some compassionate leave so he can visit an old
353               flame in New York.
354             </desc>
355           </programme>
356         
357           <programme channel="channel4.com" start="20010829095500 +0100">
358             <title lang="en">King of the Hill</title>
359             <sub-title lang="en">Meet the Propaniacs</sub-title>
360             <desc lang="en">
361                Bobby tours with a comedy troupe who specialize in
362                propane-related mirth.
363             </desc>
364             <credits>
365               <actor>Mike Judge</actor>
366               <actor>Lane Smith</actor>
367             </credits>
368             <category lang="en">animation</category>
369           </programme>
370         </tv>
371     */
372     
373     function toXml()
374     {
375     
376         //print_r($this->schedule);
377         $doc = new DomDocument('1.0', 'UTF-8');
378         $tv = $doc->createElement('tv');
379         $tv->setAttribute( 'generator-info-name','akpear_xml_tv');
380         $doc->appendChild($tv);
381         
382         
383         //$out = '<'.'?xml version="1.0" encoding="UTF-8"?.'>'."\n" .
384          //       '<!DOCTYPE tv SYSTEM "xmltv.dtd">'."\n" ."\n" .
385           ///      '<tv generator-info-name="akpear_xml_tv">'."\n";
386           $donec = array();
387         foreach($this->channels as $k => $v) {
388             // dont dupe?!
389             $chid = isset($v['id']) ? $v['id'] : $k;
390             if (isset($donec[$chid])) {
391                 continue;
392             }
393             $donec[$chid] = true;
394             $ch = $doc->createElement('channel');
395             $ch->setAttribute('id', $chid);
396             $disp = $doc->createElement('display-name');
397             $disp->setAttribute('lang', 'en');
398             $disp->appendChild($doc->createTextNode($v['name']));
399             $ch->appendChild($disp);
400             $tv->appendChild($ch);
401             //$out .=  
402             //    '<channel id="'. $k .'">
403             //        <display-name lang="en">'. $v['name'] .'</display-name>
404             //    </channel>'."\n";
405         }
406         //print_r($this->schedule);
407         foreach($this->schedule as $chan => $scheds) {
408             //print_r($sched);
409             foreach($scheds as $day => $sched) {
410                 $hoffset = 0;
411                 $last = -1;
412                 
413                 if (empty($sched)) {
414                     continue;
415                 }
416                 foreach($sched as $item) {
417                     $item['day'] = $day;
418                     
419                     $bits = explode(':', $item['hour']);
420                     if ($bits[0] < $last) {
421                         $hoffset +=12;
422                     }
423                     $last = $bits[0];
424                     
425                     //var_dump($bits[0] + $hoffset);
426                     $start = mktime(/*hmsmdy  */
427                             $bits[0] + $hoffset,
428                             $bits[1],
429                             0,
430                             date('m', $day),
431                             date('d', $day),
432                             date('Y', $day)
433                             );
434                     if ($start < strtotime('NOW - 1 DAY')) {
435                         continue;
436                     }
437                     $this->debug(print_r($item, true));
438                     $start_str = date('YmdHis',$start) . ' ' . $this->config['gmtoffset'];
439                     //var_dump($start_str);
440                     //var_dump($this->channels);
441                     $description =   iconv($this->channels[$chan]['encoding'], 'UTF-8',$item['description'] . 
442                                 (isset($item['description2']) ? ('   ' . $item['description2']) : '')); 
443                    
444                     $this->debug(date("Y-m-d H:i - "). $description); 
445                    
446                    
447                     $pg = $doc->createElement('programme');
448                     
449                     $pg->setAttribute('channel', $chan);
450                     $pg->setAttribute('start', $start_str);
451                     
452                     $title = $doc->createElement('title');
453                     $title->setAttribute('lang', 'zh');
454                     $title->appendChild($doc->createTextNode($this->toTitle($description,$chan)));
455                     $pg->appendChild($title);
456                     
457                     $title = $doc->createElement('desc');
458                     $title->setAttribute('lang', 'zh');
459                     $title->appendChild($doc->createTextNode($description));
460                     $pg->appendChild($title);
461             
462                     $tv->appendChild($pg);
463                     //$out.= '<programme channel="'.$chan. '" start="'.$start_str. '">
464                     //    <title lang="zh">'. $this->toTitle($description) .'</title>
465                     //      <desc lang="zh">'. $description .'</desc>
466                     //    </programme>'."\n";
467                 }
468             }
469         }
470         
471         $doc->formatOutput = true;
472         
473         //$out .= "</tv>\n";
474         
475         return $doc->saveXML();
476     
477     }
478   
479     function toTitle($description, $chan)  
480     {
481         // remove sponsor message.
482         $title_pre = '';
483         list($title, $fuldesc) = explode("&gt;&gt;",$description);
484         
485         
486         
487         if (preg_match('/Followed\s*By/i', $title)) {
488             $bits = preg_split('/Followed\s*By/i', $title);
489             $title_pre  = $bits[0]  . ' Followed By ';
490             $title = $bits[1];
491         }
492         $title = preg_replace('#countdown to[a-z0-9 ]+#i', '' , $title); # NICAM Language   
493         $title = preg_replace('#^(solar x|Samsung Digital)\s*#i', '' , $title); # known sponsors..
494         
495         $title = preg_replace('#[a-z0-9 ]+(presents|special|blockbuster|movie of the month|showtime)\s*:\s*#i', '', $title);
496         
497         $title = preg_replace('#\([a-z]+/[a-z]+\s*(|bilingual)\)#i', '' , $title); # NICAM Language 
498         $title = preg_replace('#\(live\)#i', '' , $title);            # live
499         $title = preg_replace('#\((s|c|l|e|cs|es|ecs|can|ce)[*]*\)#i', '' , $title);            # Subtitle
500         $title = preg_replace('#\((pg\d*\w*)\)#i', '' , $title);         # Adult
501         $title = preg_replace('#\(r\)#i', '' , $title);         # Repeated
502         $title = trim($title, '/');
503         $title = trim($title);
504         
505         $ret = $title_pre . $title;
506         
507       //  if (!strlen($ret)) {
508        //     die("got $description : nothing to return");
509         //   }
510         if (in_array($chan, array('tvbpearl.hk', 'english.atvworld.hk'))) {
511             $enonly = preg_replace('#^[^a-z0-9]+#i', '', $title);
512             if (strlen($enonly) > 10) {
513                 $title = $enonly;
514             }
515         }
516         
517         
518         return $title_pre . $title;
519     }
520  
521     
522     
523     function debug($str)
524     {
525         if (empty($this->config['debug'])) {
526              return;
527            }
528         echo $str."\n";
529        }
530     
531     
532 }
533
534 $x = new XML_Tv;
535 //print_r($_SERVER);
536
537 $x->start($_SERVER['argv'][1]);