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