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