Marc record should be set to UTF-8 in leader.Force it.
[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 ( BinaryEncoding => 'utf8' );
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         opac_news => "(
97                                 `idnew` int(10) unsigned NOT NULL auto_increment,
98                                 `title` varchar(250) NOT NULL default '',
99                                 `new` text NOT NULL,
100                                 `lang` varchar(4) NOT NULL default '',
101                                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
102                                 PRIMARY KEY  (`idnew`)
103                                 )",
104         repeatable_holidays => "(
105                                 `id` int(11) NOT NULL auto_increment,
106                                 `branchcode` varchar(4) NOT NULL default '',
107                                 `weekday` smallint(6) default NULL,
108                                 `day` smallint(6) default NULL,
109                                 `month` smallint(6) default NULL,
110                                 `title` varchar(50) NOT NULL default '',
111                                 `description` text NOT NULL,
112                                 PRIMARY KEY  (`id`)
113                                 )",
114         special_holidays => "(
115                                 `id` int(11) NOT NULL auto_increment,
116                                 `branchcode` varchar(4) NOT NULL default '',
117                                 `day` smallint(6) NOT NULL default '0',
118                                 `month` smallint(6) NOT NULL default '0',
119                                 `year` smallint(6) NOT NULL default '0',
120                                 `isexception` smallint(1) NOT NULL default '1',
121                                 `title` varchar(50) NOT NULL default '',
122                                 `description` text NOT NULL,
123                                 PRIMARY KEY  (`id`)
124                                 )",
125         overduerules    =>"(`branchcode` varchar(255) NOT NULL default '',
126                                         `categorycode` char(2) NOT NULL default '',
127                                         `delay1` int(4) default '0',
128                                         `letter1` varchar(20) default NULL,
129                                         `debarred1` char(1) default '0',
130                                         `delay2` int(4) default '0',
131                                         `debarred2` char(1) default '0',
132                                         `letter2` varchar(20) default NULL,
133                                         `delay3` int(4) default '0',
134                                         `letter3` varchar(20) default NULL,
135                                         `debarred3` int(1) default '0',
136                                         PRIMARY KEY  (`branchcode`,`categorycode`)
137                                         )",
138         cities                  => "(`cityid` int auto_increment,
139                                                 `city_name` char(100) NOT NULL,
140                                                 `city_zipcode` char(20),
141                                                 PRIMARY KEY (`cityid`)
142                                         )",
143         roadtype                        => "(`roadtypeid` int auto_increment,
144                                                 `road_type` char(100) NOT NULL,
145                                                 PRIMARY KEY (`roadtypeid`)
146                                         )",
147 );
148
149 my %requirefields = (
150         subscription => { 'letter' => 'char(20) NULL', 'distributedto' => 'text NULL'},
151         itemtypes => { 'imageurl' => 'char(200) NULL'},
152         aqbookfund => { 'branchcode' => 'varchar(4) NULL'},
153         aqbudget => { 'branchcode' => 'varchar(4) NULL'},
154 #    tablename        => { 'field' => 'fieldtype' },
155 );
156
157 my %dropable_table = (
158         sessionqueries  => 'sessionqueries',
159         marcrecorddone  => 'marcrecorddone',
160         users                   => 'users',
161         itemsprices             => 'itemsprices',
162         biblioanalysis  => 'biblioanalysis',
163         borexp                  => 'borexp',
164 # tablename => 'tablename',
165 );
166
167 my %uselessfields = (
168 # tablename => "field1,field2",
169         borrowers => "suburb,altstreetaddress,altsuburb,altcity,studentnumber,school,area,preferredcont,altcp",
170         );
171 # the other hash contains other actions that can't be done elsewhere. they are done
172 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
173
174 # The tabledata hash contains data that should be in the tables.
175 # The uniquefieldrequired hash entry is used to determine which (if any) fields
176 # must not exist in the table for this row to be inserted.  If the
177 # uniquefieldrequired entry is already in the table, the existing data is not
178 # modified, unless the forceupdate hash entry is also set.  Fields in the
179 # anonymous "forceupdate" hash will be forced to be updated to the default
180 # values given in the %tabledata hash.
181
182 my %tabledata = (
183 # tablename => [
184 #       {       uniquefielrequired => 'fieldname', # the primary key in the table
185 #               fieldname => fieldvalue,
186 #               fieldname2 => fieldvalue2,
187 #       },
188 # ],
189     systempreferences => [
190                 {
191             uniquefieldrequired => 'variable',
192             variable            => 'Activate_Log',
193             value               => 'On',
194             forceupdate         => { 'explanation' => 1,
195                                      'type' => 1},
196             explanation         => 'Turn Log Actions on DB On an Off',
197             type                => 'YesNo',
198         },
199         {
200             uniquefieldrequired => 'variable',
201             variable            => 'IndependantBranches',
202             value               => 0,
203             forceupdate         => { 'explanation' => 1,
204                                      'type' => 1},
205             explanation         => 'Turn Branch independancy management On an Off',
206             type                => 'YesNo',
207         },
208                 {
209             uniquefieldrequired => 'variable',
210             variable            => 'ReturnBeforeExpiry',
211             value               => 'Off',
212             forceupdate         => { 'explanation' => 1,
213                                      'type' => 1},
214             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
215             type                => 'YesNo',
216         },
217         {
218             uniquefieldrequired => 'variable',
219             variable            => 'opacstylesheet',
220             value               => '',
221             forceupdate         => { 'explanation' => 1,
222                                      'type' => 1},
223             explanation         => 'Enter a complete URL to use an alternate stylesheet in OPAC',
224             type                => 'free',
225         },
226         {
227             uniquefieldrequired => 'variable',
228             variable            => 'opacsmallimage',
229             value               => '',
230             forceupdate         => { 'explanation' => 1,
231                                      'type' => 1},
232             explanation         => 'Enter a complete URL to an image, will be on top/left instead of the Koha logo',
233             type                => 'free',
234         },
235         {
236             uniquefieldrequired => 'variable',
237             variable            => 'opaclargeimage',
238             value               => '',
239             forceupdate         => { 'explanation' => 1,
240                                      'type' => 1},
241             explanation         => 'Enter a complete URL to an image, will be on the main page, instead of the Koha logo',
242             type                => 'free',
243         },
244         {
245             uniquefieldrequired => 'variable',
246             variable            => 'delimiter',
247             value               => ';',
248             forceupdate         => { 'explanation' => 1,
249                                      'type' => 1},
250             explanation         => 'separator for reports exported to spreadsheet',
251             type                => 'free',
252         },
253         {
254             uniquefieldrequired => 'variable',
255             variable            => 'MIME',
256             value               => 'OPENOFFICE.ORG',
257             forceupdate         => { 'explanation' => 1,
258                                      'type' => 1,
259                                      'options' => 1},
260             explanation         => 'Define the default application for report exportations into files',
261                 type            => 'Choice',
262                 options         => 'EXCEL|OPENOFFICE.ORG'
263         },
264         {
265             uniquefieldrequired => 'variable',
266             variable            => 'Delimiter',
267             value               => ';',
268                 forceupdate             => { 'explanation' => 1,
269                                      'type' => 1,
270                                      'options' => 1},
271             explanation         => 'Define the default separator character for report exportations into files',
272                 type            => 'Choice',
273                 options         => ';|tabulation|,|/|\|#'
274         },
275         {
276             uniquefieldrequired => 'variable',
277             variable            => 'SubscriptionHistory',
278             value               => ';',
279                 forceupdate             => { 'explanation' => 1,
280                                      'type' => 1,
281                                      'options' => 1},
282             explanation         => 'Define the information level for serials history in OPAC',
283                 type            => 'Choice',
284                 options         => 'simplified|full'
285         },
286         {
287             uniquefieldrequired => 'variable',
288             variable            => 'hidelostitems',
289             value               => 'No',
290             forceupdate         => { 'explanation' => 1,
291                                      'type' => 1},
292             explanation         => 'show or hide "lost" items in OPAC.',
293             type                => 'YesNo',
294         },
295                  {
296             uniquefieldrequired => 'variable',
297             variable            => 'IndependantBranches',
298             value               => '0',
299             forceupdate         => { 'explanation' => 1,
300                                      'type' => 1},
301             explanation         => 'Turn Branch independancy management On an Off',
302             type                => 'YesNo',
303         },
304                 {
305             uniquefieldrequired => 'variable',
306             variable            => 'ReturnBeforeExpiry',
307             value               => '0',
308             forceupdate         => { 'explanation' => 1,
309                                      'type' => 1},
310             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
311             type                => 'YesNo',
312         },
313         {
314             uniquefieldrequired => 'variable',
315             variable            => 'Disable_Dictionary',
316             value               => '0',
317             forceupdate         => { 'explanation' => 1,
318                                      'type' => 1},
319             explanation         => 'Disables Dictionary buttons if set to yes',
320             type                => 'YesNo',
321         },
322         {
323             uniquefieldrequired => 'variable',
324             variable            => 'hide_marc',
325             value               => '0',
326             forceupdate         => { 'explanation' => 1,
327                                      'type' => 1},
328             explanation         => 'hide marc specific datas like subfield code & indicators to library',
329             type                => 'YesNo',
330         },
331         {
332             uniquefieldrequired => 'variable',
333             variable            => 'NotifyBorrowerDeparture',
334             value               => '0',
335             forceupdate         => { 'explanation' => 1,
336                                      'type' => 1},
337             explanation         => 'Delay before expiry where a notice is sent when issuing',
338             type                => 'Integer',
339         },
340         {
341             uniquefieldrequired => 'variable',
342             variable            => 'OpacPasswordChange',
343             value               => '1',
344             forceupdate         => { 'explanation' => 1,
345                                      'type' => 1},
346             explanation         => 'Enable/Disable password change in OPAC (disable it when using LDAP auth)',
347             type                => 'YesNo',
348         },
349         {
350             uniquefieldrequired => 'variable',
351             variable            => 'useDaysMode',
352             value               => 'Calendar',
353             forceupdate         => { 'explanation' => 1,
354                                      'type' => 1},
355             explanation                 => 'How to calculate return dates : Calendar means holidays will be controled, Days means the return date don\'t depend on holidays',
356                 type            => 'Choice',
357                 options         => 'Calendar|Days'
358         },
359         {
360             uniquefieldrequired => 'variable',
361             variable            => 'borrowerMandatoryField',
362             value               => 'zipcode|surname',
363             forceupdate         => { 'explanation' => 1,
364                                      'type' => 1},
365             explanation         => 'List all mandatory fields for borrowers',
366             type                => 'free',
367         },
368         {
369             uniquefieldrequired => 'variable',
370             variable            => 'borrowerRelationship',
371             value               => 'father|mother,grand-mother',
372             forceupdate         => { 'explanation' => 1,
373                                      'type' => 1},
374             explanation         => 'The relationships between a guarantor & a guarantee (separated by | or ,)',
375             type                => 'free',
376         },
377     ],
378
379 );
380
381 my %fielddefinitions = (
382 # fieldname => [
383 #       {                 field => 'fieldname',
384 #             type    => 'fieldtype',
385 #             null    => '',
386 #             key     => '',
387 #             default => ''
388 #         },
389 #     ],
390         serial => [
391         {
392             field   => 'notes',
393             type    => 'TEXT',
394             null    => 'NULL',
395             key     => '',
396             default => '',
397             extra   => ''
398         },
399     ],
400         aqbasket =>  [
401                 {
402                         field   => 'booksellerid',
403                         type    => 'int(11)',
404                         null    => 'NOT NULL',
405                         key             => '',
406                         default => '1',
407                         extra   => '',
408                 },
409         ],
410         aqbooksellers =>  [
411                 {
412                         field   => 'listprice',
413                         type    => 'varchar(10)',
414                         null    => 'NULL',
415                         key             => '',
416                         default => '',
417                         extra   => '',
418                 },
419                 {
420                         field   => 'invoiceprice',
421                         type    => 'varchar(10)',
422                         null    => 'NULL',
423                         key             => '',
424                         default => '',
425                         extra   => '',
426                 },
427         ],
428         issues =>  [
429                 {
430                         field   => 'borrowernumber',
431                         type    => 'int(11)',
432                         null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
433                         key             => '',
434                         default => '',
435                         extra   => '',
436                 },
437                 {
438                         field   => 'itemnumber',
439                         type    => 'int(11)',
440                         null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
441                         key             => '',
442                         default => '',
443                         extra   => '',
444                 },
445         ],
446         borrowers => [
447                 {       field => 'B_email',
448                         type => 'text',
449                         null => 'NULL',
450                         after => 'B_zipcode',
451                  },
452                  {
453                         field => 'streetnumber', # street number (hidden if streettable table is empty)
454                         type => 'char(10)',
455                         null => 'NULL',
456                         after => 'initials',
457                 },
458                 {
459                         field => 'streettype', # street table, list builded from a system table
460                         type => 'char(50)',
461                         null => 'NULL',
462                         after => 'streetnumber',
463                 },
464                  {
465                         field => 'B_streetnumber', # street number (hidden if streettable table is empty)
466                         type => 'char(10)',
467                         null => 'NULL',
468                         after => 'fax',
469                 },
470                 {
471                         field => 'B_streettype', # street table, list builded from a system table
472                         type => 'char(50)',
473                         null => 'NULL',
474                         after => 'B_streetnumber',
475                 },
476                 {
477                         field => 'phonepro',
478                         type => 'text',
479                         null => 'NULL',
480                         after => 'fax',
481                 },
482                 {
483                         field => 'address2', # complement address
484                         type => 'text',
485                         null => 'NULL',
486                         after => 'address',
487                 },
488                 {
489                         field => 'emailpro',
490                         type => 'text',
491                         null => 'NULL',
492                         after => 'fax',
493                 },
494                 {
495                         field => 'contactfirstname', # contact's firstname
496                         type => 'text',
497                         null => 'NULL',
498                         after => 'contactname',
499                 },
500                 {
501                         field => 'contacttitle', # contact's title
502                         type => 'text',
503                         null => 'NULL',
504                         after => 'contactfirstname',
505                 },
506         ],
507         categories =>  [
508                 {
509                         field   => 'category_type',
510                         type    => 'char(1)',
511                         null    => 'NOT NULL',
512                         key             => '',
513                         default => 'A',
514                         extra   => '',
515                 },
516         ],
517
518 );
519
520 my %indexes = (
521 #       table => [
522 #               {       indexname => 'index detail'
523 #               }
524 #       ],
525         shelfcontents => [
526                 {       indexname => 'shelfnumber',
527                         content => 'shelfnumber',
528                 },
529                 {       indexname => 'itemnumber',
530                         content => 'itemnumber',
531                 }
532         ],
533         bibliosubject => [
534                 {       indexname => 'biblionumber',
535                         content => 'biblionumber',
536                 }
537         ],
538         items => [
539                 {       indexname => 'homebranch',
540                         content => 'homebranch',
541                 },
542                 {       indexname => 'holdingbranch',
543                         content => 'holdingbranch',
544                 }
545         ],
546         aqbooksellers => [
547                 {       indexname => 'PRIMARY',
548                         content => 'id',
549                         type => 'PRIMARY',
550                 }
551         ],
552         aqbasket => [
553                 {       indexname => 'booksellerid',
554                         content => 'booksellerid',
555                 },
556         ],
557         aqorders => [
558                 {       indexname => 'basketno',
559                         content => 'basketno',
560                 },
561         ],
562         aqorderbreakdown => [
563                 {       indexname => 'ordernumber',
564                         content => 'ordernumber',
565                 },
566                 {       indexname => 'bookfundid',
567                         content => 'bookfundid',
568                 },
569         ],
570         currency => [
571                 {       indexname => 'PRIMARY',
572                         content => 'currency',
573                         type => 'PRIMARY',
574                 }
575         ],
576 );
577
578 my %foreign_keys = (
579 #       table => [
580 #               {       key => 'the key in table' (must be indexed)
581 #                       foreigntable => 'the foreigntable name', # (the parent)
582 #                       foreignkey => 'the foreign key column(s)' # (in the parent)
583 #                       onUpdate => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
584 #                       onDelete => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
585 #               }
586 #       ],
587         shelfcontents => [
588                 {       key => 'shelfnumber',
589                         foreigntable => 'bookshelf',
590                         foreignkey => 'shelfnumber',
591                         onUpdate => 'CASCADE',
592                         onDelete => 'CASCADE',
593                 },
594                 {       key => 'itemnumber',
595                         foreigntable => 'items',
596                         foreignkey => 'itemnumber',
597                         onUpdate => 'CASCADE',
598                         onDelete => 'CASCADE',
599                 },
600         ],
601         # onDelete is RESTRICT on reference tables (branches, itemtype) as we don't want items to be 
602         # easily deleted, but branches/itemtype not too easy to empty...
603         biblioitems => [
604                 {       key => 'biblionumber',
605                         foreigntable => 'biblio',
606                         foreignkey => 'biblionumber',
607                         onUpdate => 'CASCADE',
608                         onDelete => 'CASCADE',
609                 },
610                 {       key => 'itemtype',
611                         foreigntable => 'itemtypes',
612                         foreignkey => 'itemtype',
613                         onUpdate => 'CASCADE',
614                         onDelete => 'RESTRICT',
615                 },
616         ],
617         items => [
618                 {       key => 'biblioitemnumber',
619                         foreigntable => 'biblioitems',
620                         foreignkey => 'biblioitemnumber',
621                         onUpdate => 'CASCADE',
622                         onDelete => 'CASCADE',
623                 },
624                 {       key => 'homebranch',
625                         foreigntable => 'branches',
626                         foreignkey => 'branchcode',
627                         onUpdate => 'CASCADE',
628                         onDelete => 'RESTRICT',
629                 },
630                 {       key => 'holdingbranch',
631                         foreigntable => 'branches',
632                         foreignkey => 'branchcode',
633                         onUpdate => 'CASCADE',
634                         onDelete => 'RESTRICT',
635                 },
636         ],
637         additionalauthors => [
638                 {       key => 'biblionumber',
639                         foreigntable => 'biblio',
640                         foreignkey => 'biblionumber',
641                         onUpdate => 'CASCADE',
642                         onDelete => 'CASCADE',
643                 },
644         ],
645         bibliosubject => [
646                 {       key => 'biblionumber',
647                         foreigntable => 'biblio',
648                         foreignkey => 'biblionumber',
649                         onUpdate => 'CASCADE',
650                         onDelete => 'CASCADE',
651                 },
652         ],
653         aqbasket => [
654                 {       key => 'booksellerid',
655                         foreigntable => 'aqbooksellers',
656                         foreignkey => 'id',
657                         onUpdate => 'CASCADE',
658                         onDelete => 'RESTRICT',
659                 },
660         ],
661         aqorders => [
662                 {       key => 'basketno',
663                         foreigntable => 'aqbasket',
664                         foreignkey => 'basketno',
665                         onUpdate => 'CASCADE',
666                         onDelete => 'CASCADE',
667                 },
668                 {       key => 'biblionumber',
669                         foreigntable => 'biblio',
670                         foreignkey => 'biblionumber',
671                         onUpdate => 'SET NULL',
672                         onDelete => 'SET NULL',
673                 },
674         ],
675         aqbooksellers => [
676                 {       key => 'listprice',
677                         foreigntable => 'currency',
678                         foreignkey => 'currency',
679                         onUpdate => 'CASCADE',
680                         onDelete => 'CASCADE',
681                 },
682                 {       key => 'invoiceprice',
683                         foreigntable => 'currency',
684                         foreignkey => 'currency',
685                         onUpdate => 'CASCADE',
686                         onDelete => 'CASCADE',
687                 },
688         ],
689         aqorderbreakdown => [
690                 {       key => 'ordernumber',
691                         foreigntable => 'aqorders',
692                         foreignkey => 'ordernumber',
693                         onUpdate => 'CASCADE',
694                         onDelete => 'CASCADE',
695                 },
696                 {       key => 'bookfundid',
697                         foreigntable => 'aqbookfund',
698                         foreignkey => 'bookfundid',
699                         onUpdate => 'CASCADE',
700                         onDelete => 'CASCADE',
701                 },
702         ],
703         branchtransfers => [
704                 {       key => 'frombranch',
705                         foreigntable => 'branches',
706                         foreignkey => 'branchcode',
707                         onUpdate => 'CASCADE',
708                         onDelete => 'CASCADE',
709                 },
710                 {       key => 'tobranch',
711                         foreigntable => 'branches',
712                         foreignkey => 'branchcode',
713                         onUpdate => 'CASCADE',
714                         onDelete => 'CASCADE',
715                 },
716                 {       key => 'itemnumber',
717                         foreigntable => 'items',
718                         foreignkey => 'itemnumber',
719                         onUpdate => 'CASCADE',
720                         onDelete => 'CASCADE',
721                 },
722         ],
723         issuingrules => [
724                 {       key => 'categorycode',
725                         foreigntable => 'categories',
726                         foreignkey => 'categorycode',
727                         onUpdate => 'CASCADE',
728                         onDelete => 'CASCADE',
729                 },
730                 {       key => 'itemtype',
731                         foreigntable => 'itemtypes',
732                         foreignkey => 'itemtype',
733                         onUpdate => 'CASCADE',
734                         onDelete => 'CASCADE',
735                 },
736         ],
737         issues => [     # constraint is SET NULL : when a borrower or an item is deleted, we keep the issuing record
738         # for stat purposes
739                 {       key => 'borrowernumber',
740                         foreigntable => 'borrowers',
741                         foreignkey => 'borrowernumber',
742                         onUpdate => 'SET NULL',
743                         onDelete => 'SET NULL',
744                 },
745                 {       key => 'itemnumber',
746                         foreigntable => 'items',
747                         foreignkey => 'itemnumber',
748                         onUpdate => 'SET NULL',
749                         onDelete => 'SET NULL',
750                 },
751         ],
752         reserves => [
753                 {       key => 'borrowernumber',
754                         foreigntable => 'borrowers',
755                         foreignkey => 'borrowernumber',
756                         onUpdate => 'CASCADE',
757                         onDelete => 'CASCADE',
758                 },
759                 {       key => 'biblionumber',
760                         foreigntable => 'biblio',
761                         foreignkey => 'biblionumber',
762                         onUpdate => 'CASCADE',
763                         onDelete => 'CASCADE',
764                 },
765                 {       key => 'itemnumber',
766                         foreigntable => 'items',
767                         foreignkey => 'itemnumber',
768                         onUpdate => 'CASCADE',
769                         onDelete => 'CASCADE',
770                 },
771                 {       key => 'branchcode',
772                         foreigntable => 'branches',
773                         foreignkey => 'branchcode',
774                         onUpdate => 'CASCADE',
775                         onDelete => 'CASCADE',
776                 },
777         ],
778         borrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
779         # but prevent deleting a branch as soon as it has 1 borrower !
780                 {       key => 'categorycode',
781                         foreigntable => 'categories',
782                         foreignkey => 'categorycode',
783                         onUpdate => 'RESTRICT',
784                         onDelete => 'RESTRICT',
785                 },
786                 {       key => 'branchcode',
787                         foreigntable => 'branches',
788                         foreignkey => 'branchcode',
789                         onUpdate => 'RESTRICT',
790                         onDelete => 'RESTRICT',
791                 },
792         ],
793         accountlines => [
794                 {       key => 'borrowernumber',
795                         foreigntable => 'borrowers',
796                         foreignkey => 'borrowernumber',
797                         onUpdate => 'CASCADE',
798                         onDelete => 'CASCADE',
799                 },
800                 {       key => 'itemnumber',
801                         foreigntable => 'items',
802                         foreignkey => 'itemnumber',
803                         onUpdate => 'SET NULL',
804                         onDelete => 'SET NULL',
805                 },
806         ],
807         auth_tag_structure => [
808                 {       key => 'authtypecode',
809                         foreigntable => 'auth_types',
810                         foreignkey => 'authtypecode',
811                         onUpdate => 'CASCADE',
812                         onDelete => 'CASCADE',
813                 },
814         ],
815         # FIXME : don't constraint auth_*_table and auth_word, as they may be replaced by zebra
816 );
817
818
819 # column changes
820 my %column_change = (
821         # table
822         borrowers => [
823                                 {
824                                         from => 'emailaddress',
825                                         to => 'email',
826                                         after => 'city',
827                                 },
828                                 {
829                                         from => 'streetaddress',
830                                         to => 'address',
831                                         after => 'initials',
832                                 },
833                                 {
834                                         from => 'faxnumber',
835                                         to => 'fax',
836                                         after => 'phone',
837                                 },
838                                 {
839                                         from => 'textmessaging',
840                                         to => 'opacnote',
841                                         after => 'userid',
842                                 },
843                                 {
844                                         from => 'altnotes',
845                                         to => 'contactnote',
846                                         after => 'opacnote',
847                                 },
848                                 {
849                                         from => 'physstreet',
850                                         to => 'B_address',
851                                         after => 'fax',
852                                 },
853                                 {
854                                         from => 'streetcity',
855                                         to => 'B_city',
856                                         after => 'B_address',
857                                 },
858                                 {
859                                         from => 'phoneday',
860                                         to => 'mobile',
861                                         after => 'phone',
862                                 },
863                                 {
864                                         from => 'zipcode',
865                                         to => 'zipcode',
866                                         after => 'city',
867                                 },
868                                 {
869                                         from => 'homezipcode',
870                                         to => 'B_zipcode',
871                                         after => 'B_city',
872                                 },
873                                 {
874                                         from => 'altphone',
875                                         to => 'B_phone',
876                                         after => 'B_zipcode',
877                                 },
878                                 {
879                                         from => 'expiry',
880                                         to => 'dateexpiry',
881                                         after => 'dateenrolled',
882                                 },
883                                 {
884                                         from => 'guarantor',
885                                         to => 'guarantorid',
886                                         after => 'contactname',
887                                 },
888                                 {
889                                         from => 'textmessaging',
890                                         to => 'opacnotes',
891                                         after => 'flags',
892                                 },
893                                 {
894                                         from => 'altnotes',
895                                         to => 'contactnotes',
896                                         after => 'opacnotes',
897                                 },
898                                 {
899                                         from => 'altrelationship',
900                                         to => 'relationship',
901                                         after => 'borrowernotes',
902                                 },
903                         ],
904                 );
905                 
906 foreach my $table (keys %column_change) {
907         $sth = $dbh->prepare("show columns from $table");
908         $sth->execute();
909         undef %types;
910         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
911         {
912                 $types{$column}->{type} ="$type";
913                 $types{$column}->{null} = "$null";
914                 $types{$column}->{key} = "$key";
915                 $types{$column}->{default} = "$default";
916                 $types{$column}->{extra} = "$extra";
917         }    # while
918         my $tablerows = $column_change{$table};
919         foreach my $row ( @$tablerows ) {
920                 if ($types{$row->{from}}->{type}) {
921                         print "altering $table $row->{from} to $row->{to}\n";
922                         # ALTER TABLE `borrowers` CHANGE `faxnumber` `fax` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL 
923 #                       alter table `borrowers` change `faxnumber` `fax` type text  null after phone
924                         my $sql = 
925                                 "alter table `$table` change `$row->{from}` `$row->{to}` $types{$row->{from}}->{type} ".
926                                 ($types{$row->{from}}->{null} eq 'YES'?" NULL":" NOT NULL").
927                                 ($types{$row->{from}}->{default}?" default ".$types{$row->{from}}->{default}:"").
928                                 "$types{$row->{from}}->{extra} after $row->{after} ";
929 #                       print "$sql";
930                         $dbh->do($sql);
931                 }
932         }
933 }
934
935 #-------------------
936 # Initialize
937
938 # Start checking
939
940 # Get version of MySQL database engine.
941 my $mysqlversion = `mysqld --version`;
942 $mysqlversion =~ /Ver (\S*) /;
943 $mysqlversion = $1;
944 if ( $mysqlversion ge '3.23' ) {
945     print "Could convert to MyISAM database tables...\n" unless $silent;
946 }
947
948 #---------------------------------
949 # Tables
950
951 # Collect all tables into a list
952 $sth = $dbh->prepare("show tables");
953 $sth->execute;
954 while ( my ($table) = $sth->fetchrow ) {
955     $existingtables{$table} = 1;
956 }
957
958
959 # Now add any missing tables
960 foreach $table ( keys %requiretables ) {
961     unless ( $existingtables{$table} ) {
962         print "Adding $table table...\n" unless $silent;
963         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
964         $sth->execute;
965         if ( $sth->err ) {
966             print "Error : $sth->errstr \n";
967             $sth->finish;
968         }    # if error
969     }    # unless exists
970 }    # foreach
971
972 # now drop useless tables
973 foreach $table ( keys %dropable_table ) {
974         if ( $existingtables{$table} ) {
975                 print "Dropping unused table $table\n" if $debug and not $silent;
976                 $dbh->do("drop table $table");
977                 if ( $dbh->err ) {
978                         print "Error : $dbh->errstr \n";
979                 }
980         }
981 }
982
983 #---------------------------------
984 # Columns
985
986 foreach $table ( keys %requirefields ) {
987     print "Check table $table\n" if $debug and not $silent;
988     $sth = $dbh->prepare("show columns from $table");
989     $sth->execute();
990     undef %types;
991     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
992     {
993         $types{$column} = $type;
994     }    # while
995     foreach $column ( keys %{ $requirefields{$table} } ) {
996         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
997         if ( !$types{$column} ) {
998
999             # column doesn't exist
1000             print "Adding $column field to $table table...\n" unless $silent;
1001             $query = "alter table $table
1002                         add column $column " . $requirefields{$table}->{$column};
1003             print "Execute: $query\n" if $debug;
1004             my $sti = $dbh->prepare($query);
1005             $sti->execute;
1006             if ( $sti->err ) {
1007                 print "**Error : $sti->errstr \n";
1008                 $sti->finish;
1009             }    # if error
1010         }    # if column
1011     }    # foreach column
1012 }    # foreach table
1013
1014 foreach $table ( keys %fielddefinitions ) {
1015         print "Check table $table\n" if $debug;
1016         $sth = $dbh->prepare("show columns from $table");
1017         $sth->execute();
1018         my $definitions;
1019         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1020         {
1021                 $definitions->{$column}->{type}    = $type;
1022                 $definitions->{$column}->{null}    = $null;
1023                 $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
1024                 $definitions->{$column}->{key}     = $key;
1025                 $definitions->{$column}->{default} = $default;
1026                 $definitions->{$column}->{extra}   = $extra;
1027         }    # while
1028         my $fieldrow = $fielddefinitions{$table};
1029         foreach my $row (@$fieldrow) {
1030                 my $field   = $row->{field};
1031                 my $type    = $row->{type};
1032                 my $null    = $row->{null};
1033 #               $null    = 'YES' if $row->{null} eq 'NULL';
1034                 my $key     = $row->{key};
1035                 my $default = $row->{default};
1036                 my $null    = $row->{null};
1037 #               $default="''" unless $default;
1038                 my $extra   = $row->{extra};
1039                 my $def     = $definitions->{$field};
1040                 my $after       = ($row->{after}?" after ".$row->{after}:"");
1041
1042                 unless ( $type eq $def->{type}
1043                         && $null eq $def->{null}
1044                         && $key eq $def->{key}
1045                         && $extra eq $def->{extra} )
1046                 {
1047                         if ( $null eq '' ) {
1048                                 $null = 'NOT NULL';
1049                         }
1050                         if ( $key eq 'PRI' ) {
1051                                 $key = 'PRIMARY KEY';
1052                         }
1053                         unless ( $extra eq 'auto_increment' ) {
1054                                 $extra = '';
1055                         }
1056
1057                         # if it's a new column use "add", if it's an old one, use "change".
1058                         my $action;
1059                         if ($definitions->{$field}->{type}) {
1060                                 $action="change $field"
1061                         } else {
1062                                 $action="add";
1063                         }
1064 # if it's a primary key, drop the previous pk, before altering the table
1065                         my $sth;
1066                         if ($key ne 'PRIMARY KEY') {
1067                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ? $after");
1068                         } else {
1069                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ? $after");
1070                         }
1071                         $sth->execute($default);
1072                         print "  alter or create $field in $table\n" unless $silent;
1073                 }
1074         }
1075 }
1076
1077 # Populate tables with required data
1078
1079
1080 # synch table and deletedtable.
1081 foreach my $table (('borrowers','items','biblio','biblioitems')) {
1082         my %deletedborrowers;
1083         print "synch'ing $table\n";
1084         $sth = $dbh->prepare("show columns from deleted$table");
1085         $sth->execute;
1086         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
1087                 $deletedborrowers{$column}=1;
1088         }
1089         $sth = $dbh->prepare("show columns from $table");
1090         $sth->execute;
1091         my $previous;
1092         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
1093                 unless ($deletedborrowers{$column}) {
1094                         my $newcol="alter table deleted$table add $column $type";
1095                         if ($null eq 'YES') {
1096                                 $newcol .= " NULL ";
1097                         } else {
1098                                 $newcol .= " NOT NULL ";
1099                         }
1100                         $newcol .= "default $default" if $default;
1101                         $newcol .= " after $previous" if $previous;
1102                         $previous=$column;
1103                         print "creating column $column\n";
1104                         $dbh->do($newcol);
1105                 }
1106         }
1107 }
1108
1109 foreach my $table ( keys %tabledata ) {
1110     print "Checking for data required in table $table...\n" unless $silent;
1111     my $tablerows = $tabledata{$table};
1112     foreach my $row (@$tablerows) {
1113         my $uniquefieldrequired = $row->{uniquefieldrequired};
1114         my $uniquevalue         = $row->{$uniquefieldrequired};
1115         my $forceupdate         = $row->{forceupdate};
1116         my $sth                 =
1117           $dbh->prepare(
1118 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
1119         );
1120         $sth->execute($uniquevalue);
1121                 if ($sth->rows) {
1122                         foreach my $field (keys %$forceupdate) {
1123                                 if ($forceupdate->{$field}) {
1124                                         my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
1125                                         $sth->execute($row->{$field}, $uniquevalue);
1126                                 }
1127                 }
1128                 } else {
1129                         print "Adding row to $table: " unless $silent;
1130                         my @values;
1131                         my $fieldlist;
1132                         my $placeholders;
1133                         foreach my $field ( keys %$row ) {
1134                                 next if $field eq 'uniquefieldrequired';
1135                                 next if $field eq 'forceupdate';
1136                                 my $value = $row->{$field};
1137                                 push @values, $value;
1138                                 print "  $field => $value" unless $silent;
1139                                 $fieldlist .= "$field,";
1140                                 $placeholders .= "?,";
1141                         }
1142                         print "\n" unless $silent;
1143                         $fieldlist    =~ s/,$//;
1144                         $placeholders =~ s/,$//;
1145                         my $sth =
1146                         $dbh->prepare(
1147                                 "insert into $table ($fieldlist) values ($placeholders)");
1148                         $sth->execute(@values);
1149                 }
1150         }
1151 }
1152
1153 #
1154 # check indexes and create them when needed
1155 #
1156 print "Checking for index required...\n" unless $silent;
1157 foreach my $table ( keys %indexes ) {
1158         #
1159         # read all indexes from $table
1160         #
1161         $sth = $dbh->prepare("show index from $table");
1162         $sth->execute;
1163         my %existingindexes;
1164         while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow ) {
1165                 $existingindexes{$key_name} = 1;
1166         }
1167         # read indexes to check
1168         my $tablerows = $indexes{$table};
1169         foreach my $row (@$tablerows) {
1170                 my $key_name=$row->{indexname};
1171                 if ($existingindexes{$key_name} eq 1) {
1172 #                       print "$key_name existing";
1173                 } else {
1174                         print "\tCreating index $key_name in $table\n";
1175                         my $sql;
1176                         if ($row->{indexname} eq 'PRIMARY') {
1177                                 $sql = "alter table $table ADD PRIMARY KEY ($row->{content})";
1178                         } else {
1179                                 $sql = "alter table $table ADD INDEX $key_name ($row->{content}) $row->{type}";
1180                         }
1181                         $dbh->do($sql);
1182             print "Error $sql : $dbh->err \n" if $dbh->err;
1183                 }
1184         }
1185 }
1186
1187 #
1188 # check foreign keys and create them when needed
1189 #
1190 print "Checking for foreign keys required...\n" unless $silent;
1191 foreach my $table ( keys %foreign_keys ) {
1192         #
1193         # read all indexes from $table
1194         #
1195         $sth = $dbh->prepare("show table status like '$table'");
1196         $sth->execute;
1197         my $stat = $sth->fetchrow_hashref;
1198         # read indexes to check
1199         my $tablerows = $foreign_keys{$table};
1200         foreach my $row (@$tablerows) {
1201                 my $foreign_table=$row->{foreigntable};
1202                 if ($stat->{'Comment'} =~/$foreign_table/) {
1203 #                       print "$foreign_table existing\n";
1204                 } else {
1205                         print "\tCreating foreign key $foreign_table in $table\n";
1206                         # first, drop any orphan value in child table
1207                         if ($row->{onDelete} ne "RESTRICT") {
1208                                 my $sql = "delete from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})";
1209                                 $dbh->do($sql);
1210                                 print "SQL ERROR: $sql : $dbh->err \n" if $dbh->err;
1211                         }
1212                         my $sql="alter table $table ADD FOREIGN KEY $row->{key} ($row->{key}) REFERENCES $row->{foreigntable} ($row->{foreignkey})";
1213                         $sql .= " on update ".$row->{onUpdate} if $row->{onUpdate};
1214                         $sql .= " on delete ".$row->{onDelete} if $row->{onDelete};
1215                         $dbh->do($sql);
1216                         if ($dbh->err) {
1217                                 print "====================
1218 An error occured during :
1219 \t$sql
1220 It probably means there is something wrong in your DB : a row ($table.$row->{key}) refers to a value in $row->{foreigntable}.$row->{foreignkey} that does not exist. solve the problem and run updater again (or just the previous SQL statement).
1221 You can find those values with select
1222 \t$table.* from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})
1223 ====================\n
1224 ";
1225                         }
1226                 }
1227         }
1228 }
1229
1230 #
1231 # SPECIFIC STUFF
1232 #
1233 #
1234 # create frameworkcode row in biblio table & fill it with marc_biblio.frameworkcode.
1235 #
1236
1237 # 1st, get how many biblio we will have to do...
1238 $sth = $dbh->prepare('select count(*) from marc_biblio');
1239 $sth->execute;
1240 my ($totaltodo) = $sth->fetchrow;
1241
1242 $sth = $dbh->prepare("show columns from biblio");
1243 $sth->execute();
1244 my $definitions;
1245 my $bibliofwexist=0;
1246 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
1247         $bibliofwexist=1 if $column eq 'frameworkcode';
1248 }
1249 unless ($bibliofwexist) {
1250         print "moving biblioframework to biblio table\n";
1251         $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
1252         $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
1253         $sth->execute;
1254         my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
1255         my $totaldone=0;
1256         while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
1257                 $sth_update->execute($frameworkcode,$biblionumber);
1258                 $totaldone++;
1259                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
1260         }
1261         print "\rdone\n";
1262 }
1263
1264 #
1265 # moving MARC data from marc_subfield_table to biblioitems.marc
1266 #
1267 $sth = $dbh->prepare("show columns from biblioitems");
1268 $sth->execute();
1269 my $definitions;
1270 my $marcdone=0;
1271 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
1272         $marcdone=1 if ($type eq 'blob' && $column eq 'marc') ;
1273 }
1274 unless ($marcdone) {
1275         print "moving MARC record to biblioitems table\n";
1276         # changing marc field type
1277         $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` BLOB NULL DEFAULT NULL ');
1278         # adding marc xml, just for convenience
1279         $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ');
1280         # moving data from marc_subfield_value to biblio
1281         $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio');
1282         $sth->execute;
1283         my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?');
1284         my $totaldone=0;
1285         while (my ($bibid,$biblionumber) = $sth->fetchrow) {
1286                 my $record = MARCgetbiblio($dbh,$bibid);
1287         #Force UTF-8 in record leader
1288                 $record->encoding('UTF-8');
1289                 print $record->as_formatted if ($biblionumber==3902);
1290                 $sth_update->execute($record->as_usmarc(),$record->as_xml_record(),$biblionumber);
1291                 $totaldone++;
1292                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
1293         }
1294         print "\rdone\n";
1295 }
1296
1297
1298 # at last, remove useless fields
1299 foreach $table ( keys %uselessfields ) {
1300         my @fields = split /,/,$uselessfields{$table};
1301         my $fields;
1302         my $exists;
1303         foreach my $fieldtodrop (@fields) {
1304                 $fieldtodrop =~ s/\t//g;
1305                 $fieldtodrop =~ s/\n//g;
1306                 $exists =0;
1307                 $sth = $dbh->prepare("show columns from $table");
1308                 $sth->execute;
1309                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1310                 {
1311                         $exists =1 if ($column eq $fieldtodrop);
1312                 }
1313                 if ($exists) {
1314                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
1315                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
1316                         $sth->execute;
1317                 }
1318         }
1319 }    # foreach
1320
1321
1322 # MOVE all tables TO UTF-8 and innoDB
1323 $sth = $dbh->prepare("show table status");
1324 $sth->execute;
1325 while ( my $table = $sth->fetchrow_hashref ) {
1326 #       if ($table->{Engine} ne 'InnoDB') {
1327 #               $dbh->do("ALTER TABLE $table->{Name} TYPE = innodb");
1328 #               print "moving $table->{Name} to InnoDB\n";
1329 #       }
1330         unless ($table->{Collation} =~ /^utf8/) {
1331                 $dbh->do("ALTER TABLE $table->{Name} CONVERT TO CHARACTER SET utf8");
1332                 $dbh->do("ALTER TABLE $table->{Name} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
1333                 # FIXME : maybe a ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 would be better, def char set seems to work fine. If any problem encountered, let's try with convert !
1334                 print "moving $table->{Name} to utf8\n";
1335         } else {
1336         }
1337 }
1338
1339 $sth->finish;
1340
1341 #
1342 # those 2 subs are a copy of Biblio.pm, version 2.2.4
1343 # they are useful only once, for moving from 2.2 to 3.0
1344 # the MARCgetbiblio & MARCgetitem subs in Biblio.pm
1345 # are still here, but uses other tables
1346 # (the ones that are filled by updatedatabase !)
1347 #
1348
1349 sub MARCgetbiblio {
1350
1351     # Returns MARC::Record of the biblio passed in parameter.
1352     my ( $dbh, $bibid ) = @_;
1353     my $record = MARC::Record->new();
1354 #       warn "". $bidid;
1355
1356     my $sth =
1357       $dbh->prepare(
1358 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
1359                                  from marc_subfield_table
1360                                  where bibid=? order by tag,tagorder,subfieldorder
1361                          "
1362     );
1363     my $sth2 =
1364       $dbh->prepare(
1365         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
1366     $sth->execute($bibid);
1367     my $prevtagorder = 1;
1368     my $prevtag      = 'XXX';
1369     my $previndicator;
1370     my $field;        # for >=10 tags
1371     my $prevvalue;    # for <10 tags
1372     while ( my $row = $sth->fetchrow_hashref ) {
1373
1374         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
1375             $sth2->execute( $row->{'valuebloblink'} );
1376             my $row2 = $sth2->fetchrow_hashref;
1377             $sth2->finish;
1378             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
1379         }
1380         if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
1381             $previndicator .= "  ";
1382             if ( $prevtag < 10 ) {
1383                                 if ($prevtag ne '000') {
1384                         $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
1385                                 } else {
1386                                         $record->leader(sprintf("%24s",$prevvalue));
1387                                 }
1388             }
1389             else {
1390                 $record->add_fields($field) unless $prevtag eq "XXX";
1391             }
1392             undef $field;
1393             $prevtagorder  = $row->{tagorder};
1394             $prevtag       = $row->{tag};
1395             $previndicator = $row->{tag_indicator};
1396             if ( $row->{tag} < 10 ) {
1397                 $prevvalue = $row->{subfieldvalue};
1398             }
1399             else {
1400                 $field = MARC::Field->new(
1401                     ( sprintf "%03s", $prevtag ),
1402                     substr( $row->{tag_indicator} . '  ', 0, 1 ),
1403                     substr( $row->{tag_indicator} . '  ', 1, 1 ),
1404                     $row->{'subfieldcode'},
1405                     $row->{'subfieldvalue'}
1406                 );
1407             }
1408         }
1409         else {
1410             if ( $row->{tag} < 10 ) {
1411                 $record->add_fields( ( sprintf "%03s", $row->{tag} ),
1412                     $row->{'subfieldvalue'} );
1413             }
1414             else {
1415                 $field->add_subfields( $row->{'subfieldcode'},
1416                     $row->{'subfieldvalue'} );
1417             }
1418             $prevtag       = $row->{tag};
1419             $previndicator = $row->{tag_indicator};
1420         }
1421     }
1422
1423     # the last has not been included inside the loop... do it now !
1424     if ( $prevtag ne "XXX" )
1425     { # check that we have found something. Otherwise, prevtag is still XXX and we
1426          # must return an empty record, not make MARC::Record fail because we try to
1427          # create a record with XXX as field :-(
1428         if ( $prevtag < 10 ) {
1429             $record->add_fields( $prevtag, $prevvalue );
1430         }
1431         else {
1432
1433             #           my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
1434             $record->add_fields($field);
1435         }
1436     }
1437     return $record;
1438 }
1439
1440 sub MARCgetitem {
1441
1442     # Returns MARC::Record of the biblio passed in parameter.
1443     my ( $dbh, $bibid, $itemnumber ) = @_;
1444     my $record = MARC::Record->new();
1445
1446     # search MARC tagorder
1447     my $sth2 =
1448       $dbh->prepare(
1449 "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=?"
1450     );
1451     $sth2->execute( $bibid, $itemnumber );
1452     my ($tagorder) = $sth2->fetchrow_array();
1453
1454     #---- TODO : the leader is missing
1455     my $sth =
1456       $dbh->prepare(
1457 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
1458                                  from marc_subfield_table
1459                                  where bibid=? and tagorder=? order by subfieldcode,subfieldorder
1460                          "
1461     );
1462     $sth2 =
1463       $dbh->prepare(
1464         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
1465     $sth->execute( $bibid, $tagorder );
1466     while ( my $row = $sth->fetchrow_hashref ) {
1467         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
1468             $sth2->execute( $row->{'valuebloblink'} );
1469             my $row2 = $sth2->fetchrow_hashref;
1470             $sth2->finish;
1471             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
1472         }
1473         if ( $record->field( $row->{'tag'} ) ) {
1474             my $field;
1475
1476 #--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
1477             #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
1478             if ( length( $row->{'tag'} ) < 3 ) {
1479                 $row->{'tag'} = "0" . $row->{'tag'};
1480             }
1481             $field = $record->field( $row->{'tag'} );
1482             if ($field) {
1483                 my $x =
1484                   $field->add_subfields( $row->{'subfieldcode'},
1485                     $row->{'subfieldvalue'} );
1486                 $record->delete_field($field);
1487                 $record->add_fields($field);
1488             }
1489         }
1490         else {
1491             if ( length( $row->{'tag'} ) < 3 ) {
1492                 $row->{'tag'} = "0" . $row->{'tag'};
1493             }
1494             my $temp =
1495               MARC::Field->new( $row->{'tag'}, " ", " ",
1496                 $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
1497             $record->add_fields($temp);
1498         }
1499
1500     }
1501     return $record;
1502 }
1503
1504
1505 exit;
1506
1507 # $Log$
1508 # Revision 1.135  2006/04/15 02:37:03  tgarip1957
1509 # Marc record should be set to UTF-8 in leader.Force it.
1510 # XML should be with<record> wrappers
1511 #
1512 # Revision 1.134  2006/04/14 09:37:29  tipaul
1513 # improvements from SAN Ouest Provence :
1514 # * introducing a category_type into categories. It can be A (adult), C (children), P (Professionnal), I (institution/organisation).
1515 # * each category_type has it's own forms to create members.
1516 # * the borrowers table has been heavily modified (many fields changed), to get something more logic & readable
1517 # * reintroducing guarantor/guanrantee system that is now independant from hardcoded C/A for categories
1518 # * updating templates to fit template rules
1519 #
1520 # (see mail feb, 17 on koha-devel "new features for borrowers" for more details)
1521 #
1522 # Revision 1.133  2006/04/13 08:36:42  plg
1523 # new: function C4::Date::get_date_format_string_for_DHTMLcalendar based on
1524 # the system preference prefered date format.
1525 #
1526 # improvement: book fund list and budget list screen redesigned. Filters on
1527 # each field. Columns are not sortable yet. Using DHTML Calendar to fill date
1528 # fields instead of manual filling. Pagination system. From the book fund
1529 # list, you can reach the budget list, filtered on a book fund, or not. A
1530 # budget can be added only from book fund list screen.
1531 #
1532 # bug fixed: branchcode was missing in table aqbudget.
1533 #
1534 # bug fixed: when setting a branchcode to a book fund, all associated budgets
1535 # move to this branchcode.
1536 #
1537 # modification: when adding/modifying budget/fund, MySQL specific "REPLACE..."
1538 # statements replaced by standard SQL compliant statement.
1539 #
1540 # bug fixed: when adding/modifying a budget, if the book fund is associated to
1541 # a branch, the branch selection is disabled and set to the book fund branch.
1542 #
1543 # Revision 1.132  2006/04/06 12:37:05  hdl
1544 # Bugfixing : aqbookfund needed a field.
1545 #
1546 # Revision 1.131  2006/03/03 17:02:22  tipaul
1547 # commit for holidays and news management.
1548 # (some forgotten files)
1549 #
1550 # Revision 1.130  2006/03/03 16:35:21  tipaul
1551 # commit for holidays and news management.
1552 #
1553 # Contrib from Tümer Garip (from Turkey) :
1554 # * holiday :
1555 # in /tools/ the holiday.pl script let you define holidays (days where the library is closed), branch by branch. You can define 3 types of holidays :
1556 # - single day : only this day is closed
1557 # - repet weekly (like "sunday") : the day is holiday every week
1558 # - repet yearly (like "July, 4") : this day is closed every year.
1559 #
1560 # You can also put exception :
1561 # - sunday is holiday, but "2006 March, 5th" the library will be open
1562 #
1563 # The holidays are used for return date calculation : the return date is set to the next date where the library is open. A systempreference (useDaysMode) set ON (Calendar) or OFF (Normal) the calendar calculation.
1564 #
1565 # Revision 1.129  2006/02/27 18:19:33  hdl
1566 # New table used in overduerules.pl tools page.
1567 #
1568 # Revision 1.128  2006/01/25 15:16:06  tipaul
1569 # updating DB :
1570 # * removing useless tables
1571 # * adding useful indexes
1572 # * altering some columns definitions
1573 # * The goal being to have updater working fine for foreign keys.
1574 #
1575 # For me it's done, let me know if it works for you. You can see an updated schema of the DB (with constraints) on the wiki
1576 #
1577 # Revision 1.127  2006/01/24 17:57:17  tipaul
1578 # DB improvements : adding foreign keys on some tables. partial stuff done.
1579 #
1580 # Revision 1.126  2006/01/06 16:39:42  tipaul
1581 # synch'ing head and rel_2_2 (from 2.2.5, including npl templates)
1582 # Seems not to break too many things, but i'm probably wrong here.
1583 # at least, new features/bugfixes from 2.2.5 are here (tested on some features on my head local copy)
1584 #
1585 # - removing useless directories (koha-html and koha-plucene)
1586 #
1587 # Revision 1.125  2006/01/04 15:54:55  tipaul
1588 # utf8 is a : go for beta test in HEAD.
1589 # some explanations :
1590 # - updater/updatedatabase => will transform all tables in innoDB (not related to utf8, just to warn you) AND collate them in utf8 / utf8_general_ci. The SQL command is : ALTER TABLE tablename DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci.
1591 # - *-top.inc will show the pages in utf8
1592 # - THE HARD THING : for me, mysql-client and mysql-server were set up to communicate in iso8859-1, whatever the mysql collation ! Thus, pages were improperly shown, as datas were transmitted in iso8859-1 format ! After a full day of investigation, someone on usenet pointed "set NAMES 'utf8'" to explain that I wanted utf8. I could put this in my.cnf, but if I do that, ALL databases will "speak" in utf8, that's not what we want. Thus, I added a line in Context.pm : everytime a DB handle is opened, the communication is set to utf8.
1593 # - using marcxml field and no more the iso2709 raw marc biblioitems.marc field.
1594 #
1595 # Revision 1.124  2005/10/27 12:09:05  tipaul
1596 # new features for serial module :
1597 # - the last 5 issues are now shown, and their status can be changed (but not reverted to "waited", as there can be only one "waited")
1598 # - the library can create a "distribution list". this paper contains a list of borrowers (selected from the borrower list, or manually entered), and print it for a given issue. once printed, the sheet can be put on the issue and distributed to every reader on the list (one by one).
1599 #
1600 # Revision 1.123  2005/10/26 09:13:37  tipaul
1601 # big commit, still breaking things...
1602 #
1603 # * synch with rel_2_2. Probably the last non manual synch, as rel_2_2 should not be modified deeply.
1604 # * code cleaning (cleaning warnings from perl -w) continued
1605 #
1606 # Revision 1.122  2005/09/02 14:18:38  tipaul
1607 # new feature : image for itemtypes.
1608 #
1609 # * run updater/updatedatabase to create imageurl field in itemtypes.
1610 # * 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)
1611 # * go to OPAC, and search something. In the result list, you now have the picture instead of the text itemtype.
1612 #
1613 # Revision 1.121  2005/08/24 08:49:03  hdl
1614 # Adding a note field in serial table.
1615 # This will allow librarian to mention a note on a peculiar waiting serial number.
1616 #
1617 # Revision 1.120  2005/08/09 14:10:32  tipaul
1618 # 1st commit to go to zebra.
1619 # don't update your cvs if you want to have a working head...
1620 #
1621 # this commit contains :
1622 # * 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...
1623 # * 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.
1624 # * other files : get rid of bibid and use biblionumber instead.
1625 #
1626 # What is broken :
1627 # * does not do anything on zebra yet.
1628 # * if you rename marc_subfield_table, you can't search anymore.
1629 # * you can view a biblio & bibliodetails, go to MARC editor, but NOT save any modif.
1630 # * 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 ;-) )
1631 #
1632 # 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
1633 # 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.
1634 #
1635 # Revision 1.119  2005/08/04 16:07:58  tipaul
1636 # Synch really broke this script...
1637 #
1638 # Revision 1.118  2005/08/04 16:02:55  tipaul
1639 # oops... error in synch between 2.2 and head
1640 #
1641 # Revision 1.117  2005/08/04 14:24:39  tipaul
1642 # synch'ing 2.2 and head
1643 #
1644 # Revision 1.116  2005/08/04 08:55:54  tipaul
1645 # Letters / alert system, continuing...
1646 #
1647 # * adding a package Letters.pm, that manages Letters & alerts.
1648 # * 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)
1649 # * 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)
1650 # * 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.
1651 #
1652 # Note that the system should be generic enough to manage any type of alert.
1653 # 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 ;-) )
1654 #
1655 # Revision 1.115  2005/08/02 16:15:34  tipaul
1656 # adding 2 fields to letter system :
1657 # * module (acquisition, catalogue...) : it will be usefull to show the librarian only letters he may be interested by.
1658 # * title, that will be used as mail subject.
1659 #
1660 # Revision 1.114  2005/07/28 15:10:13  tipaul
1661 # 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.
1662 # the letter table contains 3 fields :
1663 # * code => the code of the letter
1664 # * name => the complete name of the letter
1665 # * content => the complete text. It's a TEXT field type, so has no limits.
1666 #
1667 # My next goal now is to work on point 2-I "serial issue alert"
1668 # 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.
1669 # (see mail on koha-devel, 2005/04/07)
1670 #
1671 # The "serial issue alert" will be the 1st to use this letter system that probably needs some tweaking ;-)
1672 #
1673 # Once it will be stabilised default letters (in any languages) could be added during installer to help the library begin with this new feature.
1674 #
1675 # Revision 1.113  2005/07/28 08:38:41  tipaul
1676 # 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 :
1677 # * ReturnBeforeExpiry = yes => return date can't be after expiry date
1678 # * ReturnBeforeExpiry = no  => return date can be after expiry date
1679 #
1680 # Revision 1.112  2005/07/26 08:19:47  hdl
1681 # Adding IndependantBranches System preference variable in order to manage Branch independancy.
1682 #
1683 # Revision 1.111  2005/07/25 15:35:38  tipaul
1684 # we have decided that moving to Koha 3.0 requires being already in Koha 2.2.x
1685 # So, the updatedatabase script can highly be cleaned (90% removed).
1686 # Let's play with the new Koha DB structure now ;-)
1687 #