summaryrefslogtreecommitdiff
path: root/lib/XXV/MODULES/EPG.pm
blob: b3be04cd5c7d918ac175e35d46f0ba7dfabaaa18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
package XXV::MODULES::EPG;
use strict;

use Tools;
use File::Basename;

# This module method must exist for XXV
# ------------------
sub module {
# ------------------
    my $self = shift || return error('No object defined!');
    my $args = {
        Name => 'EPG',
        Prereq => {
            'Date::Manip' => 'date manipulation routines',
            'Time::Local' => 'efficiently compute time from local and GMT time ',
        },
        Description => gettext('This module reads new EPG data and saves it to the database.'),
        Status => sub{ $self->status(@_) },
        Preferences => {
            epgimages => {
                description => gettext('Location of additional EPG images.'),
                default     => '/var/cache/vdr/epgimages',
                type        => 'dir',
            },
            interval => {
                description => gettext('How often EPG data are to be analyzed (in seconds)'),
                default     => 60 * 60,
                type        => 'integer',
                required    => gettext('This is required!'),
            },
            periods => {
                description => gettext("Preferred program times. (eg. 12:00, 18:00)"),
                default     => '12:00,18:00,20:15,22:00',
                type        => 'string',
                required    => gettext('This is required!'),
                level       => 'guest'
            },
            timeframe => {
                description => gettext("How much hours to display in schema"),
                default     => 2,
                type        => 'integer',
                required    => gettext('This is required!'),
                level       => 'guest'
            },
        },
        Commands => {
            search => {
                description => gettext('Search within EPG data'),
                short       => 's',
                callback    => sub{ $self->search(@_) },
            },
            program => {
                description => gettext("List program for channel 'channel name'"),
                short       => 'p',
                callback    => sub{ $self->program(@_) },
            },
            display => {
                description => gettext("Show program 'eventid'"),
                short       => 'd',
                callback    => sub{ $self->display(@_) },
            },
            now => {
                description => gettext('Display events currently showing.'),
                short       => 'n',
                callback    => sub{ $self->runningNow(@_) },
            },
            next => {
                description => gettext('Display events showing next.'),
                short       => 'nx',
                callback    => sub{ $self->runningNext(@_) },
            },
            schema => {
                description => gettext('Display events in a schematic way'),
                short       => 'sch',
                callback    => sub{ $self->schema(@_) },
            },
            erestart => {
                description => gettext('Update EPG data.'),
                short       => 'er',
                callback    => sub{
                    my $console = shift || return error('No console defined!');

                    debug sprintf('Start reload EPG data%s',
                        ( $console->{USER} && $console->{USER}->{Name} ? sprintf(' from user: %s', $console->{USER}->{Name}) : "" )
                        );

                    $self->startReadEpgData($console);
                },
                Level       => 'admin',
            },
            erun => {
                description => gettext('Display the current program running in the VDR'),
                short       => 'en',
                callback    => sub{ $self->NowOnChannel(@_) },
                Level       => 'user',
                DenyClass   => 'remote',
            },
            conflict => {
                hidden      => 'yes',
                callback    => sub{ $self->checkOnTimer(@_) },
            },
            edescription => {
                hidden      => 'yes',
                short       => 'ed',
                callback    => sub { $self->getDescription(@_) },
            },
            esuggest => {
                hidden      => 'yes',
                callback    => sub{ $self->suggest(@_) },
            },
            eimage => {
                hidden      => 'yes',
                short       => 'ei',
                callback    => sub{ $self->image(@_) },
                binary      => 'cache'
            },
            opensearch => {
                hidden      => 'yes',
                binary      => 'cache',
                callback    => sub{ $self->opensearch(@_) }
            },

        },
    };
    return $args;
}

# ------------------
sub status {
# ------------------
    my $self = shift || return error('No object defined!');
    my $lastReportTime = shift || 0;

    my $total = 0;
    my $newEntrys = 0;

    {
        my $sth = $self->{dbh}->prepare("SELECT SQL_CACHE count(*) as count from EPG");
        if(!$sth->execute())
        {
            error sprintf("Couldn't execute query: %s.",$sth->errstr);
        } else {
            my $erg = $sth->fetchrow_hashref();
            $total = $erg->{count} if($erg && $erg->{count});
        }
    }

    {
        my $sth = $self->{dbh}->prepare("SELECT SQL_CACHE count(*) as count from EPG where UNIX_TIMESTAMP(addtime) > ?");
        if(!$sth->execute($lastReportTime))
        {
            error sprintf("Couldn't execute query: %s.",$sth->errstr);
        } else {
            my $erg = $sth->fetchrow_hashref();
            $newEntrys = $erg->{count} if($erg && $erg->{count});
        }
    }

    return {
        message => sprintf(gettext('EPG table contains %d entries and since the last login on %s %d new entries.'),
            $total, datum($lastReportTime), $newEntrys),
        complete => $total
    };
}

# ------------------
sub new {
# ------------------
    my($class, %attr) = @_;
    my $self = {};
    bless($self, $class);

    $self->{charset} = delete $attr{'-charset'};
    if($self->{charset} eq 'UTF-8'){
      eval 'use utf8';
    }

    # paths
    $self->{paths} = delete $attr{'-paths'};

    # who am I
    $self->{MOD} = $self->module;

    # all configvalues to $self without parents (important for ConfigModule)
    map {
        $self->{$_} = $attr{'-config'}->{$self->{MOD}->{Name}}->{$_};
        $self->{$_} = $self->{MOD}->{Preferences}->{$_}->{default} unless($self->{$_});
    } keys %{$self->{MOD}->{Preferences}};

    # Try to use the Requirments
    map {
        eval "use $_";
        if($@) {
          my $m = (split(/ /, $_))[0];
          return panic("\nCouldn't load perl module: $m\nPlease install this module on your system:\nperl -MCPAN -e 'install $m'");
        }
    } keys %{$self->{MOD}->{Prereq}};

    # read the DB Handle
    $self->{dbh} = delete $attr{'-dbh'};

    # The Initprocess
    $self->_init or return error('Problem to initialize modul!');

    return $self;
}

# ------------------
sub _init {
# ------------------
    my $self = shift || return error('No object defined!');

    unless($self->{dbh}) {
      panic("Session to database is'nt connected");
      return 0;
    }

    my $version = 33; # Must be increment if rows of table changed
    # this tables hasen't handmade user data,
    # therefore old table could dropped if updated rows

    # Look for table or create this table
    foreach my $table (qw/EPG OLDEPG TEMPEPG/) {

      # remove old table, if updated version
      if(!tableUpdated($self->{dbh},$table,$version,1)) {
        return 0;
      }

      $self->{dbh}->do(qq|
          CREATE TABLE IF NOT EXISTS $table (
              eventid int unsigned NOT NULL default '0',
              vid int unsigned NOT NULL,
              title text NOT NULL default '',
              subtitle text default '',
              description text,
              channel_id varchar(32) NOT NULL default '',
              starttime datetime NOT NULL default '0000-00-00 00:00:00',
              duration int NOT NULL default '0',
              tableid tinyint(4) default 0,
              image text default '',
              version tinyint default 0,
              video varchar(32) default '',
              audio varchar(128) default '',
              content varchar(32) default '',
              rating tinyint default 0,
              addtime datetime NOT NULL default '0000-00-00 00:00:00',
              vpstime datetime default '0000-00-00 00:00:00',
              PRIMARY KEY (vid,eventid),
              INDEX (starttime),
              INDEX (channel_id)
            ) COMMENT = '$version'
        |);
    }

    $self->{before_updated} = [];
    $self->{after_updated} = [];

    # Repair later Data ...
    main::after(sub{
        $self->{svdrp} = main::getModule('SVDRP');
        unless($self->{svdrp}) {
           panic ("Couldn't get modul SVDRP");
           return 0;
        }

        $self->startReadEpgData();

        # Restart interval every x hours
        Event->timer(
            interval => $self->{interval},
            prio => 6,  # -1 very hard ... 6 very low
            cb => sub{
                lg sprintf('The read on epg data is restarted!');
                $self->startReadEpgData();
            },
        );
        return 1;
    }, "EPG: Start read epg data and repair ...", 40);

    return 1;
}

# ------------------
sub startReadEpgData {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift;
    my $config = shift;

    debug sprintf('The read on epg data start now!');

    my $waiter;
    if(ref $console && $console->typ eq 'HTML') {
        $waiter = $console->wait(gettext("Read EPG data ..."),0,1000,'no');
    }
    my $updated = 0;
    $self->_before_updated($console,$waiter);
  
    $self->moveOldEPGEntrys();

    # Read data over SVDRP
    my $hostlist = $self->{svdrp}->list_hosts();
    # read from svdrp
    foreach my $vid (@$hostlist) {
      my ($vdata,$error) = $self->{svdrp}->command('LSTE',$vid);
      unless($error) {
        map { 
          $_ =~ s/^\d{3}.//;
        # $_ =~ s/[\r|\n]$//;
        } @$vdata;


        # Adjust waiter max value now.
        $waiter->max(scalar @$vdata)
            if(ref $console && ref $waiter);

        # Read file row by row
        $updated |= $self->compareEpgData($vdata,$vid,$console,$waiter);
      }
    }
    $self->deleteDoubleEPGEntrys();

    $self->_updated($console,$waiter) if($updated);

    # last call of waiter
    $waiter->end() if(ref $waiter);

    if(ref $console) {
        $console->start() if(ref $waiter);
        con_msg($console, sprintf(gettext("%d events in database updated."), $updated));

        $console->redirect({url => '?cmd=now', wait => 1})
            if($console->typ eq 'HTML');
    }
}

# Routine um Callbacks zu registrieren die vor dem Aktualisieren der EPG Daten 
# ausgeführt werden
# ------------------
sub before_updated {
# ------------------
    my $self = shift || return error('No object defined!');
    my $cb = shift || return error('No callback defined!');
    my $log = shift || 0;

    push(@{$self->{before_updated}}, [$cb, $log]);
}

# Ausführen der Registrierten Callbacks vor dem Aktualisieren der EPG Daten
# ------------------
sub _before_updated {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift;
    my $waiter = shift;

    foreach my $CB (@{$self->{before_updated}}) {
        next unless(ref $CB eq 'ARRAY');
        lg $CB->[1]
            if($CB->[1]);
        &{$CB->[0]}($console,$waiter)
            if(ref $CB->[0] eq 'CODE');
    }
}

# Routine um Callbacks zu registrieren die nach dem Aktualisieren der EPG Daten 
# ausgeführt werden
# ------------------
sub updated {
# ------------------
    my $self = shift || return error('No object defined!');
    my $cb = shift || return error('No callback defined!');
    my $log = shift || 0;

    push(@{$self->{after_updated}}, [$cb, $log]);
}

# Ausführen der Registrierten Callbacks nach dem Aktualisieren der EPG Daten
# ------------------
sub _updated {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift;
    my $waiter = shift;

    foreach my $CB (@{$self->{after_updated}}) {
        next unless(ref $CB eq 'ARRAY');
        lg $CB->[1]
            if($CB->[1]);
        &{$CB->[0]}($console,$waiter)
            if(ref $CB->[0] eq 'CODE');
    }
}
# This Routine will compare data from epg.data
# and EPG Database row by row
# ------------------
sub compareEpgData {
# ------------------
    my $self = shift || return error('No object defined!');
    my $vdata = shift || return error('No data defined!');
    my $vid = shift;
    my $console = shift;
    my $waiter = shift;

    my $changedData = 0;
    my $updatedData = 0;
    my $deleteData = 0;

    # Second - read data
    my $count = 0;

    my $vdrData;
    my $channel;
    my $channelname;
    my $hostname = $self->{svdrp}->hostname($vid);

    while($count < scalar $vdata) {
      ($vdrData,$channel,$channelname,$count) = $self->readEpgData($vid,$vdata,$count);
      last if(not $channel);

      $waiter->next($count,undef, sprintf(gettext("Analyze channel '%s'"), $channelname))
        if(ref $waiter);

      # First - read database
      my $sql = qq|SELECT SQL_CACHE eventid, title, subtitle, length(description) as ldescription, duration, UNIX_TIMESTAMP(starttime) as starttime, UNIX_TIMESTAMP(vpstime) as vpstime, video, audio, content from EPG where vid = ? and channel_id = ? |;
      my $sth = $self->{dbh}->prepare($sql);
      $sth->execute($vid, $channel)
        or return error sprintf("Couldn't execute query: %s.",$sth->errstr);
      my $db_data = $sth->fetchall_hashref('eventid');

      lg sprintf("Compare EPG Database with data from %s : %d / %d for channel '%s' - %s", $hostname, scalar keys %$db_data,scalar keys %$vdrData, $channelname, $channel);
      # Compare this Hashes
      foreach my $eid (keys %{$vdrData}) {
        my $row = $vdrData->{$eid};

        # Exists in DB .. update
        if(exists $db_data->{$eid}) {
          # Compare fields
          foreach my $field (qw/title subtitle ldescription duration starttime vpstime video audio content/) {
            next if(not exists $row->{$field} or not $row->{$field});
            if((not exists $db_data->{$eid}->{$field})
                or (not $db_data->{$eid}->{$field})
                or ($db_data->{$eid}->{$field} ne $row->{$field})) {
              $self->replace($eid, $vid, $row);
              $updatedData++;
              last;
            }
          }

          # delete updated rows from hash
          delete $db_data->{$eid};

        } else {
          # Not exists in DB .. insert
          $self->replace($eid, $vid, $row);
          $changedData++;
        }
      }

      # Delete unused EpgEntrys in DB 
      if(scalar keys %$db_data > 0) {
        my @todel = keys(%$db_data);
        my $sql = sprintf('DELETE FROM EPG WHERE vid = ? and eventid IN (%s)', join(',' => ('?') x @todel)); 
        my $sth = $self->{dbh}->prepare($sql);
        if(!$sth->execute($vid, @todel)) {
            error sprintf("Couldn't execute query: %s.",$sth->errstr);
        }
        $deleteData += scalar @todel;
      }
    } 
    debug sprintf('Finish .. %d events created, %d events replaced, %d events deleted', $changedData, $updatedData, $deleteData);

    return ($changedData + $updatedData + $deleteData);
}

# ------------------
sub moveOldEPGEntrys {
# ------------------
    my $self = shift || return error('No object defined!');

    # Copy and delete old EPG Entrys
    $self->{dbh}->do('REPLACE INTO OLDEPG SELECT * FROM EPG WHERE (UNIX_TIMESTAMP(EPG.starttime) + EPG.duration) < UNIX_TIMESTAMP()');
    $self->{dbh}->do('DELETE FROM EPG WHERE (UNIX_TIMESTAMP(EPG.starttime) + EPG.duration) < UNIX_TIMESTAMP()');
}

# ------------------
sub deleteDoubleEPGEntrys {
# ------------------
    my $self = shift || return error('No object defined!');

    # Delete double EPG Entrys
    my $erg = $self->{dbh}->selectall_arrayref('SELECT eventid FROM EPG GROUP BY starttime, vid, channel_id having count(*) > 1');
    if(scalar @$erg > 0) {
        lg sprintf('Repair data found %d wrong events!', scalar @$erg);
        my $sth = $self->{dbh}->prepare('DELETE FROM EPG WHERE eventid = ?');
        foreach my $row (@$erg) {
            $sth->execute($row->[0]);
        }
    }
}

# ------------------
sub replace {
# ------------------
    my $self = shift || return error('No object defined!');
    my $eventid = shift || return error('No eventid defined!');
    my $vid = shift || return error('No vid defined!');
    my $attr = shift || return error('No data defined!');

    my $sth = $self->{dbh}->prepare('REPLACE INTO EPG(eventid, vid, title, subtitle, description, channel_id, duration, tableid, image, version, video, audio, content, rating, starttime, vpstime, addtime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,FROM_UNIXTIME(?),FROM_UNIXTIME(?),NOW())');
    $sth->execute(
        $eventid,
        $vid,
        $attr->{title},
        $attr->{subtitle},
        $attr->{description},
        $attr->{channel},
        $attr->{duration},
        $attr->{tableid},
        $attr->{image} || '',
        hex($attr->{version}),
        $attr->{video} || '1 01 deu 4:3',
        $attr->{audio} || "2 03 deu stereo",
        $attr->{content} || '',
        $attr->{rating} || 0,
        $attr->{starttime},
        $attr->{vpstime}
    ) if($attr->{channel});
}

# ------------------
sub encodeEpgId {
# ------------------
    my $self = shift || return error('No object defined!');
    my $vid = shift || return error('No data defined!');
    my $epgid = shift || return error('No event defined!');
    my $channel = shift || return error('No channel defined!');

    # look for NID-TID-SID for unique eventids (SID 0-30000 / TID 0 - 1000 / NID 0 - 10000
    my @id = split('-', $channel);

    # Make a fix format 0xCCCCEEEE : C-Channelid (high-word), E-Eventid(low-word) => real-eventid = uniqueid & FFFF
    my $eventid = ((($id[-3] + $id[-2] + $id[-1]) & 0x3FFF) << 16) | ($epgid & 0xFFFF);
       $eventid &= 0x6FFFFFFF; # Keep 0x70000000 .... free for recording events

    return $eventid;
}

# ------------------
sub readEpgData {
# ------------------
    my $self = shift || return error('No object defined!');
    my $vid = shift || return error('No data defined!');
    my $vdata = shift || return error('No data defined!');
    my $count = shift || 0;
    my $dataHash = {};

    my $cmod = main::getModule ('CHANNELS');
    my $channels = $cmod->ChannelArray ('id,name',sprintf(" vid = '%d'", $vid));
    my $channel;
    my $channelname;
    my $event;

    for(;$count < scalar (@$vdata);$count++) {
      my $line = @{$vdata}[$count];

      # Ok, Datarow complete...
      if($line eq 'e' and $event->{eventid} and $event->{channel}) {
        if(-e sprintf('%s/%d.png', $self->{epgimages}, $event->{eventid})) {
          my $firstimage = sprintf('%d',$event->{eventid});
          $event->{image} = $firstimage."\n";
          my $imgpath = sprintf('%s/%d_?.png',$self->{epgimages},$event->{eventid});
          foreach my $img (glob($imgpath)) {
            $event->{image} .= basename($img, '.png')."\n";;
          }
        }

        $channel = $event->{channel};
        my $eventid = $self->encodeEpgId($vid, $event->{eventid}, $channel);

        $event->{title} = gettext("No title")
          unless($event->{title});
        $event->{description} = ""
          unless($event->{description});

        %{$dataHash->{$eventid}} = %{$event};

        $event = undef;
        $event->{channel} = $channel;
        next;
      } 
      elsif($line eq 'c') {
        # Finish this channel
        return ($dataHash,$channel,$channelname,$count+1)
          if(scalar keys %$dataHash);

        undef $event->{channel};
        undef $channel;
        undef $channelname;
      }

      my ($mark, $data) = $line =~ /^(\S)\s+(.+)/g;
      next unless($mark and $data);

      # Next channel 
      if($mark eq 'C') {
        if($channel) {
          debug sprintf('Missing channel endtag c at line %d',$count);
          return ($dataHash,$channel,$channelname,$count) if(scalar keys %$dataHash);
        }
        undef $event->{channel};
        my $channel = (split(/\s+/, $data))[0];
        # import only known channels
        foreach my $ch (@{$channels}) {
          if($ch->[0] eq $channel) { 
            $event->{channel} = $channel;
            $channelname = $ch->[1];
            last;
          }
        }
      } elsif($mark eq 'E') {
        ($event->{eventid}, $event->{starttime}, $event->{duration}, $event->{tableid}, $event->{version}) = split(/\s+/, $data);
      } elsif($mark eq 'T') {
        $event->{title} = $data;
      } elsif($mark eq 'S') {
        $event->{subtitle} = $data;
      } elsif($mark eq 'D') {
        $event->{description} = $data;
        $event->{description} =~ s/\|/\r\n/g;            # pipe used from vdr as linebreak
        $event->{description} =~ s/^\s+//;               # no leading white space
        $event->{description} =~ s/\s+$//;               # no trailing white space
        $event->{ldescription} = length($event->{description});
      } elsif($mark eq 'X') {
        my @d = split(/\s+/, $data);
        if($d[0] eq '1') {
          $event->{video} .= $data;
        } else {
          $event->{audio} .= $data."\n";
        }
      } elsif($mark eq 'V') {
        $event->{vpstime} = $data;
      } elsif($mark eq 'G') {
        $event->{content} = $data;
      } elsif($mark eq 'R') {
        $event->{rating} = $data;
      }
    }
    return ($dataHash,$channel,$channelname,$count);
}

# ------------------
sub search {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $data = shift;
    my $params = shift;

    # Textsearch
    my $search;
    if($data) {
        if($params->{Where} && $params->{Where} eq 'title') {
            $search = buildsearch("e.title",$data);
        } elsif($params->{Where} && $params->{Where} eq 'titlesubtitle') {
            $search = buildsearch("e.title,e.subtitle",$data);
        } else {
            $search = buildsearch("e.title,e.subtitle,e.description",$data);
        }
    } else {
      $search->{query} = "1";
    }

    my $erg = [];
    my $rows = 0;
    my $cmod = main::getModule('CHANNELS');

    if($search) {

      # Channelsearch
      if($params->{channel}) {
          $search->{query} .= ' AND c.id = ?';
          push(@{$search->{term}}, $cmod->ToCID($params->{channel}));
      }

      # Videoformat search
      if($params->{Videoformat} && $params->{Videoformat} eq 'widescreen') {
          $search->{query} .= ' AND e.video like "%%16:9%%"';
      }

      # Audioformat search
      # XXX: Leider kann man an den Audioeintrag nicht richtig erkennnen
      # hab erst zu spät erkannt das diese Info aus dem tvm2vdr kommen ;(
  #    if($params->{Audioformat} eq 'dts') {
  #        $search->{query} .= ' AND e.audio like "%%Digital%%"';
  #    }

      # MinLength search
      if($params->{MinLength}) {
          $search->{query} .= ' AND e.duration >= ?';
          push(@{$search->{term}},($params->{MinLength}*60));
      }

      if($params->{contentid}) {
          my $c = $params->{contentid};
          $c .= '[[:xdigit:]]+' if(length $c == 1);
          $search->{query} .= ' AND e.content REGEXP ?';
          push(@{$search->{term}}, $c);
      }

      my %f = (
          'id' => gettext('Service'),
          'title' => gettext('Title'),
          'channel' => gettext('Channel'),
          'start' => gettext('Start'),
          'stop' => gettext('Stop'),
          'duration' => gettext('Duration'),
          'day' => gettext('Day')
      );

      my $sql = qq|
      SELECT SQL_CACHE 
          e.eventid as \'$f{'id'}\',
          e.title as \'$f{'title'}\',
          e.subtitle as __Subtitle,
          c.name as \'$f{'channel'}\',
          c.hash as __position,
          DATE_FORMAT(e.starttime, '%H:%i') as \'$f{'start'}\',
          DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(e.starttime) + e.duration), '%H:%i') as \'$f{'stop'}\',
          e.duration as \'$f{'duration'}\',
          UNIX_TIMESTAMP(e.starttime) as \'$f{'day'}\',
          IF(CHAR_LENGTH(e.description)>77,RPAD(LEFT(e.description,77),80,'.'),e.description) as __Description,
          IF(e.vpstime!=0,DATE_FORMAT(e.vpstime, '%H:%i'),'') as __PDC,
          ( SELECT 
              t.id
              FROM TIMERS as t
              WHERE t.eventid = e.eventid
              LIMIT 1) as __timerid,
          ( SELECT 
              (t.flags & 1) 
              FROM TIMERS as t
              WHERE t.eventid = e.eventid
              LIMIT 1) as __timeractiv,
          ( SELECT 
              NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
              FROM TIMERS as t
              WHERE t.eventid = e.eventid
              LIMIT 1) as __running,
          ( SELECT 
              s.level
              FROM SHARE as s
              WHERE s.eventid = e.eventid
              LIMIT 1) as __level
      from
          EPG as e,
          CHANNELS as c
      where
          e.channel_id = c.id
          AND e.vid = c.vid
          AND ( $search->{query} )
          AND ((UNIX_TIMESTAMP(e.starttime) + e.duration) > UNIX_TIMESTAMP())
      group by
          c.id, e.eventid
      order by
          starttime
          |;

      my $sth;
      my $limit = $console->{cgi} && $console->{cgi}->param('limit') ? CORE::int($console->{cgi}->param('limit')) : 250;
      if($limit > 0) {
        # Query total count of rows
        my $rsth = $self->{dbh}->prepare($sql);
           $rsth->execute(@{$search->{term}})
            or return error sprintf("Couldn't execute query: %s.",$rsth->errstr);
        $rows = $rsth->rows;
        if($rows <= $limit) {
          $sth = $rsth;
        } else {
          # Add limit query
          if($console->{cgi}->param('start')) {
            $sql .= " LIMIT " . CORE::int($console->{cgi}->param('start'));
            $sql .= "," . $limit;
          } else {
            $sql .= " LIMIT " . $limit;
          }
        }
      }

      unless($sth) {
        $sth = $self->{dbh}->prepare($sql);
        $sth->execute(@{$search->{term}})
          or return error sprintf("Couldn't execute query: %s.",$sth->errstr);
        $rows = $sth->rows unless($rows);
      }

      my $fields = $sth->{'NAME'};
      $erg = $sth->fetchall_arrayref();

      unless($console->typ eq 'AJAX') {
        map {
            $_->[7] = fmtSec2Time($_->[7]);
            $_->[8] = datum($_->[8],'weekday');
        } @$erg;

        unshift(@$erg, $fields);
      }
    }
    my $info = {
      rows => $rows
    };
    if($console->typ eq 'HTML') {
      $info->{channels} = $cmod->ChannelWithGroup('c.name,c.hash');
    }
    $console->table($erg, $info );
}

# ------------------
sub program {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $cid = shift;
    unless($cid) {
      my $c = $self->{dbh}->selectrow_arrayref("SELECT SQL_CACHE hash from CHANNELS order by vid, pos limit 1");
      return $console->err(gettext("No channel available!"))
        unless($c && $c->[0]);
      $cid = $c->[0];
    }


    my $cmod = main::getModule('CHANNELS');

    my $search;
    if($console->{cgi}->param('filter')) {
      $search = buildsearch("e.title,e.subtitle,e.description",$console->{cgi}->param('filter'));
      $search->{query} .= ' AND ';
    }

    $search->{query} .= ' c.id = ?';
    $cid = $cmod->ToCID($cid);
    push(@{$search->{term}},$cid);

    my %f = (
        'id' => gettext('Service'),
        'title' => gettext('Title'),
        'start' => gettext('Start'),
        'stop' => gettext('Stop')
    );

    my $sql = qq|
SELECT SQL_CACHE 
    e.eventid as \'$f{'id'}\',
    e.title as \'$f{'title'}\',
    e.subtitle as __Subtitle,
    DATE_FORMAT(e.starttime, '%H:%i') as \'$f{'start'}\',
    DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(e.starttime) + e.duration), '%H:%i') as \'$f{'stop'}\',
    e.duration as __duration,
    UNIX_TIMESTAMP(e.starttime) as __day,
    IF(CHAR_LENGTH(e.description)>77,RPAD(LEFT(e.description,77),80,'.'),e.description) as __Description,
    IF(e.vpstime!=0,DATE_FORMAT(e.vpstime, '%H:%i'),'') as __PDC,
    ( SELECT 
        t.id
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timerid,
    ( SELECT 
        (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timeractiv,
    ( SELECT 
        NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __running,
    ( SELECT 
        s.level
        FROM SHARE as s
        WHERE s.eventid = e.eventid
        LIMIT 1) as __level
from
    EPG as e, CHANNELS as c
where
    e.channel_id = c.id
    AND e.vid = c.vid
    AND ( $search->{query} )
    AND ((UNIX_TIMESTAMP(e.starttime) + e.duration) > UNIX_TIMESTAMP())
group by
    e.eventid
order by
    starttime
|;

    my $rows;
    my $sth;
    my $limit = $console->{cgi} && $console->{cgi}->param('limit') ? CORE::int($console->{cgi}->param('limit')) : 0;
    if($limit > 0) {
      # Query total count of rows
      my $rsth = $self->{dbh}->prepare($sql);
         $rsth->execute(@{$search->{term}})
          or return error sprintf("Couldn't execute query: %s.",$rsth->errstr);
      $rows = $rsth->rows;
      if($rows <= $limit) {
        $sth = $rsth;
      } else {
        # Add limit query
        if($console->{cgi}->param('start')) {
          $sql .= " LIMIT " . CORE::int($console->{cgi}->param('start'));
          $sql .= "," . $limit;
        } else {
          $sql .= " LIMIT " . $limit;
        }
      }
    }

    unless($sth) {
      $sth = $self->{dbh}->prepare($sql);
      $sth->execute(@{$search->{term}})
        or return error sprintf("Couldn't execute query: %s.",$sth->errstr);
      $rows = $sth->rows unless($rows);
    }

    my $fields = $sth->{'NAME'};
    my $erg = $sth->fetchall_arrayref();

    unless($console->typ eq 'AJAX') {
      map {
          $_->[5] = fmtSec2Time($_->[5]);
          $_->[6] = datum($_->[6],'weekday');
      } @$erg;

      unshift(@$erg, $fields);
    }

    my $info = {
      rows => $rows
    };
    if($console->typ eq 'HTML' 
        || $console->typ eq 'WML') {
      $info->{channels} = $cmod->ChannelWithGroup('c.name,c.hash');
      $info->{current} = $cid;
    }
    $console->table($erg, $info );
}

# ------------------
sub display {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $eventid = shift;

    unless($eventid) {
        con_err($console, gettext("No ID defined to display this program! Please use display 'eid'!"));
        return;
    }

    my %f = (
        'Id' => gettext('Service'),
        'Title' => gettext('Title'),
        'Subtitle' => gettext('Subtitle'),
        'Channel' => gettext('Channel'),
        'Start' => gettext('Start'),
        'Stop' => gettext('Stop'),
        'Description' => gettext('Description'),
        'Percent' => gettext('Percent')
    );

    my $fields;
    my $erg;

   foreach my $table (qw/EPG OLDEPG/) {
    my $sql = qq|
SELECT SQL_CACHE 
    e.eventid as \'$f{'Id'}\',
    e.title as \'$f{'Title'}\',
    e.subtitle as \'$f{'Subtitle'}\',
    UNIX_TIMESTAMP(e.starttime) as \'$f{'Start'}\',
    UNIX_TIMESTAMP(e.starttime) + e.duration as \'$f{'Stop'}\',
    c.name as \'$f{'Channel'}\',
    e.description as \'$f{'Description'}\',
    e.video as __Video,
    e.audio as __Audio,
    (unix_timestamp(e.starttime) + e.duration - unix_timestamp())/duration*100 as \'$f{'Percent'}\',
    ( SELECT 
        t.id
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timerid,
    ( SELECT 
        (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timeractiv,
    ( SELECT 
        NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __running,
    e.image as __Image,
    UNIX_TIMESTAMP(e.vpstime) as __PDC,
    e.channel_id as __channel_id,
    ( SELECT 
        s.level
        FROM SHARE as s
        WHERE s.eventid = e.eventid
        LIMIT 1) as __level,
    e.content as __content,
    e.rating as __rating
from
    $table as e,CHANNELS as c
where
    e.channel_id = c.id
    AND e.vid = c.vid
    and eventid = ?
group by
    eventid
|;
    my $sth = $self->{dbh}->prepare($sql);
    $sth->execute($eventid)
        or return con_err($console, sprintf("Couldn't execute query: %s.",$sth->errstr));
    $fields = $sth->{'NAME'};
    $erg = $sth->fetchall_arrayref();

    last
      if(scalar @{$erg} != 0 );
    }

    if(scalar @{$erg} == 0 ) {
        con_err($console, sprintf(gettext("Event '%d' does not exist in the database!"),$eventid));
        return;
    }
    if($console->{TYP} ne 'HTML') {
      map {
          $_->[3] = datum($_->[3],'voll');
          $_->[4] = datum($_->[4],'time');
          $_->[14] = datum($_->[14],'time') if($_->[14]);
      } @$erg;
    }
    unless($console->typ eq 'AJAX') {
      unshift(@$erg, $fields);
    }
    $console->table($erg);
}

# ------------------
sub runningNext {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $data   = shift;
    my $param   = shift || {};

    # Create temporary table
    $self->{dbh}->do(qq|
CREATE TEMPORARY TABLE IF NOT EXISTS NEXTEPG (
    channel_id varchar(100) NOT NULL default '',
    nexttime datetime NOT NULL default '0000-00-00 00:00:00'
    )
|) or error sprintf("Couldn't execute query: %s.", $DBI::errstr);
    # Remove old data
    $self->{dbh}->do('delete from NEXTEPG') or error sprintf("Couldn't execute query: %s.", $DBI::errstr);

    # Get channelid and starttime of next broadcasting
    my $sqltemp = qq|
INSERT INTO NEXTEPG select 
    c.id as channel_id,
    MIN(e.starttime) as nexttime
    FROM EPG as e, CHANNELS as c, CHANNELGROUPS as g
    WHERE e.channel_id = c.id
    AND e.starttime > NOW()
    AND c.grp = g.id
|;

    my $term;
    my $grpsql = '';
    my $cmod = main::getModule('CHANNELS');
    my $cgroups = $cmod->ChannelGroupsArray('name');
    my $cgrp = $param->{cgrp} || $cgroups->[0][1]; # First id of groups;

    if($cgrp && $cgrp ne 'all') {
      my $cgrps;
      # Find any groups by same group name
      foreach my $g (@$cgroups) {
        if($g->[1] == $cgrp) {
          $cgrps = $cmod->GroupsByName($g->[0]);
          last;
        }
      }
      # build query
      if($cgrps) {
        $grpsql = sprintf(" AND g.id in (%s) ",join(',' => ('?') x @$cgrps));
        foreach my $c (@$cgrps) {
          push(@{$term},$c->[0]);
        }
      } elsif($cgrp) { # group id 
        $grpsql = " AND g.id = ? ";
        push(@{$term},$cgrp);
      }
    }
    $sqltemp .= $grpsql;
    $sqltemp .= qq|
GROUP BY c.id 
ORDER BY c.vid, c.pos
|;

    my $sthtemp = $self->{dbh}->prepare($sqltemp);
    if($term) {
      if(ref $term eq 'ARRAY') {
        my $x = 1;
        foreach (@$term) {
          $sthtemp->bind_param( $x++, $_ );
        }
      } 
      else {
        $sthtemp->bind_param( 1, $term );
      }
    }
    $sthtemp->execute()
      or return con_err($console, sprintf("Couldn't execute query: %s.",$sthtemp->errstr));

    my %f = (
        'Service' => gettext('Service'),
        'Title' => gettext('Title'),
        'Channel' => gettext('Channel'),
        'Start' => gettext('Start'),
        'Stop' => gettext('Stop')
    );
    my $sql =
qq|
SELECT SQL_CACHE 
    e.eventid as \'$f{'Service'}\',
    e.title as \'$f{'Title'}\',
    e.subtitle as __Subtitle,
    c.name as \'$f{'Channel'}\',
    c.hash as __position,
    g.name as __Channelgroup,
    DATE_FORMAT(e.starttime, "%H:%i") as \'$f{'Start'}\',
    DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(starttime) + e.duration), "%H:%i") as \'$f{'Stop'}\',
    e.duration as __duration,
    IF(CHAR_LENGTH(e.description)>77,RPAD(LEFT(e.description,77),80,'.'),e.description) as __Description,
    999 as __Percent,
    ( SELECT 
        t.id
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timerid,
    ( SELECT 
        (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timeractiv,
    ( SELECT 
        NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __running,
    IF(e.vpstime!=0,DATE_FORMAT(e.vpstime, '%H:%i'),'') as __PDC,
    ( SELECT 
        s.level
        FROM SHARE as s
        WHERE s.eventid = e.eventid
        LIMIT 1) as __level
FROM
    EPG as e, CHANNELS as c, NEXTEPG as n, CHANNELGROUPS as g
WHERE
    e.starttime = n.nexttime
    AND e.channel_id = c.id
    AND c.grp = g.id
|;

    # Merge epg entries from different hosts, only if more then one host exists (it slow down query)
#    if(scalar @{$self->{svdrp}->list_hosts()} > 1) {
#        $sql .= qq|
#    AND e.vid = c.vid
#    AND c.vid = g.vid
#|;
#    }

    $sql .= $grpsql;
    $sql .= qq|
GROUP BY c.id 
ORDER BY g.pos, c.pos, c.vid
|;

    my $rows;
    my $sth;
    my $limit = $console->{cgi} && $console->{cgi}->param('limit') ? CORE::int($console->{cgi}->param('limit')) : 0;
    if($limit > 0) {
      # Query total count of rows
      my $rsth = $self->{dbh}->prepare($sql);
        if($term) {
          if(ref $term eq 'ARRAY') {
            my $x = 1;
            foreach (@$term) {
              $sth->bind_param( $x++, $_ );
            }
          }
          else {
            $sth->bind_param( 1, $term );
          }
        }
        $rsth->execute()
          or return error sprintf("Couldn't execute query: %s.",$rsth->errstr);
      $rows = $rsth->rows;
      if($rows <= $limit) {
        $sth = $rsth;
      } else {
        # Add limit query
        if($console->{cgi}->param('start')) {
          $sql .= " LIMIT " . CORE::int($console->{cgi}->param('start'));
          $sql .= "," . $limit;
        } else {
          $sql .= " LIMIT " . $limit;
        }
      }
    }

    unless($sth) {
      $sth = $self->{dbh}->prepare($sql);
      if($term) {
        if(ref $term eq 'ARRAY') {
          my $x = 1;
          foreach (@$term) {
            $sth->bind_param( $x++, $_ );
          }
        }
        else {
          $sth->bind_param( 1, $term );
        }
      }
      $sth->execute()
        or return error sprintf("Couldn't execute query: %s.",$sth->errstr);
      $rows = $sth->rows unless($rows);
    }


    my $fields = $sth->{'NAME'};
    my $erg = $sth->fetchall_arrayref();
    unless($console->typ eq 'AJAX') {
      map {
          $_->[8] = fmtSec2Time($_->[8]);
      } @$erg;
      unshift(@$erg, $fields);
    }

    $console->table($erg,
        {
            periods => $config->{periods},
            cgroups => $cgroups,
            channelgroup => $cgrp,
            rows => $rows
        }
    );
}

# ------------------
sub runningNow {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $zeit = shift || time;
    my $param   = shift || {};

    # i.e.: 635 --> 06:35
    $zeit = fmttime($zeit)
        if(length($zeit) <= 4);

    # i.e.: 06:35 --> timeinsecs
    if($zeit =~ /^\d+:\d+$/sig) {
        $zeit   = UnixDate(ParseDate($zeit),"%s") || time;
    }

    $zeit += 86400 if($zeit < time);
    $zeit++;

    my %f = (
        'Service' => gettext('Service'),
        'Title' => gettext('Title'),
        'Channel' => gettext('Channel'),
        'Start' => gettext('Start'),
        'Stop' => gettext('Stop'),
        'Percent' => gettext('Percent')
    );
    my $sql =
qq|
SELECT SQL_CACHE 
    e.eventid as \'$f{'Service'}\',
    e.title as \'$f{'Title'}\',
    e.subtitle as __Subtitle,
    c.name as \'$f{'Channel'}\',
    c.hash as __position,
    g.name as __Channelgroup,
    DATE_FORMAT(e.starttime, "%H:%i") as \'$f{'Start'}\',
    DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(starttime) + e.duration), "%H:%i") as \'$f{'Stop'}\',
    e.duration as __duration,
    IF(CHAR_LENGTH(e.description)>77,RPAD(LEFT(e.description,77),80,'.'),e.description) as __Description,
    (unix_timestamp(e.starttime) + e.duration - unix_timestamp())/e.duration*100 as \'$f{'Percent'}\',
    ( SELECT 
        t.id
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timerid,
    ( SELECT 
        (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timeractiv,
    ( SELECT 
        NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __running,
    IF(e.vpstime!=0,DATE_FORMAT(e.vpstime, '%H:%i'),'') as __PDC,
    ( SELECT 
      s.level
      FROM SHARE as s
      WHERE s.eventid = e.eventid
      LIMIT 1) as __level
FROM
    EPG as e, CHANNELS as c, CHANNELGROUPS as g
WHERE
    ? BETWEEN UNIX_TIMESTAMP(e.starttime)
    AND (UNIX_TIMESTAMP(e.starttime) + e.duration)
    AND e.channel_id = c.id
    AND c.grp = g.id
|;

    # Merge epg entries from different hosts, only if more then one host exists (it slow down query)
    if(scalar @{$self->{svdrp}->list_hosts()} > 1) {
        $sql .= qq|
    AND e.vid = c.vid
    AND c.vid = g.vid
|;
    }

    my $cmod = main::getModule('CHANNELS');
    my $cgroups = $cmod->ChannelGroupsArray('name');
    my $cgrp = $param->{cgrp} || $cgroups->[0][1]; # First id of groups;

    my $term;
    push(@{$term},$zeit);
    if($cgrp && $cgrp ne 'all') {
      my $cgrps;
      # Find any groups by same group name
      foreach my $g (@$cgroups) {
        if($g->[1] == $cgrp) {
          $cgrps = $cmod->GroupsByName($g->[0]);
          last;
        }
      }
      # build query
      if($cgrps) {
        $sql .= sprintf(" AND g.id in (%s) ",join(',' => ('?') x @$cgrps));
        foreach my $c (@$cgrps) {
          push(@{$term},$c->[0]);
        }
      } elsif($cgrp) { # group id 
        $sql .= " AND g.id = ? ";
        push(@{$term},$cgrp);
      }
    }

    $sql .= qq|
GROUP BY c.id 
ORDER BY g.pos, c.pos, c.vid
|;

    my $rows;
    my $sth;
    my $limit = $console->{cgi} && $console->{cgi}->param('limit') ? CORE::int($console->{cgi}->param('limit')) : 0;
    if($limit > 0) {
      # Query total count of rows
      my $rsth = $self->{dbh}->prepare($sql);
         $rsth->execute(@{$term})
          or return error sprintf("Couldn't execute query: %s.",$rsth->errstr);
      $rows = $rsth->rows;
      if($rows <= $limit) {
        $sth = $rsth;
      } else {
        # Add limit query
        if($console->{cgi}->param('start')) {
          $sql .= " LIMIT " . CORE::int($console->{cgi}->param('start'));
          $sql .= "," . $limit;
        } else {
          $sql .= " LIMIT " . $limit;
        }
      }
    }

    unless($sth) {
      $sth = $self->{dbh}->prepare($sql);
        $sth->execute(@{$term})
          or return error sprintf("Couldn't execute query: %s.",$sth->errstr);
      $rows = $sth->rows unless($rows);
    }

    my $fields = $sth->{'NAME'};
    my $erg = $sth->fetchall_arrayref();
    unless($console->typ eq 'AJAX') {
      map {
          $_->[8] = fmtSec2Time($_->[8]);
      } @$erg;
      unshift(@$erg, $fields);
    }

    $console->table($erg,
        {
            zeit => $zeit,
            periods => $config->{periods},
            cgroups => $cgroups,
            channelgroup => $cgrp,
            rows => $rows
        }
    );
}

# ------------------
sub NowOnChannel {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift;
    my $config = shift;
    my $channel = shift;
    my $vid = shift || $self->{svdrp}->primary_hosts();

    $channel = $self->_actualChannel($vid) unless($channel);
    return con_err($console, gettext('No channel defined!')) unless($channel);

    my $zeit = time;

    my $sql =
qq|
SELECT SQL_CACHE 
    e.eventid as Service,
    e.title as Title,
    e.subtitle as Subtitle,
    c.name as Channel,
    c.pos as POS,
    e.video as __video,
    e.audio as __audio,
    DATE_FORMAT(e.starttime, "%a %d.%m") as StartDay,
    DATE_FORMAT(e.starttime, "%H:%i") as StartTime,
    (unix_timestamp(e.starttime) + e.duration - unix_timestamp())/e.duration*100 as __Percent,
    IF(CHAR_LENGTH(e.description)>77,RPAD(LEFT(e.description,77),80,'.'),e.description) as Description,
    IF(e.vpstime!=0,DATE_FORMAT(e.vpstime, '%H:%i'),'') as __PDC,        
    ( SELECT 
        t.id
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timerid,
    ( SELECT 
        (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timeractiv,
    ( SELECT 
        NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __running,
    ( SELECT 
        s.level
        FROM SHARE as s
        WHERE s.eventid = e.eventid
        LIMIT 1) as __level
FROM
    EPG as e, CHANNELS as c
WHERE
    e.channel_id = c.id
    AND e.vid = c.vid
    AND ? BETWEEN UNIX_TIMESTAMP(e.starttime)
    AND (UNIX_TIMESTAMP(e.starttime) + e.duration)
    AND c.vid = ?
    AND c.pos = ?
ORDER BY
    starttime
LIMIT 1
|;
    my $sth = $self->{dbh}->prepare($sql);
    $sth->execute($zeit, $vid, $channel)
        or return con_err($console, sprintf("Couldn't execute query: %s.",$sth->errstr));
    my $erg = $sth->fetchrow_hashref();

    if(ref $console) {
        return $console->table($erg);
    } else {
        return $erg;
    }
}

# ------------------
sub _actualChannel {
# ------------------
    my $self = shift  || return error('No object defined!');
    my $vid = shift;

    my ($erg,$error) = $self->{svdrp}->command('chan', $vid);
    unless($error) {
      my ($chanpos, $channame) = $erg->[1] =~ /^250\s+(\d+)\s+(\S+)/sig;
      return $chanpos;
    } else {
      return undef;
    }
}

# ------------------
sub schema {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $zeit = shift || time;
    my $param   = shift || {};

    my $term;

    # i.e.: 635 --> 06:35
    $zeit = fmttime($zeit)
        if(length($zeit) <= 4);

    # i.e.: 06:35 --> timeinsecs
    if($zeit =~ /^\d+:\d+$/sig) {
        $zeit   = UnixDate(ParseDate($zeit),"%s") || time;
    }

    $zeit += 86400 if($zeit < time - ($config->{timeframe} * 3600));
    $zeit++;

    my $zeitvon = $self->toFullHour($zeit);
    my $zeitbis = $zeitvon + ($config->{timeframe}*3600);

    push(@$term, $zeitvon);
    push(@$term, $zeitbis);
    push(@$term, $zeitvon);
    push(@$term, $zeitbis);
    push(@$term, $zeitvon);
    push(@$term, $zeitbis);

    my $sql =
qq|
SELECT SQL_CACHE 
    e.eventid as Service,
    e.title as Title,
    e.subtitle as __Subtitle,
    c.name as Channel,
    c.hash as __channelid,
    DATE_FORMAT(e.starttime, "%H:%i") as Start,
    DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(starttime) + e.duration), "%H:%i") as Stop,
    (unix_timestamp(e.starttime) + e.duration - unix_timestamp())/e.duration*100 as Percent,
    IF(CHAR_LENGTH(e.description)>77,RPAD(LEFT(e.description,77),80,'.'),e.description) as __Description,
    UNIX_TIMESTAMP(starttime) as second_start,
    UNIX_TIMESTAMP(starttime) + e.duration as second_stop,
    e.image as __image,      
    ( SELECT 
        t.id
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timerid,
    ( SELECT 
        (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __timeractiv,
    ( SELECT 
        NOW() between t.starttime and t.stoptime AND (t.flags & 1) 
        FROM TIMERS as t
        WHERE t.eventid = e.eventid
        LIMIT 1) as __running,
    c.vid as __vid,
    c.pos as __position,
    ( SELECT 
              s.level
              FROM SHARE as s
              WHERE s.eventid = e.eventid
              LIMIT 1) as __level
FROM
    EPG as e, CHANNELS as c, CHANNELGROUPS as g
WHERE
    e.channel_id = c.id
    AND c.grp = g.id
    AND
    (
        ( UNIX_TIMESTAMP(e.starttime) BETWEEN ? AND ? )
        OR
        ( UNIX_TIMESTAMP(e.starttime) + e.duration BETWEEN ? AND ? )
        OR
        ( ? BETWEEN UNIX_TIMESTAMP(e.starttime) AND (UNIX_TIMESTAMP(e.starttime) + e.duration) )
        OR
        ( ? BETWEEN UNIX_TIMESTAMP(e.starttime) AND (UNIX_TIMESTAMP(e.starttime) + e.duration) )
    )|;

    my $cmod = main::getModule('CHANNELS');
    my $cgroups = $cmod->ChannelGroupsArray('name');
    my $cgrp = $param->{cgrp} || $cgroups->[0][1]; # First id of groups;

    if($cgrp && $cgrp ne 'all') {
      my $cgrps;
      # Find any groups by same group name
      foreach my $g (@$cgroups) {
        if($g->[1] == $cgrp) {
          $cgrps = $cmod->GroupsByName($g->[0]);
          last;
        }
      }
      # build query
      if($cgrps) {
        $sql .= sprintf(" AND g.id in (%s) ",join(',' => ('?') x @$cgrps));
        foreach my $c (@$cgrps) {
          push(@{$term},$c->[0]);
        }
      } elsif($cgrp) { # group id 
        $sql .= " AND g.id = ? ";
        push(@{$term},$cgrp);
      }
    }
    $sql .= qq|
  GROUP BY c.id,e.starttime
  ORDER BY c.vid, c.pos,e.starttime
|;

    my $sth = $self->{dbh}->prepare($sql);
    $sth->execute(@$term)
        or return con_err($console, sprintf("Couldn't execute query: %s.",$sth->errstr));
    my $erg = $sth->fetchall_arrayref();

    my $data = {};
    foreach my $c (@$erg) {
        push(@{$data->{($c->[15]*100000) + $c->[16]}}, $c);
    }

    $console->table($data,
        {
            zeitvon => $zeitvon,
            zeitbis => $zeitbis,
            periods => $config->{periods},
            cgroups => $cgroups,
            channelgroup => $cgrp
        }
    );
}

# ------------------
sub checkOnTimer {
# ------------------
    my $self = shift  || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $eid = shift  || return con_err($console, gettext('No event id defined!'));

    my $sql = qq|
SELECT SQL_CACHE 
    e.starttime,
    ADDDATE(e.starttime, INTERVAL e.duration SECOND) as stoptime,
    LEFT(c.Source,1) as source,
    c.TID,
    e.vid
FROM
    EPG as e, CHANNELS as c
WHERE
    e.eventid = ?
    AND e.channel_id = c.id
    AND e.vid = c.vid
|;

    my $tmod = main::getModule('TIMERS');

    my $sth = $self->{dbh}->prepare($sql);
    $sth->execute($eid)
        or return con_err($console, sprintf("Couldn't execute query: %s.",$sth->errstr));
    my $data = $sth->fetchrow_hashref();
    my $erg = $tmod->checkOverlapping($data) || ['ok'];

    # Zeige den Title des Timers
    foreach (@$erg) { 
      $_ = $tmod->getTimerById((split(':', $_))[0])->{file}
        unless($_ eq 'ok'); 
    }

    $console->message(join(',',@$erg))
        if(ref $console);

}

# ------------------
sub getDescription {
# ------------------
    my $self = shift  || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $eid = shift || 0;

    my $event = $self->getId($eid,"description");

    $console->message($event && $event->{description} ? $event->{description} : "")
      if(ref $console);
}

# ------------------
sub toFullHour {
# ------------------
    my $self = shift  || return error('No object defined!');
    my $zeit = shift || return error ('No time to convert defined!');

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
                                             localtime($zeit);
    my $retzeit = timelocal(0, 0, $hour, $mday, $mon, $year);
    return $retzeit;
}


# ------------------
sub getId {
# ------------------
    my $self = shift || return error('No object defined!');
    my $id = shift || return error('No id defined!');
    my $fields = shift || '*';

    foreach my $table (qw/EPG OLDEPG/) {
    # EPG
        my $sql = sprintf('SELECT SQL_CACHE %s from %s WHERE eventid = ?',$fields, $table); 
        my $sth = $self->{dbh}->prepare($sql);
           $sth->execute($id) 
                or return error "Couldn't execute query: $sth->errstr.";

        my $erg = $sth->fetchrow_hashref();
        return $erg
            if($erg);
    }
    lg sprintf("Event %d does not exist!", $id);
    return {};
}

# ------------------
sub suggest {
# ------------------
    my $self = shift  || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $search = shift;
    my $params  = shift;
  
    if($search) {
        my $ch = '';
        my $cid;
        if($params->{channel}) {
            my $cmod = main::getModule('CHANNELS');
            $cid = $cmod->ToCID($params->{channel});
            return con_err($console, sprintf(gettext("Channel '%s' does not exist in the database!"),$params->{channel}))
              unless($cid);
            $ch = " AND c.id = ? ";
        }

        my $sql = qq|
    SELECT SQL_CACHE
        e.title as title
    FROM
        EPG as e,
        CHANNELS as c
    WHERE
        channel_id = c.id
      AND e.vid = c.vid
      AND ( e.title LIKE ? )
        $ch
    GROUP BY
        title
UNION
    SELECT SQL_CACHE 
        e.subtitle as title
    FROM
        EPG as e,
        CHANNELS as c
    WHERE
        channel_id = c.id
      AND e.vid = c.vid
      AND ( e.subtitle LIKE ? )
        $ch
    GROUP BY
        title
ORDER BY
    title
LIMIT 25
        |;
        my $sth = $self->{dbh}->prepare($sql);
        if($cid) {
            $sth->execute('%'.$search.'%',$cid,'%'.$search.'%',$cid) 
                or return error "Couldn't execute query: $sth->errstr.";
        } else {
            $sth->execute('%'.$search.'%','%'.$search.'%')
                or return error "Couldn't execute query: $sth->errstr.";
        }
        my $result = $sth->fetchall_arrayref();
        $console->table($result)
            if(ref $console && $result);
    }
}

# ------------------
sub image {
# ------------------
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');
    my $data = shift;

    return $console->err(gettext("Sorry, get image is'nt supported"))
      if ($console->{TYP} ne 'HTML');

    return $console->status404('NULL','Wrong image parameter') 
      unless($data);

    my ($eventid) = $data =~ /^([0-9_]+)$/si;

    return $console->status404('NULL','Wrong image parameter') 
      unless($eventid);
    return $console->datei(sprintf('%s/%s.png',$self->{epgimages},$eventid));
}


# ------------------
sub content {
# ------------------
    my $self = shift || return error('No object defined!');
    my $content = shift || return error('No content defined!');
  
    $content = hex($content);
    
    my $translate = {
       0x1  => gettext('Movie/Drama')
      ,0x10 => gettext('Movie/Drama')
      ,0x11 => gettext('Detective/Thriller')
      ,0x12 => gettext('Adventure/Western/War')
      ,0x13 => gettext('Science Fiction/Fantasy/Horror')
      ,0x14 => gettext('Comedy')
      ,0x15 => gettext('Soap/Melodrama/Folkloric')
      ,0x16 => gettext('Romance')
      ,0x17 => gettext('Serious/Classical/Religious/Historical Movie/Drama')
      ,0x18 => gettext('Adult Movie/Drama')
#     ,0x19 to 0x1E reserved for future use
#     ,0x1F => user defined

      ,0x2   => gettext('News/Current Affairs')
      ,0x20  => gettext('News/Current Affairs')
      ,0x21  => gettext('News/Weather Report')
      ,0x22  => gettext('News Magazine')
      ,0x23  => gettext('Documentary')
      ,0x24  => gettext('Discussion/Inverview/Debate')
#     ,0x25 to 0x2E reserved for future use
#     ,0x2F  => user defined

      ,0x3   => gettext('Show/Game Show')
      ,0x30  => gettext('Show/Game Show')
      ,0x31  => gettext('Game Show/Quiz/Contest')
      ,0x32  => gettext('Variety Show')
      ,0x33  => gettext('Talk Show')
#     ,0x34 to 0x3E reserved for future use
#     ,0x3F  => user defined

      ,0x4   => gettext('Sports')
      ,0x40  => gettext('Sports')
      ,0x41  => gettext('Special Event')
      ,0x42  => gettext('Sport Magazine')
      ,0x43  => gettext('Football/Soccer') 
      ,0x44  => gettext('Tennis/Squash')
      ,0x45  => gettext('Team Sports')
      ,0x46  => gettext('Athletics')
      ,0x47  => gettext('Motor Sport')
      ,0x48  => gettext('Water Sport')
      ,0x49  => gettext('Winter Sports')
      ,0x4A  => gettext('Equestrian')
      ,0x4B  => gettext('Martial Sports')
#     ,0x4C to 0x4E reserved for future use
#     ,0x4F  => user defined

      ,0x5   => gettext("Children's/Youth Programme")
      ,0x50  => gettext("Children's/Youth Programme")
      ,0x51  => gettext("Pre-school Children's Programme")
      ,0x52  => gettext('Entertainment Programme for 6 to 14')
      ,0x53  => gettext('Entertainment Programme for 10 to 16')
      ,0x54  => gettext('Informational/Educational/School Programme')
      ,0x55  => gettext('Cartoons/Puppets')
#     ,0x56 to 0x5E reserved for future use
#     ,0x5F  => user defined

      ,0x6   => gettext('Music/Ballet/Dance')
      ,0x60  => gettext('Music/Ballet/Dance')
      ,0x61  => gettext('Rock/Pop')
      ,0x62  => gettext('Serious/Classical Music')
      ,0x63  => gettext('Folk/Tradional Music')
      ,0x64  => gettext('Jazz')
      ,0x65  => gettext('Musical/Opera')
      ,0x66  => gettext('Ballet')
#     ,0x67 to 0x6E reserved for future use
#     ,0x6F  => user defined

      ,0x7   => gettext('Arts/Culture')
      ,0x70  => gettext('Arts/Culture')
      ,0x71  => gettext('Performing Arts')
      ,0x72  => gettext('Fine Arts')
      ,0x73  => gettext('Religion')
      ,0x74  => gettext('Popular Culture/Traditional Arts')
      ,0x75  => gettext('Literature')
      ,0x76  => gettext('Film/Cinema')
      ,0x77  => gettext('Experimental Film/Video')
      ,0x78  => gettext('Broadcasting/Press')
      ,0x79  => gettext('New Media')
      ,0x7A  => gettext('Arts/Culture Magazine')
      ,0x7B  => gettext('Fashion')
#     ,0x7C to 0x7E reserved for future use
#     ,0x7F  => user defined

      ,0x8   => gettext('Social/Political/Economics')
      ,0x80  => gettext('Social/Political/Economics')
      ,0x81  => gettext('Magazine/Report/Documentary')
      ,0x82  => gettext('Economics/Social Advisory')
      ,0x83  => gettext('Remarkable People')
#     ,0x84 to 0x8E reserved for future use
#     ,0x8F  => user defined

      ,0x9   => gettext('Education/Science/Factual')
      ,0x90  => gettext('Education/Science/Factual')
      ,0x91  => gettext('Nature/Animals/Environment')
      ,0x92  => gettext('Technology/Natural Sciences')
      ,0x93  => gettext('Medicine/Physiology/Psychology')
      ,0x94  => gettext('Foreign Countries/Expeditions')
      ,0x95  => gettext('Social/Spiritual Sciences')
      ,0x96  => gettext('Further Education')
      ,0x97  => gettext('Languages')
#     ,0x98 to 0x9E reserved for future use
#     ,0x9F  => user defined

      ,0xA   => gettext('Leisure/Hobbies')
      ,0xA0  => gettext('Leisure/Hobbies')
      ,0xA1  => gettext('Tourism/Travel')
      ,0xA2  => gettext('Handicraft')
      ,0xA3  => gettext('Motoring')
      ,0xA4  => gettext('Fitness & Health')
      ,0xA5  => gettext('Cooking')
      ,0xA6  => gettext('Advertisement/Shopping')
      ,0xA7  => gettext('Gardening')
#     ,0xA8 to 0xAE reserved for future use
#     ,0xAF  => user defined

      ,0xB   => gettext('Special characteristics')
      ,0xB0  => gettext('Original Language')
      ,0xB1  => gettext('Black & White')
      ,0xB2  => gettext('Unpublished')
      ,0xB3  => gettext('Live Broadcast')
#     ,0xB4 to 0xBE reserved for future use
#     ,0xBF  => user defined

#     ,0xC0 to 0xEF reserved for future use
#     ,0xF0 to 0xFF user defined 
      };

      my $description;
      
      $description = $translate->{$content}
          if(exists $translate->{$content});

      unless($description) {
        $description = $translate->{($content & 0x0F) >> 8 }
            if(exists $translate->{($content & 0x0F) >> 8 });
      }

      return $description;
}

sub opensearch {
    my $self = shift || return error('No object defined!');
    my $console = shift || return error('No console defined!');
    my $config = shift || return error('No config defined!');

    return $console->err(gettext("Sorry, feature is'nt supported"))
      if ($console->{TYP} ne 'HTML');

    my $params = {};
    $console->out( $console->parseTemplateFile("opensearch", {}, $params, $console->{call})
                   , "application/opensearchdescription+xml" );
}

1;