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