ported r254 from hidra branch
[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 #use GDBM_File;
13 use Fcntl;      # for O_RDWR
14 use TDB_File;
15
16 $|=1;
17
18 my $config_file = $0;
19 $config_file =~ s/\.pl$/.conf/;
20 die "FATAL: can't find configuration file '$config_file'" if (! -e $config_file);
21
22 my $config;
23
24 #use index_DBI;         # default DBI module for index
25 use index_DBI_cache;    # faster DBI module using memory cache
26 my $index;
27
28 my %opts;
29
30 # usage:
31 #       -d directory name
32 #       -m multiple directories
33 #       -q quiet
34 #       -s run swish
35
36 getopts('d:m:qs', \%opts);
37
38 my $path;       # this is name of database
39
40 Text::Iconv->raise_error(0);     # Conversion errors don't raise exceptions
41
42 # this is encoding of all files on disk, including import_xml/*.xml file and
43 # filter/*.pm files! It will be used to store strings in perl internally!
44 my $codepage = 'ISO-8859-2';
45
46 my $utf2cp = Text::Iconv->new('UTF-8',$codepage);
47 # this function will convert data from XML files to local encoding
48 sub x {
49         return $utf2cp->convert($_[0]);
50 }
51
52 # decode isis/excel or other import codepage
53 my $import2cp;
54
55 # outgoing xml must be in UTF-8
56 my $cp2utf = Text::Iconv->new($codepage,'UTF-8');
57
58 # mapping between data type and tag which specify
59 # format in XML file
60 my %type2tag = (
61         'isis' => 'isis',
62         'excel' => 'column',
63         'marc' => 'marc',
64         'feed' => 'feed'
65 );
66
67 my $cache;      # for cacheing
68
69 # lookup hash (tied to file)
70 my %lhash;
71 # this option will cache all lookup entries in memory.
72 # if you are tight on memory, turn this off
73 my $use_lhash_cache = 1;
74
75 my $last_field_name;    # cache to prevent repeated fields
76
77 sub data2xml {
78
79         use xmlify;
80
81         my $type = shift @_;
82         my $row = shift @_;
83         my $add_xml = shift @_;
84         # needed to read values from configuration file
85         my $cfg = shift @_;
86         my $database = shift @_;
87
88         my $xml;
89
90         use parse_format;
91
92         my $html = "";          # html formatted display output
93
94         my %field_usage;        # counter for usage of each field
95
96         # sort subrouting using order="" attribute
97         sub by_order {
98                 my $va = $config->{indexer}->{$a}->{order} ||
99                         $config->{indexer}->{$a};
100                 my $vb = $config->{indexer}->{$b}->{order} ||
101                         $config->{indexer}->{$b};
102
103                 return $va <=> $vb;
104         }
105
106         my @sorted_tags;
107         if ($cache->{tags_by_order}) {
108                 @sorted_tags = @{$cache->{tags_by_order}};
109         } else {
110                 @sorted_tags = sort by_order keys %{$config->{indexer}};
111                 $cache->{tags_by_order} = \@sorted_tags;
112         }
113
114         # lookup key
115         my $lookup_key;
116
117         # cache for field in pages
118         delete $cache->{display_data};
119         delete $cache->{swish_data};
120         delete $cache->{swish_exact_data};
121         delete $cache->{index_data};
122         delete $cache->{index_delimiter};
123         my @page_fields;        # names of fields
124
125
126         # subs used to produce output
127
128         sub get_field_name($$$) {
129                 my ($config,$field,$field_usage) = @_;
130
131                 # find field name (signular, plural)
132                 my $field_name = "";
133                 if ($config->{indexer}->{$field}->{name_singular} && $field_usage == 1) {
134                         $field_name = $config->{indexer}->{$field}->{name_singular};
135                 } elsif ($config->{indexer}->{$field}->{name_plural}) {
136                         $field_name = $config->{indexer}->{$field}->{name_plural};
137                 } elsif ($config->{indexer}->{$field}->{name}) {
138                         $field_name = $config->{indexer}->{$field}->{name};
139                 } else {
140                         print STDERR "WARNING: field '$field' doesn't have 'name' attribute!";
141                 }
142                 if ($field_name) {
143                         if (! $last_field_name) {
144                                 $last_field_name = x($field_name);
145                                 return $last_field_name;
146                         } elsif ($field_name ne $last_field_name) {
147                                 $last_field_name = x($field_name);
148                                 return $last_field_name;
149                         }
150                 }
151         }
152
153
154         # begin real work: go field by field
155         foreach my $field (@sorted_tags) {
156
157                 $field=x($field);
158                 $field_usage{$field}++;
159
160                 my $swish_data = "";
161                 my $swish_exact_data = "";
162                 my $display_data = "";
163                 my @index_data;
164                 my $line_delimiter;
165
166                 my ($swish,$display);
167
168                 my $tag = $type2tag{$type} || die "can't find which tag to use for type $type";
169
170                 # is this field page-by-page?
171                 my $iterate_by_page = $config->{indexer}->{$field}->{iterate_by_page};
172                 push @page_fields,$field if ($iterate_by_page);
173                 my %page_max = ();
174                 # default line_delimiter if using
175                 my $page_line_delimiter = $config->{indexer}->{$field}->{page_line_delimiter} || '<br/>';
176                 $cache->{index_delimiter}->{$field} = $config->{indexer}->{$field}->{index_delimiter};
177
178                 my $format_name = $config->{indexer}->{$field}->{format_name};
179                 my $format_delimiter = $config->{indexer}->{$field}->{format_delimiter};
180                 if ($format_name && $format_delimiter) {
181                         $cache->{format}->{$field}->{format_name} = $format_name;
182                         $cache->{format}->{$field}->{format_delimiter} = $format_delimiter;
183                 }
184
185                 foreach my $x (@{$config->{indexer}->{$field}->{$tag}}) {
186
187                         my $format = x($x->{content});
188                         my $delimiter = x($x->{delimiter}) || ' ';
189
190                         my $repeat_off = 0;     # init repeatable offset
191
192                         # swish, swish_exact, display, index, index_lookup
193                         # swish and display defaults
194                         my ($s,$se,$d,$i,$il) = (1,0,1,0,0);
195                         $s = 0 if (lc($x->{type}) eq "display");
196                         $d = 0 if (lc($x->{type}) eq "swish");
197                         ($s,$se,$d,$i) = (0,1,0,1) if (lc($x->{type}) eq "index");
198                         ($s,$se,$d,$i) = (0,1,0,0) if (lc($x->{type}) eq "swish_exact");
199                         ($s,$se,$d,$i,$il) = (0,1,0,0,1) if (lc($x->{type}) =~ /^lookup/);
200
201                         # what will separate last line from this one?
202                         if ($display_data && $x->{append}) {
203                                 $line_delimiter = ' ';
204                         } elsif ($display_data) {
205                                 $line_delimiter = '<br/>';
206                         }
207
208                         # init vars so that we go into while...
209                         ($swish,$display) = (1,1);
210
211                         # placeholder for all repeatable entries for index
212
213                         sub chk_eval($) {
214                                 my $data = shift;
215                                 return if (! defined($data));
216                                 if ($data && $data =~ s/\s*eval{([^}]+)}\s*//) {
217                                         if (eval "$1") {
218                                                 return $data;
219                                         } else {
220                                                 return undef;
221                                         }
222                                 } else {
223                                         return $data;
224                                 }
225                         }
226
227                         sub mkformat($$) {
228                                 my $x = shift || die "mkformat needs tag reference";
229                                 my $data = shift || return;
230                                 my $format_name = x($x->{format_name}) || return chk_eval($data);
231                                 my $fmt = x($config->{format}->{$format_name}->{content}) || die "<format name=\"$format_name\"> is not defined!";
232                                 my $format_delimiter = x($x->{format_delimiter});
233                                 my @data;
234                                 if ($format_delimiter) {
235                                         @data = split(/$format_delimiter/,$data);
236                                 } else {
237                                         push @data,$data;
238                                 }
239
240                                 if ($fmt) {
241                                         my $nr = scalar $fmt =~ s/%s/%s/g;
242                                         if (($#data+1) == $nr) {
243                                                 return chk_eval(sprintf($fmt,@data));
244                                         } else {
245                                                 #print STDERR "mkformat: [$data] can't be split on [$format_delimiter] to $nr fields!\n";
246                                                 return chk_eval($data);
247                                         }
248                                 } else {
249                                         print STDERR "usage of link '$format_name' without defined format (<link> tag)\n";
250                                 }
251                         }
252
253                         # while because of repeatable fields
254                         while ($swish || $display) {
255                                 my $page = $repeat_off;
256                                 $page_max{$field} = $page if ($iterate_by_page && $page > ($page_max{$field} || 0));
257                                 ($swish,$display) = parse_format($type, $format,$row,$repeat_off++,$import2cp);
258                                 if ($repeat_off > 1000) {
259                                         print STDERR "loop (more than 1000 repeatable fields) deteced in $row, $format\n";
260                                         last;
261                                 }
262
263                                 # is this field is lookup?
264                                 if ($display && $x->{lookup}) {
265                                         my $null = "<!-- null -->";
266                                         if ($use_lhash_cache) {
267                                                 if (!defined($cache->{lhash}->{$display})) {
268                                                         my $new_display = $lhash{$display};
269                                                         if (defined($new_display)) {
270 #print STDERR "lookup cache store '$display' = '$new_display'\n";
271                                                                 $display = $new_display;
272                                                                 $cache->{lhash}->{$display} = $new_display;
273                                                         } else {
274 #                                                               print STDERR "WARNING: lookup for '$display' didn't find anything.\n";
275                                                                 $display = "";
276                                                                 $cache->{lhash}->{$display} = $null;
277                                                         }
278                                                 } else {
279                                                         $display = $cache->{lhash}->{$display};
280                                                 }
281                                         } else {
282                                                 $display = $lhash{$display} || $null;
283                                         }
284                                 }
285
286                                 # filter="name" ; filter this field through
287                                 # filter/[name].pm
288                                 my $filter = $x->{filter};
289                                 if ($filter && !$cache->{filter_loaded}->{$filter}) {
290                                         require "filter/".$filter.".pm";
291                                         $cache->{filter_loaded}->{$filter}++;
292                                 }
293                                 # type="swish" ; field for swish
294                                 if ($swish) {
295                                         my $tmp;
296                                         if ($filter && ($s || $se)) {
297                                                 no strict 'refs';
298                                                 $tmp = join(" ",&$filter($swish)) if ($s || $se);
299                                         }
300
301                                         $tmp = chk_eval($tmp);
302                                         $swish_data .= $tmp if ($s && $tmp);
303                                         $swish_exact_data .= "xxbxx $tmp xxexx " if ($tmp && $tmp ne "" && $se);
304                                 }
305
306                                 # type="display" ; field for display
307                                 if ($d && $display) {
308                                         my $ldel = $delimiter;
309                                         if ($line_delimiter && $display_data) {
310                                                 $ldel = $line_delimiter;
311                                         }
312                                         if ($filter) {
313                                                 no strict 'refs';
314                                                 my @arr;
315                                                 foreach my $tmp (&$filter($display)) {
316                                                         my $tmp2 = mkformat($x,$tmp);
317                                                         push @arr,$tmp2 if ($tmp2);
318                                                 }
319                                                 $display_data .= $ldel if ($display_data && @arr);
320                                                 $display_data .= join($delimiter,@arr);
321                                         } else {
322                                                 $display_data .= $ldel if ($display_data);
323                                                 my $tmp = mkformat($x,$display);
324                                                 $display_data .= $tmp if ($tmp);
325                                         }
326                                 }
327                                                 
328                                 # type="index" ; insert into index
329                                 my $idisplay;
330                                 if ($i && $display) {
331                                         $idisplay = $display;
332                                         if ($filter) {
333                                                 no strict 'refs';
334                                                 $idisplay = &$filter($idisplay);
335                                         }
336                                         $idisplay = chk_eval($idisplay);
337                                         push @index_data, $idisplay if ($idisplay && !$iterate_by_page);
338                                 }
339
340                                 # store fields in lookup
341                                 if ($il && $display) {
342                                         if (lc($x->{type}) eq "lookup_key") {
343                                                 if ($lookup_key) {
344                                                         print STDERR "WARNING: try to redefine lookup_key (keys shouldn't be repeatable fields!)";
345                                                 } else {
346                                                         if ($filter) {
347                                                                 no strict 'refs';
348                                                                 $lookup_key = &$filter($display);
349                                                         } else {
350                                                                 $lookup_key = $display;
351                                                         }
352                                                 }
353                                         } elsif (lc($x->{type}) eq "lookup_val") {
354                                                 if ($lookup_key) {
355                                                         if ($filter) {
356                                                                 no strict 'refs';
357                                                                 $lhash{$lookup_key} = &$filter($display);
358                                                         } else {
359                                                                 $lhash{$lookup_key} = $display;
360                                                         }
361                                                 } else {
362                                                         print STDERR "WARNING: no lookup_key defined for  '$display'?";
363                                                 }
364                                         }
365
366                                 }
367
368                                 # store data for page-by-page repeatable fields
369                                 if ($iterate_by_page) {
370                                         sub iterate_fld($$$$$$) {
371                                                 my ($cache,$what,$field,$page,$data,$append) = @_;
372                                                 return if (!$data);
373
374                                                 my $ldel = $page_line_delimiter;
375                                                 $ldel = " " if ($append);
376 #print STDERR "line delimiter: ",Dumper($ldel) if ($ldel);
377                                                 if (! $cache->{$what}->{$field}->[$page]) {
378                                                         $cache->{$what}->{$field}->[$page] = $data;
379                                                 } else {
380                                                         $cache->{$what}->{$field}->[$page] .= $ldel.$data;
381                                                 }
382                                         }
383
384                                         if ($display_data) {
385                                                 iterate_fld($cache,'display_data',$field,$page,$display_data,$x->{append});
386                                         }
387                                                 $display_data = "";
388                                         if ($swish_data) {
389                                                 iterate_fld($cache,'swish_data',$field,$page,$swish_data,$x->{append});
390                                                 $swish_data = "";
391                                         }
392                                         if ($swish_exact_data) {
393                                                 iterate_fld($cache,'swish_exact_data',$field,$page,$swish_exact_data,$x->{append});
394                                                 $swish_exact_data = "";
395                                         }
396
397                                         if ($idisplay) {
398                                                 my $ldel=$page_line_delimiter;
399                                                 my @index_data;
400                                                 if ($cache->{index_data}->{$field}->[$page]) {
401
402                                                         @index_data = @{$cache->{index_data}->{$field}->[$page]};
403                                                 }
404                                                 if ($x->{append}) {
405                                                         if (@index_data) {
406                                                                 $index_data[$#index_data] .= $idisplay;
407                                                         } else {
408                                                                 push @index_data, $idisplay;
409                                                         }
410                                                 } else {
411                                                         push @index_data, $idisplay;
412                                                 }
413                                                 $idisplay = "";
414                                                 @{$cache->{index_data}->{$field}->[$page]} = @index_data;
415                                         }
416                                 }
417                         }
418
419                         if (! $iterate_by_page) {
420                                 my $idel = $x->{index_delimiter};
421                                 # fill data in index
422                                 foreach my $tmp (@index_data) {
423                                         my $i = $d = $tmp;
424                                         if ($idel && $tmp =~ m/$idel/) {
425                                                 ($i,$d) = split(/$idel/,$tmp);
426                                         }
427                                         $index->insert($field, $i, $d, $path);
428                                 }
429                                 @index_data = ();
430                         }
431                 }
432
433                 # now try to parse variables from configuration file
434                 foreach my $x (@{$config->{indexer}->{$field}->{'config'}}) {
435
436                         my $delimiter = x($x->{delimiter}) || ' ';
437                         my $val = $cfg->val($database, x($x->{content}));
438
439                         my ($s,$d,$i) = (1,1,0);        # swish, display default
440                         $s = 0 if (lc($x->{type}) eq "display");
441                         $d = 0 if (lc($x->{type}) eq "swish");
442                         # no support for swish exact in config.
443                         # IMHO, it's useless
444                         ($s,$d,$i) = (0,0,1) if (lc($x->{type}) eq "index");
445
446                         if ($val) {
447                                 $display_data .= $delimiter.$val if ($d);
448                                 $swish_data .= $val if ($s);
449                                 $index->insert($field, $val, $path) if ($i);
450                         }
451
452                         if ($iterate_by_page) {
453                                 # FIXME data from config tag will appear just
454                                 # on first page!!!
455                                 my $page = 0;
456                                 if ($display_data) {
457                                         $cache->{display_data}->{$field}->[$page] = $display_data;
458                                         $display_data = "";
459                                 }
460                                 if ($swish_data) {
461                                         $cache->{swish_data}->{$field}->[$page] = $swish_data;
462                                         $swish_data = "";
463                                 }
464                                 if ($swish_exact_data) {
465                                         $cache->{swish_exact_data}->{$field}->[$page] = $swish_exact_data;
466                                         $swish_exact_data = "";
467                                 }
468                         }
469                 }
470
471                 # save data page-by-page
472                 foreach my $field (@page_fields) {
473                         my $nr_pages = $page_max{$field} || next;
474 #print STDERR "field '$field' iterate over ",($nr_pages || 0)," pages...\n";
475 #print STDERR Dumper($cache->{display_data});
476                         for (my $page=0; $page <= $nr_pages; $page++) {
477                                 my $display_data;
478                                 if ($cache->{format}->{$field}) {
479                                         my $tmp = mkformat($cache->{format}->{$field},$cache->{display_data}->{$field}->[$page]);
480                                         $display_data=$tmp if ($tmp);
481                                 } else {
482                                         $display_data = $cache->{display_data}->{$field}->[$page];
483                                 }
484                                 if ($display_data) { # default
485                                         if ($field eq "headline") {
486                                                 $xml .= xmlify("headline", $display_data);
487                                         } else {
488
489                                                 # fallback to empty field name if needed
490                                                 $html .= get_field_name($config,$field,$field_usage{$field}) || '';
491                                                 $html .= "#-#".$display_data."###\n";
492                                         }
493                                 }
494                                 
495                                 my $swish_data = $cache->{swish_data}->{$field}->[$page];
496                                 if ($swish_data) {
497                                         # remove extra spaces
498                                         $swish_data =~ s/ +/ /g;
499                                         $swish_data =~ s/ +$//g;
500
501                                         $xml .= xmlify($field."_swish", unac_string($codepage,$swish_data));
502                                 }
503
504                                 my $swish_exact_data = $cache->{swish_exact_data}->{$field}->[$page];
505                                 if ($swish_exact_data) {
506                                         $swish_exact_data =~ s/ +/ /g;
507                                         $swish_exact_data =~ s/ +$//g;
508
509                                         # add delimiters before and after word.
510                                         # That is required to produce exact match
511                                         $xml .= xmlify($field."_swish_exact", unac_string($codepage,$swish_exact_data));
512                                 }
513                                 
514                                 my $idel = $cache->{index_delimiter}->{$field};
515                                 foreach my $tmp (@{$cache->{index_data}->{$field}->[$page]}) {
516                                         my $i = $tmp;
517                                         my $d = $tmp;
518                                         if ($idel && $tmp =~ m/$idel/) {
519                                                 ($i,$d) = split(/$idel/,$tmp);
520                                         }
521                                         $index->insert($field, $i, $d, $path);
522 #print STDERR "index [$idel] $field: $i --> $d [$path]\n";
523                                 }
524                         }
525         
526                 }
527                 
528                 if (! $iterate_by_page) {
529                         if ($display_data) {
530                                 if ($field eq "headline") {
531                                         $xml .= xmlify("headline", $display_data);
532                                 } else {
533
534                                         # fallback to empty field name if needed
535                                         $html .= get_field_name($config,$field,$field_usage{$field}) || '';
536                                         $html .= "#-#".$display_data."###\n";
537                                 }
538                         }
539                         if ($swish_data) {
540                                 # remove extra spaces
541                                 $swish_data =~ s/ +/ /g;
542                                 $swish_data =~ s/ +$//g;
543
544                                 $xml .= xmlify($field."_swish", unac_string($codepage,$swish_data));
545                         }
546
547                         if ($swish_exact_data) {
548                                 $swish_exact_data =~ s/ +/ /g;
549                                 $swish_exact_data =~ s/ +$//g;
550
551                                 # add delimiters before and after word.
552                                 # That is required to produce exact match
553                                 $xml .= xmlify($field."_swish_exact", unac_string($codepage,$swish_exact_data));
554                         }
555                 }
556         }
557
558         # dump formatted output in <html>
559         if ($html) {
560                 #$xml .= xmlify("html",$html);
561                 $xml .= "<html><![CDATA[ $html ]]></html>";
562         }
563         
564         if ($xml) {
565                 $xml .= $add_xml if ($add_xml);
566                 return "<xml>\n$xml</xml>\n";
567         } else {
568                 return;
569         }
570 }
571
572 ##########################################################################
573
574 # read configuration for this script
575 my $cfg = new Config::IniFiles( -file => $config_file );
576
577 # read global.conf configuration
578 my $cfg_global = new Config::IniFiles( -file => 'global.conf' );
579
580 # open index
581 $index = new index_DBI(
582                 $cfg_global->val('global', 'dbi_dbd'),
583                 $cfg_global->val('global', 'dbi_dsn'),
584                 $cfg_global->val('global', 'dbi_user'),
585                 $cfg_global->val('global', 'dbi_passwd') || '',
586         );
587
588 my $show_progress = $cfg_global->val('global', 'show_progress');
589
590 my $unac_filter = $cfg_global->val('global', 'unac_filter');
591 if ($unac_filter) {
592         require $unac_filter;
593 }
594
595 foreach my $database ($cfg->Sections) {
596
597         my $type = lc($cfg -> val($database, 'type')) || die "$database doesn't have 'type' defined";
598         my $add_xml = $cfg -> val($database, 'xml');    # optional
599
600         # create new lookup file
601         my $lookup_file = $cfg -> val($database, 'lookup_newfile'); # optional
602         if ($lookup_file) {
603                 #tie %lhash, 'GDBM_File', $lookup_file, &GDBM_NEWDB, 0644;
604                 tie %lhash, 'TDB_File', $lookup_file, TDB_CLEAR_IF_FIRST, O_RDWR, 0644;
605                 print STDERR "creating lookup file '$lookup_file'\n";
606                 # delete memory cache for lookup file
607                 delete $cache->{lhash};
608         }
609
610         # open existing lookup file
611         $lookup_file = $cfg -> val($database, 'lookup_open'); # optional
612         if ($lookup_file) {
613                 #tie %lhash, 'GDBM_File', $lookup_file, &GDBM_READER, 0644;
614                 tie %lhash, 'TDB_File', $lookup_file, TDB_DEFAULT, O_RDWR, 0644;
615                 print STDERR "opening lookup file '$lookup_file'\n";
616         }
617
618 print STDERR "reading ./import_xml/$type.xml\n";
619
620         # extract just type basic
621         my $type_base = $type;
622         $type_base =~ s/_.+$//g;
623
624         $config=XMLin("./import_xml/$type.xml", forcearray => [ $type2tag{$type_base}, 'config', 'format' ], forcecontent => 1);
625
626         # output current progress indicator
627         my $last_p = 0;
628         sub progress {
629                 return if (! $show_progress);
630                 my $current = shift;
631                 my $total = shift || 1;
632                 my $p = int($current * 100 / $total);
633                 if ($p != $last_p) {
634                         printf STDERR ("%5d / %5d [%-51s] %-2d %% \r",$current,$total,"=" x ($p/2).">", $p );
635                         $last_p = $p;
636                 }
637         }
638
639         my $fake_dir = 1;
640         sub fakeprogress {
641                 return if (! $show_progress);
642                 my $current = shift @_;
643
644                 my @ind = ('-','\\','|','/','-','\\','|','/', '-');
645
646                 $last_p += $fake_dir;
647                 $fake_dir = -$fake_dir if ($last_p > 1000 || $last_p < 0);
648                 if ($last_p % 10 == 0) {
649                         printf STDERR ("%5d / %5s [%-51s]\r",$current,"?"," " x ($last_p/20).$ind[($last_p/20) % $#ind]);
650                 }
651         }
652
653         # now read database
654 print STDERR "using: $type...\n";
655
656         # erase cache for tags by order in this database
657         delete $cache->{tags_by_order};
658
659         if ($type_base eq "isis") {
660
661                 my $isis_db = $cfg -> val($database, 'isis_db') || die "$database doesn't have 'isis_db' defined!";
662
663                 $import2cp = Text::Iconv->new($config->{isis_codepage},$codepage);
664                 my $db = OpenIsis::open( $isis_db );
665
666                 # check if .txt database for OpenIsis is zero length,
667                 # if so, erase it and re-open database
668                 sub check_txt_db {
669                         my $isis_db = shift || die "need isis database name";
670                         my $reopen = 0;
671
672                         if (-e $isis_db.".TXT") {
673                                 print STDERR "WARNING: removing $isis_db.TXT OpenIsis database...\n";
674                                 unlink $isis_db.".TXT" || warn "FATAL: unlink error on '$isis_db.TXT': $!";
675                                 $reopen++;
676                         }
677                         if (-e $isis_db.".PTR") {
678                                 print STDERR "WARNING: removing $isis_db.PTR OpenIsis database...\n";
679                                 unlink $isis_db.".PTR" || warn "FATAL: unlink error on '$isis_db.PTR': $!";
680                                 $reopen++;
681                         }
682                         return OpenIsis::open( $isis_db ) if ($reopen);
683                 }
684
685                 # EOF error
686                 if ($db == -1) {
687                         $db = check_txt_db($isis_db);
688                         if ($db == -1) {
689                                 print STDERR "FATAL: OpenIsis can't open zero size file $isis_db\n";
690                                 next;
691                         }
692                 }
693
694                 # OpenIsis::ERR_BADF 
695                 if ($db == -4) {
696                         print STDERR "FATAL: OpenIsis can't find file $isis_db\n";
697                         next;
698                 # OpenIsis::ERR_IO
699                 } elsif ($db == -5) {
700                         print STDERR "FATAL: OpenIsis can't access file $isis_db\n";
701                         next;
702                 } elsif ($db < 0) {
703                         print STDERR "FATAL: OpenIsis unknown error $db with file $isis_db\n";
704                         next;
705                 }
706
707                 my $max_rowid = OpenIsis::maxRowid( $db );
708
709                 # if 0 records, try to rease isis .txt database
710                 if ($max_rowid == 0) {
711                         # force removal of database
712                         $db = check_txt_db($isis_db);
713                         $max_rowid = OpenIsis::maxRowid( $db );
714                 }
715
716                 print STDERR "Reading database: $isis_db [$max_rowid rows]\n";
717
718                 my $path = $database;
719
720                 for (my $row_id = 1; $row_id <= $max_rowid; $row_id++ ) {
721                         my $row = OpenIsis::read( $db, $row_id );
722                         if ($row && $row->{mfn}) {
723         
724                                 progress($row->{mfn}, $max_rowid);
725
726                                 my $swishpath = $path."#".int($row->{mfn});
727
728                                 if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
729                                         $xml = $cp2utf->convert($xml);
730                                         use bytes;      # as opposed to chars
731                                         print "Path-Name: $swishpath\n";
732                                         print "Content-Length: ".(length($xml)+1)."\n";
733                                         print "Document-Type: XML\n\n$xml\n";
734                                 }
735                         }
736                 }
737                 # for this to work with current version of OpenIsis (0.9.0)
738                 # you might need my patch from
739                 # http://www.rot13.org/~dpavlin/projects/openisis-0.9.0-perl_close.diff
740                 OpenIsis::close($db);
741                 print STDERR "\n";
742
743         } elsif ($type_base eq "excel") {
744                 require Spreadsheet::ParseExcel;
745                 require Spreadsheet::ParseExcel::Utility;
746                 import Spreadsheet::ParseExcel::Utility qw(int2col);
747                 
748                 $import2cp = Text::Iconv->new($config->{excel_codepage},$codepage);
749                 my $excel_file = $cfg -> val($database, 'excel_file') || die "$database doesn't have 'excel_file' defined!";
750
751                 my $sheet = x($config->{sheet}) || die "no sheet in $type.xml";
752                 my $start_row = x($config->{start_row}) - 1 || die "no start_row in $type.xml";
753
754                 my $oBook = Spreadsheet::ParseExcel::Workbook->Parse($excel_file) || die "can't open Excel file '$excel_file'";
755
756                 my $sheet_nr = 0;
757                 foreach my $oWks (@{$oBook->{Worksheet}}) {
758                         #print STDERR "-- SHEET $sheet_nr:", $oWks->{Name}, "\n";
759                         last if ($oWks->{Name} eq $sheet);
760                         $sheet_nr++;
761                 }
762
763                 my $oWorksheet = $oBook->{Worksheet}[$sheet_nr];
764         
765                 print STDERR "using sheet: ",$oWorksheet->{Name},"\n";
766                 defined ($oWorksheet) || die "can't find sheet '$sheet' in $excel_file";
767                 my $end_row = x($config->{end_row}) || $oWorksheet->{MaxRow};
768
769                 for(my $iR = $start_row ; defined $end_row && $iR <= $end_row ; $iR++) {
770                         my $row;
771                         for(my $iC = $oWorksheet->{MinCol} ; defined $oWorksheet->{MaxCol} && $iC <= $oWorksheet->{MaxCol} ; $iC++) {
772                                 my $cell = $oWorksheet->{Cells}[$iR][$iC];
773                                 if ($cell) {
774                                         $row->{int2col($iC)} = $cell->Value;
775                                 }
776                         }
777
778                         progress($iR, $end_row);
779
780 #                       print "row[$iR/$end_row] ";
781 #                       foreach (keys %{$row}) {
782 #                               print "$_: ",$row->{$_},"\t";
783 #                       }
784 #                       print "\n";
785
786                         my $swishpath = $database."#".$iR;
787
788                         next if (! $row);
789
790                         if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
791                                 $xml = $cp2utf->convert($xml);
792                                 use bytes;      # as opposed to chars
793                                 print "Path-Name: $swishpath\n";
794                                 print "Content-Length: ".(length($xml)+1)."\n";
795                                 print "Document-Type: XML\n\n$xml\n";
796                         }
797                 }
798         } elsif ($type_base eq "marc") {
799
800                 require MARC;
801                 
802                 $import2cp = Text::Iconv->new($config->{marc_codepage},$codepage);
803                 my $marc_file = $cfg -> val($database, 'marc_file') || die "$database doesn't have 'marc_file' defined!";
804
805                 # optional argument is format
806                 my $format = x($config->{marc_format}) || 'usmarc';
807
808                 print STDERR "Reading MARC file '$marc_file'\n";
809
810                 my $marc = new MARC;
811                 my $nr = $marc->openmarc({
812                                 file=>$marc_file, format=>$format
813                         }) || die "Can't open MARC file '$marc_file' with format '$format'";
814
815                 # read MARC file in memory
816                 $marc->nextmarc(-1);
817
818                 my $max_rec = $marc->marc_count();
819
820                 for(my $i=1; $i<=$max_rec; $i++) {
821
822                         progress($i,$max_rec);
823
824                         # store value for marc_sf.pm
825                         $main::cache->{marc_record} = $i;
826
827                         my $swishpath = $database."#".$i;
828
829                         if (my $xml = data2xml($type_base,$marc,$add_xml,$cfg,$database)) {
830                                 $xml = $cp2utf->convert($xml);
831                                 use bytes;      # as opposed to chars
832                                 print "Path-Name: $swishpath\n";
833                                 print "Content-Length: ".(length($xml)+1)."\n";
834                                 print "Document-Type: XML\n\n$xml\n";
835                         }
836                 }
837
838                 print STDERR "\n";
839
840         } elsif ($type_base eq "feed") {
841
842                 $import2cp = Text::Iconv->new($config->{feed_codepage},$codepage);
843                 my $prog = x($config->{prog}) || die "$database doesn't have 'prog' defined!";
844
845                 print STDERR "Reading feed from program '$prog'\n";
846
847                 open(FEED,"feeds/$prog |") || die "can't start $prog: $!";
848
849                 my $i=1;        # record nr.
850
851                 my $data;
852                 my $line=1;
853
854                 while (<FEED>) {
855                         chomp;
856
857                         if (/^$/) {
858                                 my $swishpath = $database."#".$i++;
859
860                                 if (my $xml = data2xml($type_base,$data,$add_xml,$cfg,$database)) {
861                                         $xml = $cp2utf->convert($xml);
862                                         use bytes;      # as opposed to chars
863                                         print "Path-Name: $swishpath\n";
864                                         print "Content-Length: ".(length($xml)+1)."\n";
865                                         print "Document-Type: XML\n\n$xml\n";
866                                 }
867                                 $line = 1;
868                                 $data = {};
869                                 next;
870                         }
871
872                         $line = $1 if (s/^(\d+):\s*//);
873                         $data->{$line++} = $_;
874
875                         fakeprogress($i);
876
877                 }
878                 # close lookup
879                 untie %lhash if (%lhash);
880         }
881 }
882
883 # call this to commit index
884 $index->close;
885
886 1;
887 __END__
888 ##########################################################################
889
890 =head1 NAME
891
892 all2xml.pl - read various file formats and dump XML for SWISH-E
893
894 =head1 DESCRIPTION
895
896 This command will read ISIS data file using OpenIsis perl module, MARC
897 records using MARC module and optionally Micro$oft Excel files to
898 create one XML file for usage with I<SWISH-E> indexer. Dispite it's name,
899 this script B<isn't general xml generator> from isis files (isis allready
900 has something like that). Output of this script is tailor-made for SWISH-E.
901
902 =head1 BUGS
903
904 Documentation is really lacking. However, in true Open Source spirit, source
905 is best documentation. I even made considerable effort to comment parts
906 which are not intuitively clear, so...
907
908 =head1 AUTHOR
909
910 Dobrica Pavlinusic <dpavlin@rot13.org>
911
912 =head1 COPYRIGHT
913
914 GNU Public License (GPL) v2 or later
915
916 =head1 SEE ALSO
917
918 SWISH-E web site at http://www.swish-e.org
919
920 =cut