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