check for bogus *.TXT databases (with zero length or 0 records) and
[webpac] / all2xml.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use OpenIsis;
5 use Getopt::Std;
6 use Data::Dumper;
7 use XML::Simple;
8 use Text::Unaccent 1.02;        # 1.01 won't compile on my platform,
9 use Text::Iconv;
10 use Config::IniFiles;
11 use Encode;
12
13 $|=1;
14
15 my $config_file = $0;
16 $config_file =~ s/\.pl$/.conf/;
17 die "FATAL: can't find configuration file '$config_file'" if (! -e $config_file);
18
19 my $config;
20
21 #use index_DBI;         # default DBI module for index
22 use index_DBI_cache;    # faster DBI module using memory cache
23 my $index;
24
25 my %opts;
26
27 # usage:
28 #       -d directory name
29 #       -m multiple directories
30 #       -q quiet
31 #       -s run swish
32
33 getopts('d:m:qs', \%opts);
34
35 my $path;       # this is name of database
36
37 Text::Iconv->raise_error(0);     # Conversion errors don't raise exceptions
38
39 # this is encoding of all files on disk, including import_xml/*.xml file and
40 # filter/*.pm files! It will be used to store strings in perl internally!
41 my $codepage = 'ISO-8859-2';
42
43 my $utf2cp = Text::Iconv->new('UTF-8',$codepage);
44 # this function will convert data from XML files to local encoding
45 sub x {
46         return $utf2cp->convert($_[0]);
47 }
48
49 # decode isis/excel or other import codepage
50 my $import2cp;
51
52 # outgoing xml must be in UTF-8
53 my $cp2utf = Text::Iconv->new($codepage,'UTF-8');
54
55 # mapping between data type and tag which specify
56 # format in XML file
57 my %type2tag = (
58         'isis' => 'isis',
59         'excel' => 'column',
60         'marc' => 'marc',
61         'feed' => 'feed'
62 );
63
64 sub data2xml {
65
66         use xmlify;
67
68         my $type = shift @_;
69         my $row = shift @_;
70         my $add_xml = shift @_;
71         # needed to read values from configuration file
72         my $cfg = shift @_;
73         my $database = shift @_;
74
75         my $xml;
76
77         use parse_format;
78
79         my $html = "";          # html formatted display output
80
81         my %field_usage;        # counter for usage of each field
82
83         # sort subrouting using order="" attribute
84         sub by_order {
85                 my $va = $config->{indexer}->{$a}->{order} ||
86                         $config->{indexer}->{$a};
87                 my $vb = $config->{indexer}->{$b}->{order} ||
88                         $config->{indexer}->{$b};
89
90                 return $va <=> $vb;
91         }
92
93         foreach my $field (sort by_order keys %{$config->{indexer}}) {
94
95                 $field=x($field);
96                 $field_usage{$field}++;
97
98                 my $swish_data = "";
99                 my $display_data = "";
100                 my $line_delimiter;
101
102                 my ($swish,$display);
103
104                 my $tag = $type2tag{$type} || die "can't find which tag to use for type $type";
105                 foreach my $x (@{$config->{indexer}->{$field}->{$tag}}) {
106
107                         my $format = x($x->{content});
108                         my $delimiter = x($x->{delimiter}) || ' ';
109
110                         my $repeat_off = 0;             # repeatable offset
111
112                         my ($s,$d,$i) = (1,1,0);        # swish, display default
113                         $s = 0 if (lc($x->{type}) eq "display");
114                         $d = 0 if (lc($x->{type}) eq "swish");
115                         ($s,$d,$i) = (0,0,1) if (lc($x->{type}) eq "index");
116
117                         # what will separate last line from this one?
118                         if ($display_data && $x->{append} && $x->{append} eq "1") {
119                                 $line_delimiter = ' ';
120                         } elsif ($display_data) {
121                                 $line_delimiter = '<br/>';
122                         }
123
124                         # init vars so that we go into while...
125                         ($swish,$display) = (1,1);
126
127                         # placeholder for all repeatable entries for index
128                         my @index_data;
129                         my $index_filter;
130
131                         # while because of repeatable fields
132                         while ($swish || $display) {
133                                 ($swish,$display) = parse_format($type, $format,$row,$repeat_off++,$import2cp);
134                                 if ($repeat_off > 1000) {
135                                         print STDERR "loop (more than 1000 repeatable fields) deteced in $row, $format\n";
136                                         last;
137                                 }
138                                 
139                                 # filter="name" ; filter this field through
140                                 # filter/[name].pm
141                                 my $filter = $x->{filter};
142                                 if ($filter) {
143                                         require "filter/".$filter.".pm";
144                                 }
145                                 # type="swish" ; field for swish
146                                 if ($s && $swish) {
147                                         if ($filter) {
148                                                 no strict 'refs';
149                                                 $swish_data .= join(" ",&$filter($swish));
150                                         } else {
151                                                 $swish_data .= $swish;
152                                         }
153                                 }
154
155                                 # type="display" ; field for display
156                                 if ($d && $display) {
157                                         if ($line_delimiter && $display_data) {
158                                                 $display_data .= $line_delimiter;
159                                                 undef $line_delimiter;
160                                         }
161                                         if ($filter) {
162                                                 no strict 'refs';
163                                                 $display_data .= join($delimiter,&$filter($display));
164                                         } else {
165                                                 if ($display_data) {
166                                                         $display_data .= $delimiter.$display;
167                                                 } else {
168                                                         $display_data .= $display;
169                                                 }
170                                         }
171                                 }
172                                                 
173                                 # type="index" ; insert into index
174                                 if ($i && $display) {
175                                         push @index_data, $display;
176                                         $index_filter = $filter if ($filter);
177                                 }
178                         }
179
180                         # fill data in index
181                         if (@index_data) {
182                                 if ($index_filter) {
183                                         no strict 'refs';
184                                         foreach my $d (&$index_filter(@index_data)) {
185                                                 $index->insert($field, $d, $path);
186                                         }
187                                 } else {
188                                         foreach my $d (@index_data) {
189                                                 $index->insert($field, $d, $path);
190                                         }
191                                 }
192                         }
193                 }
194
195                 # now try to parse variables from configuration file
196                 foreach my $x (@{$config->{indexer}->{$field}->{'config'}}) {
197
198                         my $delimiter = x($x->{delimiter}) || ' ';
199                         my $val = $cfg->val($database, x($x->{content}));
200
201                         my ($s,$d,$i) = (1,1,0);        # swish, display default
202                         $s = 0 if (lc($x->{type}) eq "display");
203                         $d = 0 if (lc($x->{type}) eq "swish");
204                         ($s,$d,$i) = (0,0,1) if (lc($x->{type}) eq "index");
205
206                         if ($val) {
207                                 $display_data .= $delimiter.$val if ($d);
208                                 $swish_data .= $val if ($s);
209                                 $index->insert($field, $val, $path) if ($i);
210                         }
211
212                 }
213
214
215                 if ($display_data) {
216
217                         if ($field eq "headline") {
218                                 $xml .= xmlify("headline", $display_data);
219                         } else {
220
221                                 # find field name (signular, plural)
222                                 my $field_name = "";
223                                 if ($config->{indexer}->{$field}->{name_singular} && $field_usage{$field} == 1) {
224                                         $field_name = $config->{indexer}->{$field}->{name_singular}."#-#";
225                                 } elsif ($config->{indexer}->{$field}->{name_plural}) {
226                                         $field_name = $config->{indexer}->{$field}->{name_plural}."#-#";
227                                 } elsif ($config->{indexer}->{$field}->{name}) {
228                                         $field_name = $config->{indexer}->{$field}->{name}."#-#";
229                                 } else {
230                                         print STDERR "WARNING: field '$field' doesn't have 'name' attribute!";
231                                 }
232                                 if ($field_name) {
233                                         $html .= x($field_name);
234                                 }
235                                 $html .= $display_data."###\n";
236                         }
237                 }
238                 if ($swish_data) {
239                         # remove extra spaces
240                         $swish_data =~ s/ +/ /g;
241                         $swish_data =~ s/ +$//g;
242
243                         $xml .= xmlify($field."_swish", unac_string($codepage,$swish_data));
244                 }
245
246
247         }
248
249         # dump formatted output in <html>
250         if ($html) {
251                 #$xml .= xmlify("html",$html);
252                 $xml .= "<html><![CDATA[ $html ]]></html>";
253         }
254         
255         if ($xml) {
256                 $xml .= $add_xml if ($add_xml);
257                 return "<xml>\n$xml</xml>\n";
258         } else {
259                 return;
260         }
261 }
262
263 ##########################################################################
264
265 # read configuration for this script
266 my $cfg = new Config::IniFiles( -file => $config_file );
267
268 # read global.conf configuration
269 my $cfg_global = new Config::IniFiles( -file => 'global.conf' );
270
271 # open index
272 $index = new index_DBI(
273                 $cfg_global->val('global', 'dbi_dbd'),
274                 $cfg_global->val('global', 'dbi_dsn'),
275                 $cfg_global->val('global', 'dbi_user'),
276                 $cfg_global->val('global', 'dbi_passwd') || '',
277         );
278
279 my $show_progress = $cfg_global->val('global', 'show_progress');
280
281 foreach my $database ($cfg->Sections) {
282
283         my $type = lc($cfg -> val($database, 'type')) || die "$database doesn't have 'type' defined";
284         my $add_xml = $cfg -> val($database, 'xml');    # optional
285
286 print STDERR "reading ./import_xml/$type.xml\n";
287
288         # extract just type basic
289         my $type_base = $type;
290         $type_base =~ s/_.+$//g;
291
292         $config=XMLin("./import_xml/$type.xml", forcearray => [ $type2tag{$type_base}, 'config' ], forcecontent => 1);
293
294         # output current progress indicator
295         my $last_p = 0;
296         sub progress {
297                 return if (! $show_progress);
298                 my $current = shift;
299                 my $total = shift || 1;
300                 my $p = int($current * 100 / $total);
301                 if ($p != $last_p) {
302                         printf STDERR ("%5d / %5d [%-51s] %-2d %% \r",$current,$total,"=" x ($p/2).">", $p );
303                         $last_p = $p;
304                 }
305         }
306
307         my $fake_dir = 1;
308         sub fakeprogress {
309                 return if (! $show_progress);
310                 my $current = shift @_;
311
312                 my @ind = ('-','\\','|','/','-','\\','|','/', '-');
313
314                 $last_p += $fake_dir;
315                 $fake_dir = -$fake_dir if ($last_p > 1000 || $last_p < 0);
316                 if ($last_p % 10 == 0) {
317                         printf STDERR ("%5d / %5s [%-51s]\r",$current,"?"," " x ($last_p/20).$ind[($last_p/20) % $#ind]);
318                 }
319         }
320
321         # now read database
322 print STDERR "using: $type...\n";
323
324         if ($type_base eq "isis") {
325
326                 my $isis_db = $cfg -> val($database, 'isis_db') || die "$database doesn't have 'isis_db' defined!";
327
328                 $import2cp = Text::Iconv->new($config->{isis_codepage},$codepage);
329                 my $db = OpenIsis::open( $isis_db );
330
331                 # check if .txt database for OpenIsis is zero length,
332                 # if so, erase it and re-open database
333                 sub check_txt_db {
334                         my $isis_db = shift || die "need isis database name";
335                         if (-e $isis_db.".TXT") {
336                                 print STDERR "WARNING: removing .txt OpenIsis database...\n";
337                                 unlink $isis_db.".TXT" || warn "unlink error on '$isis_db.TXT': $!";
338                                 my $db = OpenIsis::open( $isis_db );
339                                 return $db;
340                         }
341                 }
342
343                 # EOF error
344                 if ($db == -1) {
345                         $db = check_txt_db($isis_db);
346                         if (! $db) {
347                                 print STDERR "FATAL: OpenIsis can't open zero size file $isis_db\n";
348                                 next;
349                         }
350                 }
351
352                 # OpenIsis::ERR_BADF 
353                 if ($db == -4) {
354                         print STDERR "FATAL: OpenIsis can't find file $isis_db\n";
355                         next;
356                 # OpenIsis::ERR_IO
357                 } elsif ($db == -5) {
358                         print STDERR "FATAL: OpenIsis can't access file $isis_db\n";
359                         next;
360                 } elsif ($db < 0) {
361                         print STDERR "FATAL: OpenIsis unknown error $db with file $isis_db\n";
362                         next;
363                 }
364
365                 my $max_rowid = OpenIsis::maxRowid( $db );
366
367                 # if 0 records, try to rease isis .txt database
368                 if ($max_rowid == 0) {
369                         # force removal of database
370                         $db = check_txt_db($isis_db);
371                         $max_rowid = OpenIsis::maxRowid( $db );
372                 }
373
374                 print STDERR "Reading database: $isis_db [$max_rowid rows]\n";
375
376                 my $path = $database;
377
378                 for (my $row_id = 1; $row_id <= $max_rowid; $row_id++ ) {
379                         my $row = OpenIsis::read( $db, $row_id );
380                         if ($row && $row->{mfn}) {
381         
382                                 progress($row->{mfn}, $max_rowid);
383
384                                 my $swishpath = $path."#".int($row->{mfn});
385
386                                 if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
387                                         $xml = $cp2utf->convert($xml);
388                                         use bytes;      # as opposed to chars
389                                         print "Path-Name: $swishpath\n";
390                                         print "Content-Length: ".(length($xml)+1)."\n";
391                                         print "Document-Type: XML\n\n$xml\n";
392                                 }
393                         }
394                 }
395                 print STDERR "\n";
396
397         } elsif ($type_base eq "excel") {
398                 use Spreadsheet::ParseExcel;
399                 use Spreadsheet::ParseExcel::Utility qw(int2col);
400                 
401                 $import2cp = Text::Iconv->new($config->{excel_codepage},$codepage);
402                 my $excel_file = $cfg -> val($database, 'excel_file') || die "$database doesn't have 'excel_file' defined!";
403
404                 my $sheet = x($config->{sheet}) || die "no sheet in $type.xml";
405                 my $start_row = x($config->{start_row}) - 1 || die "no start_row in $type.xml";
406
407                 my $oBook = Spreadsheet::ParseExcel::Workbook->Parse($excel_file) || die "can't open Excel file '$excel_file'";
408
409                 my $sheet_nr = 0;
410                 foreach my $oWks (@{$oBook->{Worksheet}}) {
411                         #print STDERR "-- SHEET $sheet_nr:", $oWks->{Name}, "\n";
412                         last if ($oWks->{Name} eq $sheet);
413                         $sheet_nr++;
414                 }
415
416                 my $oWorksheet = $oBook->{Worksheet}[$sheet_nr];
417         
418                 print STDERR "using sheet: ",$oWorksheet->{Name},"\n";
419                 defined ($oWorksheet) || die "can't find sheet '$sheet' in $excel_file";
420                 my $end_row = x($config->{end_row}) || $oWorksheet->{MaxRow};
421
422                 for(my $iR = $start_row ; defined $end_row && $iR <= $end_row ; $iR++) {
423                         my $row;
424                         for(my $iC = $oWorksheet->{MinCol} ; defined $oWorksheet->{MaxCol} && $iC <= $oWorksheet->{MaxCol} ; $iC++) {
425                                 my $cell = $oWorksheet->{Cells}[$iR][$iC];
426                                 if ($cell) {
427                                         $row->{int2col($iC)} = $cell->Value;
428                                 }
429                         }
430
431                         progress($iR, $end_row);
432
433 #                       print "row[$iR/$end_row] ";
434 #                       foreach (keys %{$row}) {
435 #                               print "$_: ",$row->{$_},"\t";
436 #                       }
437 #                       print "\n";
438
439                         my $swishpath = $database."#".$iR;
440
441                         next if (! $row);
442
443                         if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
444                                 $xml = $cp2utf->convert($xml);
445                                 use bytes;      # as opposed to chars
446                                 print "Path-Name: $swishpath\n";
447                                 print "Content-Length: ".(length($xml)+1)."\n";
448                                 print "Document-Type: XML\n\n$xml\n";
449                         }
450                 }
451         } elsif ($type_base eq "marc") {
452
453                 use MARC;
454                 
455                 $import2cp = Text::Iconv->new($config->{marc_codepage},$codepage);
456                 my $marc_file = $cfg -> val($database, 'marc_file') || die "$database doesn't have 'marc_file' defined!";
457
458                 # optional argument is format
459                 my $format = x($config->{format}) || 'usmarc';
460
461                 print STDERR "Reading MARC file '$marc_file'\n";
462
463                 my $marc = new MARC;
464                 my $nr = $marc->openmarc({
465                                 file=>$marc_file, format=>$format
466                         }) || die "Can't open MARC file '$marc_file'";
467
468                 my $i=0;        # record nr.
469
470                 my $rec;
471
472                 while ($marc->nextmarc(1)) {
473
474                         # XXX
475                         fakeprogress($i++);
476
477                         my $swishpath = $database."#".$i;
478
479                         if (my $xml = data2xml($type_base,$marc,$add_xml,$cfg,$database)) {
480                                 $xml = $cp2utf->convert($xml);
481                                 use bytes;      # as opposed to chars
482                                 print "Path-Name: $swishpath\n";
483                                 print "Content-Length: ".(length($xml)+1)."\n";
484                                 print "Document-Type: XML\n\n$xml\n";
485                         }
486                 }
487         } elsif ($type_base eq "feed") {
488
489                 $import2cp = Text::Iconv->new($config->{feed_codepage},$codepage);
490                 my $prog = x($config->{prog}) || die "$database doesn't have 'prog' defined!";
491
492                 print STDERR "Reading feed from program '$prog'\n";
493
494                 open(FEED,"feeds/$prog |") || die "can't start $prog: $!";
495
496                 my $i=1;        # record nr.
497
498                 my $data;
499                 my $line=1;
500
501                 while (<FEED>) {
502                         chomp;
503
504                         if (/^$/) {
505                                 my $swishpath = $database."#".$i++;
506
507                                 if (my $xml = data2xml($type_base,$data,$add_xml,$cfg,$database)) {
508                                         $xml = $cp2utf->convert($xml);
509                                         use bytes;      # as opposed to chars
510                                         print "Path-Name: $swishpath\n";
511                                         print "Content-Length: ".(length($xml)+1)."\n";
512                                         print "Document-Type: XML\n\n$xml\n";
513                                 }
514                                 $line = 1;
515                                 $data = {};
516                                 next;
517                         }
518
519                         $line = $1 if (s/^(\d+):\s*//);
520                         $data->{$line++} = $_;
521
522                         fakeprogress($i);
523
524                 }
525         }
526 }
527
528 # call this to commit index
529 $index->close;
530
531 1;
532 __END__
533 ##########################################################################
534
535 =head1 NAME
536
537 all2xml.pl - read various file formats and dump XML for SWISH-E
538
539 =head1 DESCRIPTION
540
541 This command will read ISIS data file using OpenIsis perl module, MARC
542 records using MARC module and optionally Micro$oft Excel files to
543 create one XML file for usage with I<SWISH-E> indexer. Dispite it's name,
544 this script B<isn't general xml generator> from isis files (isis allready
545 has something like that). Output of this script is tailor-made for SWISH-E.
546
547 =head1 BUGS
548
549 Documentation is really lacking. However, in true Open Source spirit, source
550 is best documentation. I even made considerable effort to comment parts
551 which are not intuitively clear, so...
552
553 =head1 AUTHOR
554
555 Dobrica Pavlinusic <dpavlin@rot13.org>
556
557 =head1 COPYRIGHT
558
559 GNU Public License (GPL) v2 or later
560
561 =head1 SEE ALSO
562
563 SWISH-E web site at http://www.swish-e.org
564
565 =cut