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