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         
233         $this->debug($day);
234         //$this->debug(print_r($rows,true));
235     //return; 
236         array_shift($rows);
237         
238         
239         $day = false;
240         foreach($rows as $r) {
241             //print_r($r);
242             $cols = preg_split('/<td[^>]*>/i', $r);
243             $rdata = array();
244             
245             
246             //PRINT_r($cols);
247             $c= $cols[2];
248              //var_dump($c);
249             // look for time..
250             if (!preg_match('/^[0-9]+:[0-9]+/', $c)) {
251                 continue;
252             }
253             //$this->debug("GOT HOUR: $c");
254             $rdata['hour'] = trim(array_shift(explode('<', $c)));  
255             $c =  $cols[3];
256             
257             $kv = preg_split('/<br>/',$c);
258             
259             $c = $kv[0];
260             $c = str_ireplace('<br>',' ', $c);
261             $c = str_ireplace('&nbsp;',' ', $c);
262             $c = str_replace("\n",' ', $c);
263             $c = str_replace("\r",' ', $c);
264             $c = preg_replace('/\<[^>]+\>/', ' ', $c);
265             $rdata['description2']  = trim($c); 
266             
267             
268             
269             $c = $kv[1];
270             $c = str_ireplace('<br>',' ', $c);
271             $c = str_ireplace('&nbsp;',' ', $c);
272             $c = str_replace("\n",' ', $c);
273             $c = str_replace("\r",' ', $c);
274             $c = preg_replace('/\<[^>]+\>/', ' ', $c);
275             $rdata['description']  = trim($c); 
276             
277             
278             $rdata['day'] = $day;
279             
280             
281             //print_R($rdata);
282             $ret[] = $rdata;
283         }
284         //print_r($ret); exit;
285         return $ret;
286         
287     
288     }
289     
290     
291 /*
292     function parseTableCells($data,$colnames, $day) 
293     {
294         $rows = preg_split('/<tr[^>]*>/i', $data);
295         //$this->debug(print_r($rows,true));
296         //exit;
297         //exit;
298         array_shift($rows);
299         
300         
301         $day = false;
302         foreach($rows as $r) {
303             //print_r($r);
304             $cols = preg_split('/<td[^>]*>/i', $r);
305             $rdata = array();
306             $c= $cols[1];
307              //var_dump($c);
308             // look for time..
309             if (!preg_match('/^[0-9]+:[0-9]+\s/', $c)) {
310                 continue;
311             }
312             
313             $c = str_ireplace('<br>',' ', $c);
314             $c = str_ireplace('&nbsp;',' ', $c);
315             $c = str_replace("\n",' ', $c);
316             $c = str_replace("\r",' ', $c);
317             
318             
319             $c = preg_replace('/\<[^>]+\>/', ' ', $c);
320             $c = trim($c); 
321             $kv = preg_split("/\s+/", $c, 2);
322             
323             $rdata[$colnames[0]] = trim($kv[0]);
324             $rdata[$colnames[1]] = trim($kv[1]);
325             
326             
327             //print_r($kv);
328             if (count(array_values($rdata)) != count(array_values($colnames))) {
329                 continue;
330             }
331             $rdata['day'] = $day;
332             $ret[] = $rdata;
333         }
334         //print_r($ret);
335         return $ret;
336         
337     
338     }
339 */
340     /*
341     
342        <tv generator-info-name="tv_grab_uk">
343           <channel id="bbc2.bbc.co.uk">
344             <display-name lang="en">BBC2</display-name>
345           </channel>
346           <channel id="channel4.com">
347             <display-name lang="en">Channel 4</display-name>
348           </channel>
349         
350           <programme channel="bbc2.bbc.co.uk" start="20010829000500 +0100">
351             <title lang="en">The Phil Silvers Show</title>
352             <desc lang="en">
353               Bilko claims he's had a close encounter with an alien in order
354               to be given some compassionate leave so he can visit an old
355               flame in New York.
356             </desc>
357           </programme>
358         
359           <programme channel="channel4.com" start="20010829095500 +0100">
360             <title lang="en">King of the Hill</title>
361             <sub-title lang="en">Meet the Propaniacs</sub-title>
362             <desc lang="en">
363                Bobby tours with a comedy troupe who specialize in
364                propane-related mirth.
365             </desc>
366             <credits>
367               <actor>Mike Judge</actor>
368               <actor>Lane Smith</actor>
369             </credits>
370             <category lang="en">animation</category>
371           </programme>
372         </tv>
373     */
374     
375     function toXml()
376     {
377     
378         //print_r($this->schedule);
379         $doc = new DomDocument('1.0', 'UTF-8');
380         $tv = $doc->createElement('tv');
381         $tv->setAttribute( 'generator-info-name','akpear_xml_tv');
382         $doc->appendChild($tv);
383         
384         
385         //$out = '<'.'?xml version="1.0" encoding="UTF-8"?.'>'."\n" .
386          //       '<!DOCTYPE tv SYSTEM "xmltv.dtd">'."\n" ."\n" .
387           ///      '<tv generator-info-name="akpear_xml_tv">'."\n";
388           $donec = array();
389         foreach($this->channels as $k => $v) {
390             // dont dupe?!
391             $chid = isset($v['id']) ? $v['id'] : $k;
392             if (isset($donec[$chid])) {
393                 continue;
394             }
395             $donec[$chid] = true;
396             $ch = $doc->createElement('channel');
397             $ch->setAttribute('id', $chid);
398             $disp = $doc->createElement('display-name');
399             $disp->setAttribute('lang', 'en');
400             $disp->appendChild($doc->createTextNode($v['name']));
401             $ch->appendChild($disp);
402             $tv->appendChild($ch);
403             //$out .=  
404             //    '<channel id="'. $k .'">
405             //        <display-name lang="en">'. $v['name'] .'</display-name>
406             //    </channel>'."\n";
407         }
408         //print_r($this->schedule);
409         foreach($this->schedule as $chan => $scheds) {
410             //print_r($sched);
411             foreach($scheds as $day => $sched) {
412                 $hoffset = 0;
413                 $last = -1;
414                 
415                 if (empty($sched)) {
416                     continue;
417                 }
418                 foreach($sched as $item) {
419                     $item['day'] = $day;
420                     
421                     $bits = explode(':', $item['hour']);
422                     if ($bits[0] < $last) {
423                         $hoffset +=12;
424                     }
425                     $last = $bits[0];
426                     
427                     //var_dump($bits[0] + $hoffset);
428                     $start = mktime(/*hmsmdy  */
429                             $bits[0] + $hoffset,
430                             $bits[1],
431                             0,
432                             date('m', $day),
433                             date('d', $day),
434                             date('Y', $day)
435                             );
436                     if ($start < strtotime(date("Y-m-d 00:00:00", strtotime('NOW - 1 DAY')))) {
437                         continue;
438                     }
439                     $item['hoffset'] = $hoffset;
440                     $item['hoffset_ar'] = $bits;
441                     
442                     $this->debug(print_r($item, true));
443                     $start_str = date('YmdHis',$start) . ' ' . $this->config['gmtoffset'];
444                     //var_dump($start_str);
445                     //var_dump($this->channels);
446                     $description =   iconv($this->channels[$chan]['encoding'], 'UTF-8',$item['description'] . 
447                                 (isset($item['description2']) ? ('   ' . $item['description2']) : '')); 
448                    
449                     $this->debug(date("Y-m-d H:i - ", $start). $description); 
450                    
451                    
452                     $pg = $doc->createElement('programme');
453                     
454                     $pg->setAttribute('channel', $chan);
455                     $pg->setAttribute('start', $start_str);
456                     
457                     $title = $doc->createElement('title');
458                     $title->setAttribute('lang', 'zh');
459                     $title->appendChild($doc->createTextNode($this->toTitle($description,$chan)));
460                     $pg->appendChild($title);
461                     
462                     $title = $doc->createElement('desc');
463                     $title->setAttribute('lang', 'zh');
464                     $title->appendChild($doc->createTextNode($description));
465                     $pg->appendChild($title);
466             
467                     $tv->appendChild($pg);
468                     //$out.= '<programme channel="'.$chan. '" start="'.$start_str. '">
469                     //    <title lang="zh">'. $this->toTitle($description) .'</title>
470                     //      <desc lang="zh">'. $description .'</desc>
471                     //    </programme>'."\n";
472                 }
473             }
474         }
475         
476         $doc->formatOutput = true;
477         
478         //$out .= "</tv>\n";
479         
480         return $doc->saveXML();
481     
482     }
483   
484     function toTitle($description, $chan)  
485     {
486         // remove sponsor message.
487         $title_pre = '';
488         list($title, $fuldesc) = explode("&gt;&gt;",$description);
489         
490         
491         
492         if (preg_match('/Followed\s*By/i', $title)) {
493             $bits = preg_split('/Followed\s*By/i', $title);
494             $title_pre  = $bits[0]  . ' Followed By ';
495             $title = $bits[1];
496         }
497         $title = preg_replace('#countdown to[a-z0-9 ]+#i', '' , $title); # NICAM Language   
498         $title = preg_replace('#^(solar x|Samsung Digital)\s*#i', '' , $title); # known sponsors..
499         
500         $title = preg_replace('#[a-z0-9 ]+(presents|special|blockbuster|movie of the month|showtime)\s*:\s*#i', '', $title);
501         
502         $title = preg_replace('#\([a-z]+/[a-z]+\s*(|bilingual)\)#i', '' , $title); # NICAM Language 
503         $title = preg_replace('#\(live\)#i', '' , $title);            # live
504         $title = preg_replace('#\((s|c|l|e|cs|es|ecs|can|ce)[*]*\)#i', '' , $title);            # Subtitle
505         $title = preg_replace('#\((pg\d*\w*)\)#i', '' , $title);         # Adult
506         $title = preg_replace('#\(r\)#i', '' , $title);         # Repeated
507         $title = trim($title, '/');
508         $title = trim($title);
509         
510         $ret = $title_pre . $title;
511         
512       //  if (!strlen($ret)) {
513        //     die("got $description : nothing to return");
514         //   }
515         if (in_array($chan, array('tvbpearl.hk', 'english.atvworld.hk'))) {
516             $enonly = preg_replace('#^[^a-z0-9]+#i', '', $title);
517             if (strlen($enonly) > 10) {
518                 $title = $enonly;
519             }
520         }
521         
522         
523         return $title_pre . $title;
524     }
525  
526     
527     
528     function debug($str)
529     {
530         if (empty($this->config['debug'])) {
531              return;
532            }
533         echo $str."\n";
534        }
535     
536     
537 }
538
539 $x = new XML_Tv;
540 //print_r($_SERVER);
541
542 $x->start($_SERVER['argv'][1]);