big commit, still breaking things...
[koha.git] / updater / updatedatabase
1 #!/usr/bin/perl
2
3 # $Id$
4
5 # Database Updater
6 # This script checks for required updates to the database.
7
8 # Part of the Koha Library Software www.koha.org
9 # Licensed under the GPL.
10
11 # Bugs/ToDo:
12 # - Would also be a good idea to offer to do a backup at this time...
13
14 # NOTE:  If you do something more than once in here, make it table driven.
15 use strict;
16
17 # CPAN modules
18 use DBI;
19 use Getopt::Long;
20 # Koha modules
21 use C4::Context;
22
23 use MARC::Record;
24 use MARC::File::XML;
25
26 # FIXME - The user might be installing a new database, so can't rely
27 # on /etc/koha.conf anyway.
28
29 my $debug = 0;
30
31 my (
32     $sth, $sti,
33     $query,
34     %existingtables,    # tables already in database
35     %types,
36     $table,
37     $column,
38     $type, $null, $key, $default, $extra,
39     $prefitem,          # preference item in systempreferences table
40 );
41
42 my $silent;
43 GetOptions(
44         's' =>\$silent
45         );
46 my $dbh = C4::Context->dbh;
47 print "connected to your DB. Checking & modifying it\n" unless $silent;
48 $|=1; # flushes output
49
50 #-------------------
51 # Defines
52
53 # Tables to add if they don't exist
54 my %requiretables = (
55     categorytable       => "(categorycode char(5) NOT NULL default '',
56                              description text default '',
57                              itemtypecodes text default '',
58                              PRIMARY KEY (categorycode)
59                             )",
60     subcategorytable       => "(subcategorycode char(5) NOT NULL default '',
61                              description text default '',
62                              itemtypecodes text default '',
63                              PRIMARY KEY (subcategorycode)
64                             )",
65     mediatypetable       => "(mediatypecode char(5) NOT NULL default '',
66                              description text default '',
67                              itemtypecodes text default '',
68                              PRIMARY KEY (mediatypecode)
69                             )",
70     action_logs         => "(
71                                     `timestamp` TIMESTAMP NOT NULL ,
72                                     `user` INT( 11 ) NOT NULL ,
73                                     `module` TEXT default '',
74                                     `action` TEXT default '' ,
75                                     `object` INT(11) default '' ,
76                                     `info` TEXT default '' ,
77                                     PRIMARY KEY ( `timestamp` , `user` )
78                             )",
79         letter          => "(
80                                         module varchar(20) NOT NULL default '',
81                                         code varchar(20) NOT NULL default '',
82                                         name varchar(100) NOT NULL default '',
83                                         title varchar(200) NOT NULL default '',
84                                         content text,
85                                         PRIMARY KEY  (module,code)
86                                 )",
87         alert           =>"(
88                                         alertid int(11) NOT NULL auto_increment,
89                                         borrowernumber int(11) NOT NULL default '0',
90                                         type varchar(10) NOT NULL default '',
91                                         externalid varchar(20) NOT NULL default '',
92                                         PRIMARY KEY  (alertid),
93                                         KEY borrowernumber (borrowernumber),
94                                         KEY type (type,externalid)
95                                 )",
96
97 );
98
99 my %requirefields = (
100         subscription => { 'letter' => 'char(20) NULL'},
101         itemtypes => { 'imageurl' => 'char(200) NULL'},
102 #    tablename        => { 'field' => 'fieldtype' },
103 );
104
105 my %dropable_table = (
106 # tablename => 'tablename',
107 );
108
109 my %uselessfields = (
110 # tablename => "field1,field2",
111         );
112 # the other hash contains other actions that can't be done elsewhere. they are done
113 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
114
115 # The tabledata hash contains data that should be in the tables.
116 # The uniquefieldrequired hash entry is used to determine which (if any) fields
117 # must not exist in the table for this row to be inserted.  If the
118 # uniquefieldrequired entry is already in the table, the existing data is not
119 # modified, unless the forceupdate hash entry is also set.  Fields in the
120 # anonymous "forceupdate" hash will be forced to be updated to the default
121 # values given in the %tabledata hash.
122
123 my %tabledata = (
124 # tablename => [
125 #       {       uniquefielrequired => 'fieldname', # the primary key in the table
126 #               fieldname => fieldvalue,
127 #               fieldname2 => fieldvalue2,
128 #       },
129 # ],
130     systempreferences => [
131                 {
132             uniquefieldrequired => 'variable',
133             variable            => 'Activate_Log',
134             value               => 'On',
135             forceupdate         => { 'explanation' => 1,
136                                      'type' => 1},
137             explanation         => 'Turn Log Actions on DB On an Off',
138             type                => 'YesNo',
139         },
140         {
141             uniquefieldrequired => 'variable',
142             variable            => 'IndependantBranches',
143             value               => 0,
144             forceupdate         => { 'explanation' => 1,
145                                      'type' => 1},
146             explanation         => 'Turn Branch independancy management On an Off',
147             type                => 'YesNo',
148         },
149                 {
150             uniquefieldrequired => 'variable',
151             variable            => 'ReturnBeforeExpiry',
152             value               => 'Off',
153             forceupdate         => { 'explanation' => 1,
154                                      'type' => 1},
155             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
156             type                => 'YesNo',
157         },
158         {
159             uniquefieldrequired => 'variable',
160             variable            => 'opacstylesheet',
161             value               => '',
162             forceupdate         => { 'explanation' => 1,
163                                      'type' => 1},
164             explanation         => 'Enter a complete URL to use an alternate stylesheet in OPAC',
165             type                => 'free',
166         },
167         {
168             uniquefieldrequired => 'variable',
169             variable            => 'opacsmallimage',
170             value               => '',
171             forceupdate         => { 'explanation' => 1,
172                                      'type' => 1},
173             explanation         => 'Enter a complete URL to an image, will be on top/left instead of the Koha logo',
174             type                => 'free',
175         },
176         {
177             uniquefieldrequired => 'variable',
178             variable            => 'opaclargeimage',
179             value               => '',
180             forceupdate         => { 'explanation' => 1,
181                                      'type' => 1},
182             explanation         => 'Enter a complete URL to an image, will be on the main page, instead of the Koha logo',
183             type                => 'free',
184         },
185         {
186             uniquefieldrequired => 'variable',
187             variable            => 'delimiter',
188             value               => ';',
189             forceupdate         => { 'explanation' => 1,
190                                      'type' => 1},
191             explanation         => 'separator for reports exported to spreadsheet',
192             type                => 'free',
193         },
194         {
195             uniquefieldrequired => 'variable',
196             variable            => 'MIME',
197             value               => 'OPENOFFICE.ORG',
198             forceupdate         => { 'explanation' => 1,
199                                      'type' => 1,
200                                      'options' => 1},
201             explanation         => 'Define the default application for report exportations into files',
202                 type            => 'Choice',
203                 options         => 'EXCEL|OPENOFFICE.ORG'
204         },
205         {
206             uniquefieldrequired => 'variable',
207             variable            => 'Delimiter',
208             value               => ';',
209                 forceupdate             => { 'explanation' => 1,
210                                      'type' => 1,
211                                      'options' => 1},
212             explanation         => 'Define the default separator character for report exportations into files',
213                 type            => 'Choice',
214                 options         => ';|tabulation|,|/|\|#'
215         },
216         {
217             uniquefieldrequired => 'variable',
218             variable            => 'SubscriptionHistory',
219             value               => ';',
220                 forceupdate             => { 'explanation' => 1,
221                                      'type' => 1,
222                                      'options' => 1},
223             explanation         => 'Define the information level for serials history in OPAC',
224                 type            => 'Choice',
225                 options         => 'simplified|full'
226         },
227         {
228             uniquefieldrequired => 'variable',
229             variable            => 'hidelostitems',
230             value               => 'No',
231             forceupdate         => { 'explanation' => 1,
232                                      'type' => 1},
233             explanation         => 'show or hide "lost" items in OPAC.',
234             type                => 'YesNo',
235         },
236                  {
237             uniquefieldrequired => 'variable',
238             variable            => 'IndependantBranches',
239             value               => '0',
240             forceupdate         => { 'explanation' => 1,
241                                      'type' => 1},
242             explanation         => 'Turn Branch independancy management On an Off',
243             type                => 'YesNo',
244         },
245                 {
246             uniquefieldrequired => 'variable',
247             variable            => 'ReturnBeforeExpiry',
248             value               => '0',
249             forceupdate         => { 'explanation' => 1,
250                                      'type' => 1},
251             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
252             type                => 'YesNo',
253         },
254         {
255             uniquefieldrequired => 'variable',
256             variable            => 'Disable_Dictionary',
257             value               => '0',
258             forceupdate         => { 'explanation' => 1,
259                                      'type' => 1},
260             explanation         => 'Disables Dictionary buttons if set to yes',
261             type                => 'YesNo',
262         },
263         {
264             uniquefieldrequired => 'variable',
265             variable            => 'hide_marc',
266             value               => '0',
267             forceupdate         => { 'explanation' => 1,
268                                      'type' => 1},
269             explanation         => 'hide marc specific datas like subfield code & indicators to library',
270             type                => 'YesNo',
271         },
272     ],
273
274 );
275
276 my %fielddefinitions = (
277 # fieldname => [
278 #       {                 field => 'fieldname',
279 #             type    => 'fieldtype',
280 #             null    => '',
281 #             key     => '',
282 #             default => ''
283 #         },
284 #     ],
285         serial => [
286         {
287             field   => 'notes',
288             type    => 'TEXT',
289             null    => 'NULL',
290             key     => '',
291             default => '',
292             extra   => ''
293         },
294     ],
295 );
296
297 #-------------------
298 # Initialize
299
300 # Start checking
301
302 # Get version of MySQL database engine.
303 my $mysqlversion = `mysqld --version`;
304 $mysqlversion =~ /Ver (\S*) /;
305 $mysqlversion = $1;
306 if ( $mysqlversion ge '3.23' ) {
307     print "Could convert to MyISAM database tables...\n" unless $silent;
308 }
309
310 #---------------------------------
311 # Tables
312
313 # Collect all tables into a list
314 $sth = $dbh->prepare("show tables");
315 $sth->execute;
316 while ( my ($table) = $sth->fetchrow ) {
317     $existingtables{$table} = 1;
318 }
319
320
321 # Now add any missing tables
322 foreach $table ( keys %requiretables ) {
323     unless ( $existingtables{$table} ) {
324         print "Adding $table table...\n" unless $silent;
325         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
326         $sth->execute;
327         if ( $sth->err ) {
328             print "Error : $sth->errstr \n";
329             $sth->finish;
330         }    # if error
331     }    # unless exists
332 }    # foreach
333
334 # now drop useless tables
335 foreach $table ( keys %dropable_table ) {
336         if ( $existingtables{$table} ) {
337                 print "Dropping unused table $table\n" if $debug and not $silent;
338                 $dbh->do("drop table $table");
339                 if ( $dbh->err ) {
340                         print "Error : $dbh->errstr \n";
341                 }
342         }
343 }
344
345 #---------------------------------
346 # Columns
347
348 foreach $table ( keys %requirefields ) {
349     print "Check table $table\n" if $debug and not $silent;
350     $sth = $dbh->prepare("show columns from $table");
351     $sth->execute();
352     undef %types;
353     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
354     {
355         $types{$column} = $type;
356     }    # while
357     foreach $column ( keys %{ $requirefields{$table} } ) {
358         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
359         if ( !$types{$column} ) {
360
361             # column doesn't exist
362             print "Adding $column field to $table table...\n" unless $silent;
363             $query = "alter table $table
364                         add column $column " . $requirefields{$table}->{$column};
365             print "Execute: $query\n" if $debug;
366             my $sti = $dbh->prepare($query);
367             $sti->execute;
368             if ( $sti->err ) {
369                 print "**Error : $sti->errstr \n";
370                 $sti->finish;
371             }    # if error
372         }    # if column
373     }    # foreach column
374 }    # foreach table
375
376 foreach $table ( keys %fielddefinitions ) {
377         print "Check table $table\n" if $debug;
378         $sth = $dbh->prepare("show columns from $table");
379         $sth->execute();
380         my $definitions;
381         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
382         {
383                 $definitions->{$column}->{type}    = $type;
384                 $definitions->{$column}->{null}    = $null;
385                 $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
386                 $definitions->{$column}->{key}     = $key;
387                 $definitions->{$column}->{default} = $default;
388                 $definitions->{$column}->{extra}   = $extra;
389         }    # while
390         my $fieldrow = $fielddefinitions{$table};
391         foreach my $row (@$fieldrow) {
392                 my $field   = $row->{field};
393                 my $type    = $row->{type};
394                 my $null    = $row->{null};
395 #               $null    = 'YES' if $row->{null} eq 'NULL';
396                 my $key     = $row->{key};
397                 my $default = $row->{default};
398                 my $null    = $row->{null};
399 #               $default="''" unless $default;
400                 my $extra   = $row->{extra};
401                 my $def     = $definitions->{$field};
402
403                 unless ( $type eq $def->{type}
404                         && $null eq $def->{null}
405                         && $key eq $def->{key}
406                         && $extra eq $def->{extra} )
407                 {
408                         if ( $null eq '' ) {
409                                 $null = 'NOT NULL';
410                         }
411                         if ( $key eq 'PRI' ) {
412                                 $key = 'PRIMARY KEY';
413                         }
414                         unless ( $extra eq 'auto_increment' ) {
415                                 $extra = '';
416                         }
417
418                         # if it's a new column use "add", if it's an old one, use "change".
419                         my $action;
420                         if ($definitions->{$field}->{type}) {
421                                 $action="change $field"
422                         } else {
423                                 $action="add";
424                         }
425 # if it's a primary key, drop the previous pk, before altering the table
426                         my $sth;
427                         if ($key ne 'PRIMARY KEY') {
428                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ?");
429                         } else {
430                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ?");
431                         }
432                         $sth->execute($default);
433                         print "  Alter $field in $table\n" unless $silent;
434                 }
435         }
436 }
437
438
439 # Populate tables with required data
440 foreach my $table ( keys %tabledata ) {
441     print "Checking for data required in table $table...\n" unless $silent;
442     my $tablerows = $tabledata{$table};
443     foreach my $row (@$tablerows) {
444         my $uniquefieldrequired = $row->{uniquefieldrequired};
445         my $uniquevalue         = $row->{$uniquefieldrequired};
446         my $forceupdate         = $row->{forceupdate};
447         my $sth                 =
448           $dbh->prepare(
449 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
450         );
451         $sth->execute($uniquevalue);
452         if ($sth->rows) {
453             foreach my $field (keys %$forceupdate) {
454                 if ($forceupdate->{$field}) {
455                     my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
456                     $sth->execute($row->{$field}, $uniquevalue);
457                 }
458             }
459         } else {
460             print "Adding row to $table: " unless $silent;
461             my @values;
462             my $fieldlist;
463             my $placeholders;
464             foreach my $field ( keys %$row ) {
465                 next if $field eq 'uniquefieldrequired';
466                 next if $field eq 'forceupdate';
467                 my $value = $row->{$field};
468                 push @values, $value;
469                 print "  $field => $value" unless $silent;
470                 $fieldlist .= "$field,";
471                 $placeholders .= "?,";
472             }
473             print "\n" unless $silent;
474             $fieldlist    =~ s/,$//;
475             $placeholders =~ s/,$//;
476             my $sth =
477               $dbh->prepare(
478                 "insert into $table ($fieldlist) values ($placeholders)");
479             $sth->execute(@values);
480         }
481     }
482 }
483
484 #
485 # SPECIFIC STUFF
486 #
487 #
488 # create frameworkcode row in biblio table & fill it with marc_biblio.frameworkcode.
489 #
490
491 # 1st, get how many biblio we will have to do...
492 $sth = $dbh->prepare('select count(*) from marc_biblio');
493 $sth->execute;
494 my ($totaltodo) = $sth->fetchrow;
495
496 $sth = $dbh->prepare("show columns from biblio");
497 $sth->execute();
498 my $definitions;
499 my $bibliofwexist=0;
500 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
501         $bibliofwexist=1 if $column eq 'frameworkcode';
502 }
503 unless ($bibliofwexist) {
504         print "moving biblioframework to biblio table\n";
505         $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
506         $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
507         $sth->execute;
508         my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
509         my $totaldone=0;
510         while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
511                 $sth_update->execute($frameworkcode,$biblionumber);
512                 $totaldone++;
513                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
514         }
515         print "\rdone\n";
516 }
517
518 #
519 # moving MARC data from marc_subfield_table to biblioitems.marc
520 #
521 $sth = $dbh->prepare("show columns from biblioitems");
522 $sth->execute();
523 my $definitions;
524 my $marcdone=0;
525 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
526         $marcdone=1 if ($type eq 'blob' && $column eq 'marc') ;
527 }
528 unless ($marcdone) {
529         print "moving MARC record to biblioitems table\n";
530         # changing marc field type
531         $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` BLOB NULL DEFAULT NULL ');
532         # adding marc xml, just for convenience
533         $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` TEXT NOT NULL');
534         # moving data from marc_subfield_value to biblio
535         $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio');
536         $sth->execute;
537         my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?');
538         my $totaldone=0;
539         while (my ($bibid,$biblionumber) = $sth->fetchrow) {
540                 my $record = MARCgetbiblio($dbh,$bibid);
541                 $sth_update->execute($record->as_usmarc(),$record->as_xml(),$biblionumber);
542                 $totaldone++;
543                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
544         }
545         print "\rdone\n";
546 }
547
548 # at last, remove useless fields
549 foreach $table ( keys %uselessfields ) {
550         my @fields = split /,/,$uselessfields{$table};
551         my $fields;
552         my $exists;
553         foreach my $fieldtodrop (@fields) {
554                 $fieldtodrop =~ s/\t//g;
555                 $fieldtodrop =~ s/\n//g;
556                 $exists =0;
557                 $sth = $dbh->prepare("show columns from $table");
558                 $sth->execute;
559                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
560                 {
561                         $exists =1 if ($column eq $fieldtodrop);
562                 }
563                 if ($exists) {
564                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
565                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
566                         $sth->execute;
567                 }
568         }
569 }    # foreach
570
571
572 $sth->finish;
573
574 #
575 # those 2 subs are a copy of Biblio.pm, version 2.2.4
576 # they are useful only once, for moving from 2.2 to 3.0
577 # the MARCgetbiblio & MARCgetitem subs in Biblio.pm
578 # are still here, but uses other tables
579 # (the ones that are filled by updatedatabase !)
580 #
581 sub MARCgetbiblio {
582
583     # Returns MARC::Record of the biblio passed in parameter.
584     my ( $dbh, $bibid ) = @_;
585     my $record = MARC::Record->new();
586 #       warn "". $bidid;
587
588     my $sth =
589       $dbh->prepare(
590 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
591                                  from marc_subfield_table
592                                  where bibid=? order by tag,tagorder,subfieldorder
593                          "
594     );
595     my $sth2 =
596       $dbh->prepare(
597         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
598     $sth->execute($bibid);
599     my $prevtagorder = 1;
600     my $prevtag      = 'XXX';
601     my $previndicator;
602     my $field;        # for >=10 tags
603     my $prevvalue;    # for <10 tags
604     while ( my $row = $sth->fetchrow_hashref ) {
605
606         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
607             $sth2->execute( $row->{'valuebloblink'} );
608             my $row2 = $sth2->fetchrow_hashref;
609             $sth2->finish;
610             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
611         }
612         if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
613             $previndicator .= "  ";
614             if ( $prevtag < 10 ) {
615                                 if ($prevtag ne '000') {
616                         $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
617                                 } else {
618                                         $record->leader(sprintf("%24s",$prevvalue));
619                                 }
620             }
621             else {
622                 $record->add_fields($field) unless $prevtag eq "XXX";
623             }
624             undef $field;
625             $prevtagorder  = $row->{tagorder};
626             $prevtag       = $row->{tag};
627             $previndicator = $row->{tag_indicator};
628             if ( $row->{tag} < 10 ) {
629                 $prevvalue = $row->{subfieldvalue};
630             }
631             else {
632                 $field = MARC::Field->new(
633                     ( sprintf "%03s", $prevtag ),
634                     substr( $row->{tag_indicator} . '  ', 0, 1 ),
635                     substr( $row->{tag_indicator} . '  ', 1, 1 ),
636                     $row->{'subfieldcode'},
637                     $row->{'subfieldvalue'}
638                 );
639             }
640         }
641         else {
642             if ( $row->{tag} < 10 ) {
643                 $record->add_fields( ( sprintf "%03s", $row->{tag} ),
644                     $row->{'subfieldvalue'} );
645             }
646             else {
647                 $field->add_subfields( $row->{'subfieldcode'},
648                     $row->{'subfieldvalue'} );
649             }
650             $prevtag       = $row->{tag};
651             $previndicator = $row->{tag_indicator};
652         }
653     }
654
655     # the last has not been included inside the loop... do it now !
656     if ( $prevtag ne "XXX" )
657     { # check that we have found something. Otherwise, prevtag is still XXX and we
658          # must return an empty record, not make MARC::Record fail because we try to
659          # create a record with XXX as field :-(
660         if ( $prevtag < 10 ) {
661             $record->add_fields( $prevtag, $prevvalue );
662         }
663         else {
664
665             #           my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
666             $record->add_fields($field);
667         }
668     }
669     return $record;
670 }
671
672 sub MARCgetitem {
673
674     # Returns MARC::Record of the biblio passed in parameter.
675     my ( $dbh, $bibid, $itemnumber ) = @_;
676     my $record = MARC::Record->new();
677
678     # search MARC tagorder
679     my $sth2 =
680       $dbh->prepare(
681 "select tagorder from marc_subfield_table,marc_subfield_structure where marc_subfield_table.tag=marc_subfield_structure.tagfield and marc_subfield_table.subfieldcode=marc_subfield_structure.tagsubfield and bibid=? and kohafield='items.itemnumber' and subfieldvalue=?"
682     );
683     $sth2->execute( $bibid, $itemnumber );
684     my ($tagorder) = $sth2->fetchrow_array();
685
686     #---- TODO : the leader is missing
687     my $sth =
688       $dbh->prepare(
689 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
690                                  from marc_subfield_table
691                                  where bibid=? and tagorder=? order by subfieldcode,subfieldorder
692                          "
693     );
694     $sth2 =
695       $dbh->prepare(
696         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
697     $sth->execute( $bibid, $tagorder );
698     while ( my $row = $sth->fetchrow_hashref ) {
699         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
700             $sth2->execute( $row->{'valuebloblink'} );
701             my $row2 = $sth2->fetchrow_hashref;
702             $sth2->finish;
703             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
704         }
705         if ( $record->field( $row->{'tag'} ) ) {
706             my $field;
707
708 #--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
709             #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
710             if ( length( $row->{'tag'} ) < 3 ) {
711                 $row->{'tag'} = "0" . $row->{'tag'};
712             }
713             $field = $record->field( $row->{'tag'} );
714             if ($field) {
715                 my $x =
716                   $field->add_subfields( $row->{'subfieldcode'},
717                     $row->{'subfieldvalue'} );
718                 $record->delete_field($field);
719                 $record->add_fields($field);
720             }
721         }
722         else {
723             if ( length( $row->{'tag'} ) < 3 ) {
724                 $row->{'tag'} = "0" . $row->{'tag'};
725             }
726             my $temp =
727               MARC::Field->new( $row->{'tag'}, " ", " ",
728                 $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
729             $record->add_fields($temp);
730         }
731
732     }
733     return $record;
734 }
735
736
737 exit;
738
739 # $Log$
740 # Revision 1.123  2005/10/26 09:13:37  tipaul
741 # big commit, still breaking things...
742 #
743 # * synch with rel_2_2. Probably the last non manual synch, as rel_2_2 should not be modified deeply.
744 # * code cleaning (cleaning warnings from perl -w) continued
745 #
746 # Revision 1.122  2005/09/02 14:18:38  tipaul
747 # new feature : image for itemtypes.
748 #
749 # * run updater/updatedatabase to create imageurl field in itemtypes.
750 # * go to Koha >> parameters >> itemtypes >> modify (or add) an itemtype. You will see around 20 nice images to choose between (thanks to owen). If you prefer your own image, you also can type a complete url (http://www.myserver.lib/path/to/my/image.gif)
751 # * go to OPAC, and search something. In the result list, you now have the picture instead of the text itemtype.
752 #
753 # Revision 1.121  2005/08/24 08:49:03  hdl
754 # Adding a note field in serial table.
755 # This will allow librarian to mention a note on a peculiar waiting serial number.
756 #
757 # Revision 1.120  2005/08/09 14:10:32  tipaul
758 # 1st commit to go to zebra.
759 # don't update your cvs if you want to have a working head...
760 #
761 # this commit contains :
762 # * updater/updatedatabase : get rid with marc_* tables, but DON'T remove them. As a lot of things uses them, it would not be a good idea for instance to drop them. If you really want to play, you can rename them to test head without them but being still able to reintroduce them...
763 # * Biblio.pm : modify MARCgetbiblio to find the raw marc record in biblioitems.marc field, not from marc_subfield_table, modify MARCfindframeworkcode to find frameworkcode in biblio.frameworkcode, modify some other subs to use biblio.biblionumber & get rid of bibid.
764 # * other files : get rid of bibid and use biblionumber instead.
765 #
766 # What is broken :
767 # * does not do anything on zebra yet.
768 # * if you rename marc_subfield_table, you can't search anymore.
769 # * you can view a biblio & bibliodetails, go to MARC editor, but NOT save any modif.
770 # * don't try to add a biblio, it would add data poorly... (don't try to delete either, it may work, but that would be a surprise ;-) )
771 #
772 # IMPORTANT NOTE : you need MARC::XML package (http://search.cpan.org/~esummers/MARC-XML-0.7/lib/MARC/File/XML.pm), that requires a recent version of MARC::Record
773 # Updatedatabase stores the iso2709 data in biblioitems.marc field & an xml version in biblioitems.marcxml Not sure we will keep it when releasing the stable version, but I think it's a good idea to have something readable in sql, at least for development stage.
774 #
775 # Revision 1.119  2005/08/04 16:07:58  tipaul
776 # Synch really broke this script...
777 #
778 # Revision 1.118  2005/08/04 16:02:55  tipaul
779 # oops... error in synch between 2.2 and head
780 #
781 # Revision 1.117  2005/08/04 14:24:39  tipaul
782 # synch'ing 2.2 and head
783 #
784 # Revision 1.116  2005/08/04 08:55:54  tipaul
785 # Letters / alert system, continuing...
786 #
787 # * adding a package Letters.pm, that manages Letters & alerts.
788 # * adding feature : it's now possible to define a "letter" for any subscription created. If a letter is defined, users in OPAC can put an alert on the subscription. When an issue is marked "arrived", all users in the alert will recieve a mail (as defined in the "letter"). This last part (= send the mail) is not yet developped. (Should be done this week)
789 # * adding feature : it's now possible to "put to an alert" in OPAC, for any serial subscription. The alert is stored in a new table, called alert. An alert can be put only if the librarian has activated them in subscription (and they activate it just by choosing a "letter" to sent to borrowers on new issues)
790 # * adding feature : librarian can see in borrower detail which alerts they have put, and a user can see in opac-detail which alert they have put too.
791 #
792 # Note that the system should be generic enough to manage any type of alert.
793 # I plan to extend it soon to virtual shelves : a borrower will be able to put an alert on a virtual shelf, to be warned when something is changed in the virtual shelf (mail being sent once a day by cron, or manually by the shelf owner. Anyway, a mail won't be sent on every change, users would be spammed by Koha ;-) )
794 #
795 # Revision 1.115  2005/08/02 16:15:34  tipaul
796 # adding 2 fields to letter system :
797 # * module (acquisition, catalogue...) : it will be usefull to show the librarian only letters he may be interested by.
798 # * title, that will be used as mail subject.
799 #
800 # Revision 1.114  2005/07/28 15:10:13  tipaul
801 # Introducing new "Letters" system : Letters will be used everytime you want to sent something to someone (through mail or paper). For example, sending a mail for overdues use letter that you can put as parameters. Sending a mail to a borrower when a suggestion is validated uses a letter too.
802 # the letter table contains 3 fields :
803 # * code => the code of the letter
804 # * name => the complete name of the letter
805 # * content => the complete text. It's a TEXT field type, so has no limits.
806 #
807 # My next goal now is to work on point 2-I "serial issue alert"
808 # With this feature, in serials, a user can subscribe the "issue alert". For every issue arrived/missing, a mail is sent to all subscribers of this list. The mail warns the user that the issue is arrive or missing. Will be in head.
809 # (see mail on koha-devel, 2005/04/07)
810 #
811 # The "serial issue alert" will be the 1st to use this letter system that probably needs some tweaking ;-)
812 #
813 # Once it will be stabilised default letters (in any languages) could be added during installer to help the library begin with this new feature.
814 #
815 # Revision 1.113  2005/07/28 08:38:41  tipaul
816 # For instance, the return date does not rely on the borrower expiration date. A systempref will be added in Koha, to modify return date calculation schema :
817 # * ReturnBeforeExpiry = yes => return date can't be after expiry date
818 # * ReturnBeforeExpiry = no  => return date can be after expiry date
819 #
820 # Revision 1.112  2005/07/26 08:19:47  hdl
821 # Adding IndependantBranches System preference variable in order to manage Branch independancy.
822 #
823 # Revision 1.111  2005/07/25 15:35:38  tipaul
824 # we have decided that moving to Koha 3.0 requires being already in Koha 2.2.x
825 # So, the updatedatabase script can highly be cleaned (90% removed).
826 # Let's play with the new Koha DB structure now ;-)
827 #