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