to get rid of pesky log message complaining about favicon.ico
[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 lib "/usr/koha200pre2/modules";
16 use strict;
17
18 # CPAN modules
19 use DBI;
20 use Getopt::Long;
21 # Koha modules
22 use C4::Context;
23
24 # FIXME - The user might be installing a new database, so can't rely
25 # on /etc/koha.conf anyway.
26
27 my $debug = 0;
28
29 my (
30     $sth, $sti,
31     $query,
32     %existingtables,    # tables already in database
33     %types,
34     $table,
35     $column,
36     $type, $null, $key, $default, $extra,
37     $prefitem,          # preference item in systempreferences table
38 );
39
40 my $silent;
41 GetOptions(
42         's' =>\$silent
43         );
44 my $dbh = C4::Context->dbh;
45 print "connected to your DB. Checking & modifying it\n" unless $silent;
46
47 #-------------------
48 # Defines
49
50 # Tables to add if they don't exist
51 my %requiretables = (
52     shelfcontents => "( shelfnumber int not null,
53                                                         itemnumber int not null,
54                                                         flags int)",
55     bookshelf => "( shelfnumber int auto_increment primary key,
56                                                 shelfname char(255))",
57     z3950queue => "( id int auto_increment primary key,
58                                                 term text,
59                                                 type char(10),
60                                                 startdate int,
61                                                 enddate int,
62                                                 done smallint,
63                                                 results longblob,
64                                                 numrecords int,
65                                                 servers text,
66                                                 identifier char(30))",
67     z3950results => "( id int auto_increment primary key,
68                                                 queryid int,
69                                                 server char(255),
70                                                 startdate int,
71                                                 enddate int,
72                                                 results longblob,
73                                                 numrecords int,
74                                                 numdownloaded int,
75                                                 highestseen int,
76                                                 active smallint)",
77     branchrelations => "( branchcode varchar(4),
78                                                         categorycode varchar(4))",
79     websites => "( websitenumber int(11) NOT NULL auto_increment,
80                                                 biblionumber int(11) NOT NULL default '0',
81                                                 title text,
82                                                 description text,
83                                                 url varchar(255),
84                                                 PRIMARY KEY (websitenumber) )",
85     marcrecorddone => "( isbn char(40),
86                                                                 issn char(40),
87                                                                 lccn char(40),
88                                                                 controlnumber char(40))",
89     uploadedmarc => "( id int(11) NOT NULL auto_increment PRIMARY KEY,
90                                                         marc longblob,
91                                                         hidden smallint(6) default NULL,
92                                                         name varchar(255) default NULL)",
93     ethnicity => "( code varchar(10) NOT NULL default '',
94                                         name varchar(255) default NULL,
95                                         PRIMARY KEY  (code)   )",
96     sessions => "( sessionID varchar(255) NOT NULL default '',
97                                                 userid varchar(255) default NULL,
98                                                 ip varchar(16) default NULL,
99                                                 lasttime int,
100                                                 PRIMARY KEY (sessionID)   )",
101     sessionqueries => "( sessionID varchar(255) NOT NULL default '',
102                                                                 userid char(100) NOT NULL default '',
103                                                                 ip char(18) NOT NULL default '',
104                                                                 url text NOT NULL default ''  )",
105     bibliothesaurus => "( id bigint(20) NOT NULL auto_increment,
106                                                         freelib char(255) NOT NULL default '',
107                                                         stdlib char(255) NOT NULL default '',
108                                                         category char(10) NOT NULL default '',
109                                                         level tinyint(4) NOT NULL default '1',
110                                                         hierarchy char(80) NOT NULL default '',
111                                                         father char(80) NOT NULL default '',
112                                                         PRIMARY KEY  (id),
113                                                         KEY freelib (freelib),
114                                                         KEY stdlib (stdlib),
115                                                         KEY category (category),
116                                                         KEY hierarchy (hierarchy)
117                                                         )",
118     marc_biblio => "(
119                                                 bibid bigint(20) unsigned NOT NULL auto_increment,
120                                                 biblionumber int(11) NOT NULL default '0',
121                                                 datecreated date NOT NULL default '0000-00-00',
122                                                 datemodified date default NULL,
123                                                 origincode char(20) default NULL,
124                                                 PRIMARY KEY  (bibid),
125                                                 KEY origincode (origincode),
126                                                 KEY biblionumber (biblionumber)
127                                                 ) ",
128     marc_blob_subfield => "(
129                                         blobidlink bigint(20) NOT NULL auto_increment,
130                                         subfieldvalue longtext NOT NULL,
131                                         PRIMARY KEY  (blobidlink)
132                                         ) ",
133     marc_subfield_structure => "(
134                                                 tagfield char(3) NOT NULL default '',
135                                                 tagsubfield char(1) NOT NULL default '',
136                                                 liblibrarian char(255) NOT NULL default '',
137                                                 libopac char(255) NOT NULL default '',
138                                                 repeatable tinyint(4) NOT NULL default '0',
139                                                 mandatory tinyint(4) NOT NULL default '0',
140                                                 kohafield char(40)  default NULL,
141                                                 tab tinyint(1) default NULL,
142                                                 authorised_value char(10) default NULL,
143                                                 thesaurus_category char(10) default NULL,
144                                                 value_builder char(80) default NULL,
145                                                 PRIMARY KEY  (tagfield,tagsubfield),
146                                                 KEY kohafield (kohafield),
147                                                 KEY tab (tab)
148                                                 )",
149     marc_subfield_table => "(
150                                                 subfieldid bigint(20) unsigned NOT NULL auto_increment,
151                                                 bibid bigint(20) unsigned NOT NULL default '0',
152                                                 tag char(3) NOT NULL default '',
153                                                 tagorder tinyint(4) NOT NULL default '1',
154                                                 tag_indicator char(2) NOT NULL default '',
155                                                 subfieldcode char(1) NOT NULL default '',
156                                                 subfieldorder tinyint(4) NOT NULL default '1',
157                                                 subfieldvalue varchar(255) default NULL,
158                                                 valuebloblink bigint(20) default NULL,
159                                                 PRIMARY KEY  (subfieldid),
160                                                 KEY bibid (bibid),
161                                                 KEY tag (tag),
162                                                 KEY tag_indicator (tag_indicator),
163                                                 KEY subfieldorder (subfieldorder),
164                                                 KEY subfieldcode (subfieldcode),
165                                                 KEY subfieldvalue (subfieldvalue),
166                                                 KEY tagorder (tagorder)
167                                         )",
168     marc_tag_structure => "(
169                                         tagfield char(3) NOT NULL default '',
170                                         liblibrarian char(255) NOT NULL default '',
171                                         libopac char(255) NOT NULL default '',
172                                         repeatable tinyint(4) NOT NULL default '0',
173                                         mandatory tinyint(4) NOT NULL default '0',
174                                         authorised_value char(10) default NULL,
175                                         PRIMARY KEY  (tagfield)
176                                         )",
177     marc_word => "(
178                                 bibid bigint(20) NOT NULL default '0',
179                                 tag char(3) NOT NULL default '',
180                                 tagorder tinyint(4) NOT NULL default '1',
181                                 subfieldid char(1) NOT NULL default '',
182                                 subfieldorder tinyint(4) NOT NULL default '1',
183                                 word varchar(255) NOT NULL default '',
184                                 sndx_word varchar(255) NOT NULL default '',
185                                 KEY bibid (bibid),
186                                 KEY tag (tag),
187                                 KEY tagorder (tagorder),
188                                 KEY subfieldid (subfieldid),
189                                 KEY subfieldorder (subfieldorder),
190                                 KEY word (word),
191                                 KEY sndx_word (sndx_word)
192                         )",
193     marc_breeding => "(  id bigint(20) NOT NULL auto_increment,
194                                 file varchar(80) NOT NULL default '',
195                                 isbn varchar(10) NOT NULL default '',
196                                 title varchar(128) default NULL,
197                                 author varchar(80) default NULL,
198                                 marc text NOT NULL,
199                                 encoding varchar(40) default NULL,
200                                 PRIMARY KEY  (id),
201                                 KEY title (title),
202                                 KEY isbn (isbn)
203                         )",
204     authorised_values => "(id int(11) NOT NULL auto_increment,
205                                 category char(10) NOT NULL default '',
206                                 authorised_value char(80) NOT NULL default '',
207                                 lib char(80) NULL,
208                                 PRIMARY KEY  (id),
209                                 KEY name (category)
210                         )",
211     userflags => "( bit int(11) NOT NULL default '0',
212                                 flag char(30), flagdesc char(255),
213                                 defaulton int(11)
214                         )",
215         auth_types => "(
216                                         authtypecode char(10) not NULL,
217                                         authtypetext char(255) not NULL,
218                                         auth_tag_to_report char(3) not NULL,
219                                         summary text not NULL,
220                                         PRIMARY KEY (authtypecode)
221                         )",
222         biblio_framework => "(
223                                         frameworkcode char(4) not NULL,
224                                         frameworktext char(255) not NULL,
225                                         PRIMARY KEY (frameworkcode)
226                         )",
227     auth_subfield_structure => "(
228                                         authtypecode char(10) NOT NULL default '',
229                                         tagfield char(3) NOT NULL default '',
230                                         tagsubfield char(1) NOT NULL default '',
231                                         liblibrarian char(255) NOT NULL default '',
232                                         libopac char(255) NOT NULL default '',
233                                         repeatable tinyint(4) NOT NULL default '0',
234                                         mandatory tinyint(4) NOT NULL default '0',
235                                         tab tinyint(1) default NULL,
236                                         authorised_value char(10) default NULL,
237                                         value_builder char(80) default NULL,
238                                         seealso char(255) default NULL,
239                                         PRIMARY KEY  (authtypecode,tagfield,tagsubfield),
240                                         KEY tab (authtypecode,tab)
241                                         )",
242     auth_tag_structure => "(
243                                         authtypecode char(10) NOT NULL default '',
244                                         tagfield char(3) NOT NULL default '',
245                                         liblibrarian char(255) NOT NULL default '',
246                                         libopac char(255) NOT NULL default '',
247                                         repeatable tinyint(4) NOT NULL default '0',
248                                         mandatory tinyint(4) NOT NULL default '0',
249                                         authorised_value char(10) default NULL,
250                                         PRIMARY KEY  (authtypecode,tagfield)
251                                         )",
252     auth_header => "(
253                                                 authid bigint(20) unsigned NOT NULL auto_increment,
254                                                 authtypecode char(10) NOT NULL default '',
255                                                 datecreated date NOT NULL default '0000-00-00',
256                                                 datemodified date default NULL,
257                                                 origincode char(20) default NULL,
258                                                 PRIMARY KEY  (authid),
259                                                 KEY origincode (origincode)
260                                                 ) ",
261     auth_subfield_table => "(
262                                                 subfieldid bigint(20) unsigned NOT NULL auto_increment,
263                                                 authid bigint(20) unsigned NOT NULL default '0',
264                                                 tag char(3) NOT NULL default '',
265                                                 tagorder tinyint(4) NOT NULL default '1',
266                                                 tag_indicator char(2) NOT NULL default '',
267                                                 subfieldcode char(1) NOT NULL default '',
268                                                 subfieldorder tinyint(4) NOT NULL default '1',
269                                                 subfieldvalue varchar(255) default NULL,
270                                                 PRIMARY KEY  (subfieldid),
271                                                 KEY authid (authid),
272                                                 KEY tag (tag),
273                                                 KEY subfieldcode (subfieldcode),
274                                                 KEY subfieldvalue (subfieldvalue)
275                                         )",
276     auth_word => "(
277                                 authid bigint(20) NOT NULL default '0',
278                                 tagsubfield char(4) NOT NULL default '',
279                                 tagorder tinyint(4) NOT NULL default '1',
280                                 subfieldorder tinyint(4) NOT NULL default '1',
281                                 word varchar(255) NOT NULL default '',
282                                 sndx_word varchar(255) NOT NULL default '',
283                                 KEY authid (authid),
284                                 KEY marc_search (tagsubfield,word),
285                                 KEY word (word),
286                                 KEY sndx_word (sndx_word)
287                         )",
288         suggestions => "(
289                                 suggestionid int(8) NOT NULL auto_increment,
290                                 suggestedby int(11) NOT NULL default '0',
291                                 managedby int(11) default NULL ,
292                                 STATUS varchar(10) NOT NULL default '',
293                                 note text,
294                                 author varchar(80) default NULL ,
295                                 title varchar(80) default NULL ,
296                                 copyrightdate smallint(6) default NULL ,
297                                 publishercode varchar(255) default NULL ,
298                                 date timestamp(8) NOT NULL ,
299                                 volumedesc varchar(255) default NULL ,
300                                 publicationyear smallint(6) default '0',
301                                 place varchar(255) default NULL ,
302                                 isbn varchar(10) default NULL ,
303                                 mailoverseeing smallint(1) default '0',
304                                 biblionumber int(11) default NULL ,
305                                 PRIMARY KEY (suggestionid) ,
306                                 KEY suggestedby(suggestedby) ,
307                                 KEY managedby(managedby)
308                         )",
309         aqbasket => "(basketno int(11) NOT NULL auto_increment,
310                                 creationdate date,
311                                 closedate date,
312                                 booksellerid varchar(10),
313                                 authorisedby varchar(10),
314                                 booksellerinvoicenumber text,
315                                 PRIMARY KEY (basketno)
316                                 )",
317         serial => "(serialid int(11) NOT NULL auto_increment,
318                                 biblionumber varchar(100) NOT NULL default '',
319                                 subscriptionid varchar(100) NOT NULL default '',
320                                 serialseq varchar(100) NOT NULL default '',
321                                 status tinyint(4) NOT NULL default '0',
322                                 planneddate date NOT NULL default '0000-00-00',
323                                 PRIMARY KEY  (serialid)
324                                 )",
325         subscription => "(biblionumber int(11) NOT NULL default '0',
326                                                 subscriptionid int(11) NOT NULL auto_increment,
327                                                 librarian varchar(100) default '',
328                                                 startdate date default '0000-00-00',
329                                                 aqbooksellerid int(11) default '0',
330                                                 cost int(11) default '0',
331                                                 aqbudgetid int(11) default '0',
332                                                 weeklength tinyint(4) default '0',
333                                                 monthlength tinyint(4) default '0',
334                                                 numberlength tinyint(4) default '0',
335                                                 periodicity tinyint(4) default '0',
336                                                 dow varchar(100) default '',
337                                                 numberingmethod varchar(100) default '',
338                                                 notes text,
339                                                 status varchar(100) NOT NULL default '',
340                                                 add1 int(11) default 0,
341                                                 every1 int(11) default 0,
342                                                 whenmorethan1 int(11) default 0,
343                                                 setto1 int(11),
344                                                 lastvalue1 int(11),
345                                                 add2 int(11) default 0,
346                                                 every2 int(11) default 0,
347                                                 whenmorethan2 int(11) default 0,
348                                                 setto2 int(11),
349                                                 lastvalue2 int(11),
350                                                 add3 int(11) default 0,
351                                                 every3 int(11) default 0,
352                                                 innerloop1 int(11) default 0,
353                                                 innerloop2 int(11) default 0,
354                                                 innerloop3 int(11) default 0,
355                                                 whenmorethan3 int(11) default 0,
356                                                 setto3 int(11),
357                                                 lastvalue3 int(11),
358                                                 PRIMARY KEY  (subscriptionid)
359                                                 )",
360         subscriptionhistory => "(biblionumber int(11) NOT NULL default '0',
361                                                         subscriptionid int(11) NOT NULL default '0',
362                                                         histstartdate date NOT NULL default '0000-00-00',
363                                                         enddate date default '0000-00-00',
364                                                         missinglist longtext NOT NULL,
365                                                         recievedlist longtext NOT NULL,
366                                                         opacnote varchar(150) NOT NULL default '',
367                                                         librariannote varchar(150) NOT NULL default '',
368                                                         PRIMARY KEY  (subscriptionid),
369                                                         KEY biblionumber (biblionumber)
370                                                 )",
371     categorytable       => "(categorycode char(5) NOT NULL default '',
372                              description text default '',
373                              itemtypecodes text default '',
374                              PRIMARY KEY (categorycode)
375                             )",
376     subcategorytable       => "(subcategorycode char(5) NOT NULL default '',
377                              description text default '',
378                              itemtypecodes text default '',
379                              PRIMARY KEY (subcategorycode)
380                             )",
381     mediatypetable       => "(mediatypecode char(5) NOT NULL default '',
382                              description text default '',
383                              itemtypecodes text default '',
384                              PRIMARY KEY (mediatypecode)
385                             )",
386 );
387
388 my %requirefields = (
389     biblio        => { 'abstract' => 'text' },
390     deletedbiblio => { 'abstract' => 'text', 'marc' => 'blob' },
391     deleteditems => { 'marc' => 'blob', 'paidfor' => 'text', 'location' => 'varchar(80)'},
392     biblioitems   => {
393         'lccn' => 'char(25)',
394         'url'  => 'varchar(255)',
395         'marc' => 'text'
396     },
397     deletedbiblioitems => {
398         'lccn' => 'char(25)',
399         'url'  => 'varchar(255)',
400         'marc' => 'text'
401     },
402     branchtransfers => { 'datearrived'    => 'datetime' },
403     statistics      => { 'borrowernumber' => 'int(11)' },
404     aqbooksellers   => {
405         'invoicedisc' => 'float(6,4)',
406         'nocalc'      => 'int(11)'
407     },
408     borrowers => {
409                 'userid'        => 'char(30)',
410                 'password'      => 'char(30)',
411                 'flags'         => 'int(11)',
412                 'textmessaging' => 'varchar(30)',
413                 'zipcode' => 'varchar(25)',
414                 'homezipcode' => 'varchar(25)',
415                 'sort1' => 'char(80)',
416                 'sort2' => 'char(80)',
417     },
418     aqorders => { 'budgetdate' => 'date',
419                                 'sort1' => 'char(80)',
420                                 'sort2' => 'char(80)', },
421     aqbudget => {'aqbudgetid' => 'tinyint(4) auto_increment primary key'},
422     items => {'paidfor' => 'text', 'location' => 'char(80)'},
423
424     #added so that reference items are not available for reserves...
425     itemtypes         => { 'notforloan'  => 'smallint(6)' },
426     systempreferences => { 'explanation' => 'char(80)',
427                            'type' => 'char(20)',
428                            'options' => 'text' },
429     z3950servers      => { 'syntax'      => 'char(80)' },
430         marc_tag_structure =>{
431                                                         'frameworkcode' => 'char(4) not NULL default \'\''},
432     marc_subfield_structure =>{'seealso'  => 'char(255)',
433                                                         'frameworkcode' => 'char(4) not NULL default \'\'',
434                                                         'hidden' => 'tinyint(1)',
435                                                         'isurl' => 'tinyint(1)',
436                                                         'link' => 'char(80)',
437                                                         },
438     bookshelf => {'owner' => 'char(80)',
439                                         'category' => 'char(1)',
440                                 },
441     marc_biblio        => { 'frameworkcode' => 'char(4) not NULL default \'\'' },
442 );
443
444 my %dropable_table = (
445     classification => 'classification',
446     multipart      => 'multipart',
447     multivolume    => 'multivolume',
448     newitems       => 'newitems',
449     procedures     => 'procedures',
450     publisher      => 'publisher',
451     searchstats    => 'searchstats',
452     serialissues   => 'serialissues',
453 );
454
455 my %uselessfields = (
456         aqorders => "requisitionedby,authorisedby,booksellerid,
457                         deliverydays,followupdays,
458                         numberfollowupsallowed,numberfollowupssent,
459                         dateprinted,sourced,quantityreceiveddamaged,
460                         subscriptionfrom,subscriptionto
461                         "
462         );
463 # the other hash contains other actions that can't be done elsewhere. they are done
464 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
465
466 # The tabledata hash contains data that should be in the tables.
467 # The uniquefieldrequired hash entry is used to determine which (if any) fields
468 # must not exist in the table for this row to be inserted.  If the
469 # uniquefieldrequired entry is already in the table, the existing data is not
470 # modified, unless the forceupdate hash entry is also set.  Fields in the
471 # anonymous "forceupdate" hash will be forced to be updated to the default
472 # values given in the %tabledata hash.
473
474 my %tabledata = (
475     userflags => [
476         {
477             uniquefieldrequired => 'bit',
478             bit                 => 0,
479             flag                => 'superlibrarian',
480             flagdesc            => 'Access to all librarian functions',
481             defaulton           => 0
482         },
483         {
484             uniquefieldrequired => 'bit',
485             bit                 => 1,
486             flag                => 'circulate',
487             flagdesc            => 'Circulate books',
488             defaulton           => 0
489         },
490         {
491             uniquefieldrequired => 'bit',
492             bit                 => 2,
493             flag                => 'catalogue',
494             flagdesc            => 'View Catalogue (Librarian Interface)',
495             defaulton           => 0
496         },
497         {
498             uniquefieldrequired => 'bit',
499             bit                 => 3,
500             flag                => 'parameters',
501             flagdesc            => 'Set Koha system paramters',
502             defaulton           => 0
503         },
504         {
505             uniquefieldrequired => 'bit',
506             bit                 => 4,
507             flag                => 'borrowers',
508             flagdesc            => 'Add or modify borrowers',
509             defaulton           => 0
510         },
511         {
512             uniquefieldrequired => 'bit',
513             bit                 => 5,
514             flag                => 'permissions',
515             flagdesc            => 'Set user permissions',
516             defaulton           => 0
517         },
518         {
519             uniquefieldrequired => 'bit',
520             bit                 => 6,
521             flag                => 'reserveforothers',
522             flagdesc            => 'Reserve books for patrons',
523             defaulton           => 0
524         },
525         {
526             uniquefieldrequired => 'bit',
527             bit                 => 7,
528             flag                => 'borrow',
529             flagdesc            => 'Borrow books',
530             defaulton           => 1
531         },
532         {
533             uniquefieldrequired => 'bit',
534             bit                 => 8,
535             flag                => 'reserveforself',
536             flagdesc            => 'Reserve books for self',
537             defaulton           => 0
538         },
539         {
540             uniquefieldrequired => 'bit',
541             bit                 => 9,
542             flag                => 'editcatalogue',
543             flagdesc  => 'Edit Catalogue (Modify bibliographic/holdings data)',
544             defaulton => 0
545         },
546         {
547             uniquefieldrequired => 'bit',
548             bit                 => 10,
549             flag                => 'updatecharges',
550             flagdesc            => 'Update borrower charges',
551             defaulton           => 0
552         },
553         {
554             uniquefieldrequired => 'bit',
555             bit                 => 11,
556             flag                => 'acquisition',
557             flagdesc            => 'Acquisition and/or suggestion management',
558             defaulton           => 0
559         },
560         {
561             uniquefieldrequired => 'bit',
562             bit                 => 12,
563             flag                => 'management',
564             flagdesc            => 'Set library management parameters',
565             defaulton           => 0
566         },
567         {
568             uniquefieldrequired => 'bit',
569             bit                 => 13,
570             flag                => 'tools',
571             flagdesc            => 'Use tools (export, import, barcodes)',
572             defaulton           => 0
573         },        
574     ],
575     systempreferences => [
576         {
577             uniquefieldrequired => 'variable',
578             forceupdate         => { 'explanation' => 1,
579                                      'type' => 1 },
580             variable            => 'LibraryName',
581             value               => '<i><b>Koha<br/>Free Software ILS<br/><br/></b>Koha : a gift, a contribution<br/> in Maori</i>',
582             explanation         => 'Library name as shown on main opac page',
583             type                => ''
584
585         },
586         {
587             uniquefieldrequired => 'variable',
588             forceupdate         => { 'explanation' => 1,
589                                      'type' => 1 },
590             variable            => 'autoMemberNum',
591             value               => '1',
592             explanation         => 'Member number is auto-calculated',
593             type                => 'YesNo'
594
595         },
596         {
597             uniquefieldrequired => 'variable',
598             forceupdate         => { 'explanation' => 1,
599                                      'type' => 1,
600                                      'options' => 1 },
601             variable            => 'acquisitions',
602             value               => 'normal',
603             explanation         =>
604 'Normal, budget-based acquisitions, or Simple bibliographic-data acquisitions',
605             type                => 'Choice',
606             options             => 'simple|normal'
607         },
608         {
609             uniquefieldrequired => 'variable',
610             forceupdate         => { 'explanation' => 1,
611                                      'type' => 1,
612                                      'options' => 1 },
613             variable            => 'dateformat',
614             value               => 'metric',
615             explanation         =>
616             'date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy/mm/dd)',
617             type                => 'Choice',
618             options             => 'metric|us|iso'
619         },
620         {
621             uniquefieldrequired => 'variable',
622             variable            => 'template',
623             forceupdate         => { 'explanation' => 1,
624                                      'type' => 1 },
625             value               => 'default',
626             explanation         => 'Preference order for intranet interface templates',
627             type                => 'Themes'
628         },
629         {
630             uniquefieldrequired => 'variable',
631             variable            => 'autoBarcode',
632             forceupdate         => { 'explanation' => 1,
633                                      'type' => 1 },
634             value               => 'yes',
635             explanation         => 'Barcode is auto-calculated',
636             type                => 'YesNo'
637         },
638         {
639             uniquefieldrequired => 'variable',
640             variable            => 'insecure',
641             forceupdate         => { 'explanation' => 1,
642                                      'type' => 1 },
643             value               => 'no',
644             explanation         =>
645 'If YES, no auth at all is needed. Be careful if you set this to yes!',
646             type                => 'YesNo'
647         },
648         {
649             uniquefieldrequired => 'variable',
650             variable            => 'authoritysep',
651             forceupdate         => { 'explanation' => 1,
652                                      'type' => 1,
653                                      'options' => 1 },
654             value               => '--',
655             explanation         =>
656             'the separator used in authority/thesaurus. Usually --',
657             type                => 'free',
658             options             => '10'
659         },
660         {
661             uniquefieldrequired => 'variable',
662             variable            => 'opaclanguages',
663             forceupdate         => { 'explanation' => 1,
664                                      'type' => 1 },
665             value               => 'en',
666             explanation         => 'Set the preferred order for translations.  The top language will be tried first.',
667             type                => 'Languages'
668         },
669         {
670             uniquefieldrequired => 'variable',
671             variable            => 'opacthemes',
672             forceupdate         => { 'explanation' => 1,
673                                      'type' => 1 },
674             value               => 'css',
675             explanation         => 'Set the preferred order for themes.  The top theme will be tried first.',
676             type                => 'Themes'
677         },
678         {
679             uniquefieldrequired => 'variable',
680             variable            => 'timeout',
681             forceupdate         => { 'explanation' => 1,
682                                      'type' => 1 },
683             value               => '1200',
684             explanation         => 'Inactivity timeout for cookies authentication (in seconds)',
685             type                => 'Integer'
686         },
687         {
688             uniquefieldrequired => 'variable',
689             variable            => 'marc',
690             forceupdate         => { 'explanation' => 1,
691                                      'type' => 1 },
692             value               => 'yes',
693             explanation         => 'Turn on MARC support',
694             type                => 'YesNo'
695         },
696         {
697             uniquefieldrequired => 'variable',
698             variable            => 'marcflavour',
699             forceupdate         => { 'explanation' => 1,
700                                      'type' => 1,
701                                      'options' => 1},
702             value               => 'MARC21',
703             explanation         =>
704             'your MARC flavor (MARC21 or UNIMARC) used for character encoding',
705             type                => 'Choice',
706             options             => 'MARC21|UNIMARC'
707         },
708         {
709             uniquefieldrequired => 'variable',
710             variable            => 'checkdigit',
711             value               => 'none',
712             forceupdate         => { 'explanation' => 1,
713                                      'type' => 1,
714                                      'options' => 1},
715             explanation         => 'Validity checks on membership number: none or "Katipo" style checks',
716             type                => 'Choice',
717             options             => 'none|katipo'
718         },
719         {
720             uniquefieldrequired => 'variable',
721             variable            => 'maxoutstanding',
722             forceupdate         => { 'explanation' => 1,
723                                      'type' => 1 },
724             value               => '5',
725             explanation         =>
726             'maximum amount withstanding to be able make reserves ',
727             type                => 'Integer'
728         },
729         {
730             uniquefieldrequired => 'variable',
731             variable            => 'maxreserves',
732             forceupdate         => { 'explanation' => 1,
733                                      'type' => 1 },
734             value               => '5',
735             explanation         =>
736             'maximum number of reserves a member can make',
737             type                => 'Integer'
738
739         },
740         {
741             uniquefieldrequired => 'variable',
742             variable            => 'noissuescharge',
743             forceupdate         => { 'explanation' => 1,
744                                      'type' => 1 },
745             value               => '5',
746             explanation         =>
747             'maximum amount withstanding to be able to check out an item',
748             type                => 'Integer'
749
750         },
751         {
752             uniquefieldrequired => 'variable',
753             variable            => 'KohaAdminEmailAddress',
754             forceupdate         => { 'explanation' => 1,
755                                      'type' => 1 },
756             value               => 'your.mail@here',
757             explanation => 'the email address where borrowers modifs are sent',
758             type                => 'free'
759         },
760         {
761             uniquefieldrequired => 'variable',
762             variable            => 'gist',
763             forceupdate         => { 'explanation' => 1,
764                                      'type' => 1 },
765             value               => '0.125',
766             explanation => 'the gist rate. NOT in %, but in numeric form (0.12 for 12%)',
767             type                => 'free'
768         },
769         {
770             uniquefieldrequired => 'variable',
771             variable            => 'printcirculationslips',
772             forceupdate         => { 'explanation' => 1,
773                                      'type' => 1 },
774             value               => '0',
775             explanation => 'if set to 1, print circulation slips. If set to 0, don\'t',
776             type                => 'free'
777         },
778         {
779             uniquefieldrequired => 'variable',
780             variable            => 'suggestion',
781             forceupdate         => { 'explanation' => 1,
782                                      'type' => 1 },
783             value               => '0',
784             explanation => 'if set to 1, suggestions are activated in OPAC',
785             type                => 'free'
786         },
787         {
788             uniquefieldrequired => 'variable',
789             variable            => 'ISBD',
790             forceupdate         => { 'explanation' => 1,
791                                      'type' => 1 },
792             value               => 'Fill with appropriate value...',
793             explanation => 'ISBD',
794             type                => 'free'
795         },
796         {
797             uniquefieldrequired => 'variable',
798             variable            => 'virtualshelves',
799             forceupdate         => { 'explanation' => 1,
800                                      'type' => 1 },
801             value               => '0',
802             explanation => 'Set virtual shelves management ON or OFF',
803             type                => 'YesNo'
804         },
805         {
806             uniquefieldrequired => 'variable',
807             variable            => 'itemcallnumber',
808             forceupdate         => { 'explanation' => 1,
809                                      'type' => 1 },
810             value               => '676a',
811             explanation => 'The MARC field/subfield that is used to calculate the itemcallnumber (in UNIMARC : 676a for Dewey, 680a for Loc)',
812             type                => 'free'
813         },
814         {
815             uniquefieldrequired => 'variable',
816             variable            => 'BiblioDefaultView',
817             value               => 'normal',
818             forceupdate         => { 'explanation' => 1,
819                                      'type' => 1,
820                                      'options' => 1},
821             explanation         => 'Define the default view of a biblio. Can be either normal, marc or isbd',
822             type                => 'Choice',
823             options             => 'normal|marc|isbd'
824         },
825         {
826             uniquefieldrequired => 'variable',
827             variable            => 'opacstylesheet',
828             value               => '',
829             forceupdate         => { 'explanation' => 1,
830                                      'type' => 1},
831             explanation         => 'Enter a complete URL to use an alternate stylesheet in OPAC',
832             type                => 'free',
833         },
834         {
835             uniquefieldrequired => 'variable',
836             variable            => 'delimiter',
837             value               => ';',
838             forceupdate         => { 'explanation' => 1,
839                                      'type' => 1},
840             explanation         => 'separator for reports exported to spreadsheet',
841             type                => 'free',
842         },
843         {
844             uniquefieldrequired => 'variable',
845             variable            => 'MIME',
846             value               => 'OPENOFFICE.ORG',
847             forceupdate         => { 'explanation' => 1,
848                                      'type' => 1,
849                                      'options' => 1},
850             explanation         => 'Define the default application for report exportations into files',
851                 type            => 'Choice',
852                 options         => 'EXCEL|OPENOFFICE.ORG'
853         },
854         {
855             uniquefieldrequired => 'variable',
856             variable            => 'Delimiter',
857             value               => ';',
858                 forceupdate             => { 'explanation' => 1,
859                                      'type' => 1,
860                                      'options' => 1},
861             explanation         => 'Define the default separator character for report exportations into files',
862                 type            => 'Choice',
863                 options         => ';|tabulation|,|/|\|#'
864         },
865     ],
866
867 );
868
869 my %fielddefinitions = (
870     printers => [
871         {
872             field   => 'printername',
873             type    => 'char(40)',
874             null    => '',
875             key     => 'PRI',
876             default => ''
877         },
878     ],
879     aqbookfund => [
880         {
881             field   => 'bookfundid',
882             type    => 'char(5)',
883             null    => '',
884             key     => 'PRI',
885             default => ''
886         },
887     ],
888     aqbudget => [
889         {
890             field   => 'aqbudgetid',
891             type    => 'tinyint(4)',
892             null    => '',
893             key     => 'PRI',
894                   default =>'',
895             extra => 'auto_increment'
896         },
897     ],
898     z3950servers => [
899         {
900             field   => 'id',
901             type    => 'int',
902             null    => '',
903             key     => 'PRI',
904             default => '',
905             extra   => 'auto_increment'
906         },
907     ],
908         marc_breeding => [
909         {
910             field   => 'z3950random',
911             type    => 'varchar(40)',
912             null    => 'NULL',
913             key     => '',
914             default => '',
915             extra   => ''
916         },
917         {
918             field   => 'encoding',
919             type    => 'varchar(40)',
920             null    => '',
921             key     => '',
922             default => '',
923             extra   => ''
924         },
925     ],
926 );
927
928 #-------------------
929 # Initialize
930
931 # Start checking
932
933 # Get version of MySQL database engine.
934 my $mysqlversion = `mysqld --version`;
935 $mysqlversion =~ /Ver (\S*) /;
936 $mysqlversion = $1;
937 if ( $mysqlversion ge '3.23' ) {
938     print "Could convert to MyISAM database tables...\n" unless $silent;
939 }
940
941 #---------------------------------
942 # Tables
943
944 # Collect all tables into a list
945 $sth = $dbh->prepare("show tables");
946 $sth->execute;
947 while ( my ($table) = $sth->fetchrow ) {
948     $existingtables{$table} = 1;
949 }
950
951
952 # Now add any missing tables
953 foreach $table ( keys %requiretables ) {
954     unless ( $existingtables{$table} ) {
955         print "Adding $table table...\n" unless $silent;
956         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
957         $sth->execute;
958         if ( $sth->err ) {
959             print "Error : $sth->errstr \n";
960             $sth->finish;
961         }    # if error
962     }    # unless exists
963 }    # foreach
964
965 # now drop useless tables
966 foreach $table ( keys %dropable_table ) {
967         if ( $existingtables{$table} ) {
968                 print "Dropping unused table $table\n" if $debug and not $silent;
969                 $dbh->do("drop table $table");
970                 if ( $dbh->err ) {
971                         print "Error : $dbh->errstr \n";
972                 }
973         }
974 }
975 unless ( $existingtables{'z3950servers'} ) {
976         #MJR: added syntax entries to close bug 624
977     print "Adding z3950servers table...\n" unless $silent;
978     my $sti = $dbh->prepare( "create table z3950servers (
979                                                                                 host char(255),
980                                                                                 port int,
981                                                                                 db char(255),
982                                                                                 userid char(255),
983                                                                                 password char(255),
984                                                                                 name text,
985                                                                                 id int,
986                                                                                 checked smallint,
987                                                                                 rank int,
988                                                                                 syntax char(80))"
989     );
990     $sti->execute;
991     $sti = $dbh->prepare( "insert into z3950servers
992                                                                 values ('z3950.loc.gov',
993                                                                 7090,
994                                                                 'voyager',
995                                                                 '', '',
996                                                                 'Library of Congress',
997                                                                 1, 1, 1, 'USMARC')"
998     );
999     $sti->execute;
1000 }
1001 unless ( $existingtables{'issuingrules'} ) {
1002         $dbh->do("alter table categoryitem rename issuingrules");
1003         $dbh->do("ALTER TABLE issuingrules ADD maxissueqty int(4) default NULL");
1004         $dbh->do("ALTER TABLE issuingrules ADD issuelength int(4) default NULL");
1005         $dbh->do("ALTER TABLE issuingrules ADD branchcode varchar(4) NOT NULL default ''");
1006         print "renaming categoryitem\n" unless $silent;
1007 }
1008
1009
1010 #---------------------------------
1011 # Columns
1012
1013 foreach $table ( keys %requirefields ) {
1014     print "Check table $table\n" if $debug and not $silent;
1015     $sth = $dbh->prepare("show columns from $table");
1016     $sth->execute();
1017     undef %types;
1018     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1019     {
1020         $types{$column} = $type;
1021     }    # while
1022     foreach $column ( keys %{ $requirefields{$table} } ) {
1023         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
1024         if ( !$types{$column} ) {
1025
1026             # column doesn't exist
1027             print "Adding $column field to $table table...\n" unless $silent;
1028             $query = "alter table $table
1029                         add column $column " . $requirefields{$table}->{$column};
1030             print "Execute: $query\n" if $debug;
1031             my $sti = $dbh->prepare($query);
1032             $sti->execute;
1033             if ( $sti->err ) {
1034                 print "**Error : $sti->errstr \n";
1035                 $sti->finish;
1036             }    # if error
1037         }    # if column
1038     }    # foreach column
1039 }    # foreach table
1040
1041 foreach $table ( keys %fielddefinitions ) {
1042         print "Check table $table\n" if $debug;
1043         $sth = $dbh->prepare("show columns from $table");
1044         $sth->execute();
1045         my $definitions;
1046         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1047         {
1048                 $definitions->{$column}->{type}    = $type;
1049                 $definitions->{$column}->{null}    = $null;
1050                 $definitions->{$column}->{key}     = $key;
1051                 $definitions->{$column}->{default} = $default;
1052                 $definitions->{$column}->{extra}   = $extra;
1053         }    # while
1054         my $fieldrow = $fielddefinitions{$table};
1055         foreach my $row (@$fieldrow) {
1056                 my $field   = $row->{field};
1057                 my $type    = $row->{type};
1058                 my $null    = $row->{null};
1059                 my $key     = $row->{key};
1060                 my $default = $row->{default};
1061                 $default="''" unless $default;
1062                 my $extra   = $row->{extra};
1063                 my $def     = $definitions->{$field};
1064                 unless ( $type eq $def->{type}
1065                         && $null eq $def->{null}
1066                         && $key eq $def->{key}
1067                         && $default eq $def->{default}
1068                         && $extra eq $def->{extra} )
1069                 {
1070
1071                         if ( $null eq '' ) {
1072                                 $null = 'NOT NULL';
1073                         }
1074                         if ( $key eq 'PRI' ) {
1075                                 $key = 'PRIMARY KEY';
1076                         }
1077                         unless ( $extra eq 'auto_increment' ) {
1078                                 $extra = '';
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 ?");
1091                         } else {
1092                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ?");
1093                         }
1094                         $sth->execute($default);
1095                         print "  Alter $field in $table\n" unless $silent;
1096                 }
1097         }
1098 }
1099
1100 # Get list of columns from borrowers table
1101 my %itemtypes;
1102 my %nullenabled;
1103 $sth = $dbh->prepare("show columns from borrowers");
1104 $sth->execute;
1105 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1106 {
1107     $itemtypes{$column} = $type;
1108     $nullenabled{$column} = $null;
1109 }
1110
1111 unless ( $itemtypes{'cardnumber'} eq 'varchar(20)' ) {
1112     $itemtypes{'cardnumber'} =~ /varchar\((\d+)\)/;
1113     my $oldlength = $1;
1114     if ( $oldlength < 16 ) {
1115         print "Setting maximum cardnumber length to 16 (was $oldlength) and marking unique.\n" unless $silent;
1116         my $sti =
1117           $dbh->prepare(
1118             "alter table borrowers change cardnumber cardnumber varchar(16)");
1119         $sti->execute;
1120         $sti->finish;
1121         $sti =
1122           $dbh->prepare(
1123             "alter table borrowers drop index cardnumber");
1124         $sti->execute;
1125         $sti->finish;
1126         $sti =
1127           $dbh->prepare(
1128             "alter table borrowers add unique(cardnumber)");
1129         $sti->execute;
1130         $sti->finish;
1131     }
1132 }
1133 #
1134 # Get list of columns from items table
1135 $sth = $dbh->prepare("show columns from items");
1136 $sth->execute;
1137 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1138 {
1139     $itemtypes{$column} = $type;
1140     $nullenabled{$column} = $null;
1141 }
1142
1143 unless ( $itemtypes{'barcode'} eq 'varchar(20)' ) {
1144     $itemtypes{'barcode'} =~ /varchar\((\d+)\)/;
1145     my $oldlength = $1;
1146     if ( $oldlength < 20 ) {
1147         print "Setting maximum barcode length to 20 (was $oldlength).\n" unless $silent;
1148         my $sti =
1149           $dbh->prepare(
1150             "alter table items change barcode barcode varchar(20)");
1151         $sti->execute;
1152     }
1153 }
1154 #
1155 # dropping unique barcode index & setting barcode to null allowed.
1156 #
1157 $sth = $dbh->prepare("show index from items");
1158 $sth->execute;
1159 while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow )
1160 {
1161         if ($key_name eq 'barcode' && $non_unique eq 0) {
1162                 print "dropping BARCODE index to enable empty barcodes\n" unless $silent;
1163                 $dbh->do("ALTER TABLE `items` DROP INDEX `barcode`");
1164         }
1165 }
1166 $dbh->do("ALTER TABLE `items` CHANGE `barcode` `barcode` VARCHAR( 20 )") unless ($nullenabled{barcode} eq 'YES');
1167
1168 #
1169 # creating fulltext index in bibliothesaurus if needed
1170 #
1171 $sth = $dbh->prepare("show index from bibliothesaurus");
1172 $sth->execute;
1173 my $exists=0;
1174 while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow )
1175 {
1176         if ($key_name eq 'category_2') {
1177                 $exists=1;
1178         }
1179 }
1180 print "Creating fulltext index on bibliothesaurus\n" unless $exists or $silent;
1181 $dbh->do('create fulltext index category_2 on bibliothesaurus (category,freelib)') unless $exists;
1182
1183 #
1184 # creating  index in z3950results if needed
1185 #
1186 $sth = $dbh->prepare("show index from z3950results");
1187 $sth->execute;
1188 my $exists=0;
1189 while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow )
1190 {
1191         if ($key_name eq 'query_server') {
1192                 $exists=1;
1193         }
1194 }
1195 print "Creating  index on z3950results\n" unless $exists or $silent;
1196 $dbh->do('create unique index query_server on z3950results (queryid,server)') unless $exists;
1197
1198 # changing z3950daemon field to NULL in marc_breeding
1199 $dbh->do("ALTER TABLE `marc_breeding` CHANGE `z3950random` `z3950random` VARCHAR( 40 )");
1200
1201 # making borrowernumber an auto_increment field
1202 $dbh->do("ALTER TABLE `borrowers` CHANGE `borrowernumber` `borrowernumber` INTEGER auto_increment");
1203
1204 # changing indexes in marc_*_structure to use frameworkcode
1205 $dbh->do('alter table marc_subfield_structure drop index tab');
1206 $dbh->do('create index tab on marc_subfield_structure (frameworkcode,tab)');
1207 $dbh->do('alter table marc_subfield_structure drop index kohafield');
1208 $dbh->do('create index kohafield on marc_subfield_structure (frameworkcode,kohafield)');
1209
1210
1211 # extending the timestamp in branchtransfers...
1212 my %branchtransfers;
1213
1214 $sth = $dbh->prepare("show columns from branchtransfers");
1215 $sth->execute;
1216 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1217 {
1218     $branchtransfers{$column} = $type;
1219 }
1220
1221 unless ( $branchtransfers{'datesent'} eq 'datetime' ) {
1222     print "Setting type of datesent in branchtransfers to datetime.\n" unless $silent;
1223     my $sti =
1224       $dbh->prepare(
1225         "alter table branchtransfers change datesent datesent datetime");
1226     $sti->execute;
1227 }
1228
1229 unless ( $branchtransfers{'datearrived'} eq 'datetime' ) {
1230     print "Setting type of datearrived in branchtransfers to datetime.\n" unless $silent;
1231     my $sti =
1232       $dbh->prepare(
1233         "alter table branchtransfers change datearrived datearrived datetime");
1234     $sti->execute;
1235 }
1236
1237 # changing the branchcategories table around...
1238 my %branchcategories;
1239
1240 $sth = $dbh->prepare("show columns from branchcategories");
1241 $sth->execute;
1242 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1243 {
1244     $branchcategories{$column} = $type;
1245 }
1246
1247 unless ( $branchcategories{'categorycode'} eq 'varchar(4)' ) {
1248     print
1249 "Setting type of categorycode in branchcategories to varchar(4),\n and making the primary key.\n" unless $silent;
1250     my $sti =
1251       $dbh->prepare(
1252 "alter table branchcategories change categorycode categorycode varchar(4) not null"
1253     );
1254     $sti->execute;
1255     $sti =
1256       $dbh->prepare(
1257         "alter table branchcategories add primary key (categorycode)");
1258     $sti->execute;
1259 }
1260
1261 unless ( $branchcategories{'categoryname'} eq 'text' ) {
1262     print "Changing branchcode in branchcategories to categoryname text.\n" unless $silent;
1263     my $sth =
1264       $dbh->prepare(
1265         "alter table branchcategories change branchcode categoryname text");
1266     $sth->execute;
1267 }
1268
1269 unless ( $branchcategories{'codedescription'} eq 'text' ) {
1270     print
1271 "Replacing branchholding in branchcategories with codedescription text.\n" unless $silent;
1272     my $sth =
1273       $dbh->prepare(
1274         "alter table branchcategories change branchholding codedescription text"
1275     );
1276     $sth->execute;
1277 }
1278
1279 # changing the items table around...
1280 my %items;
1281
1282 $sth = $dbh->prepare("show columns from items");
1283 $sth->execute;
1284 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1285 {
1286     $items{$column} = $type;
1287 }
1288
1289 if ($items{'bulk'} eq "varchar(30)") {
1290     print "  Setting callnumber in items table\n" unless $silent;
1291     my $sti =
1292       $dbh->prepare("ALTER TABLE `items` CHANGE `bulk` `itemcallnumber` VARCHAR( 30 ) DEFAULT NULL");
1293     $sti->execute;
1294     $sti = $dbh->prepare("update marc_subfield_structure set kohafield=\"items.itemcallnumber\" where kohafield=\"items.bulk\"");
1295     $sti->execute;
1296 }
1297
1298 # changing the marc_subfield_structure table around...
1299 my %marc_subfield_structure;
1300
1301 $sth = $dbh->prepare("show columns from marc_subfield_structure");
1302 $sth->execute;
1303 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1304 {
1305     $marc_subfield_structure{$column} = $type;
1306 }
1307
1308 if ($marc_subfield_structure{thesaurus_category}) {
1309     print "  changing thesaurus_category in marc_subfield_structure table\n" unless $silent;
1310     my $sti =
1311       $dbh->prepare("ALTER TABLE marc_subfield_structure CHANGE `thesaurus_category` `authtypecode` VARCHAR(10 ) DEFAULT NULL");
1312     $sti->execute;
1313 }
1314
1315 #
1316 # creating  index in issuingrules if needed
1317 #
1318 $sth = $dbh->prepare("show index from issuingrules");
1319 $sth->execute;
1320 my $exists=0;
1321 while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow )
1322 {
1323         if ($key_name eq 'PRIMARY') {
1324                 $exists=1;
1325         }
1326 }
1327 print "Creating  index on issuing rules\n" unless $exists or $silent;
1328 $dbh->do('ALTER TABLE issuingrules ADD PRIMARY KEY ( branchcode, categorycode, itemtype )') unless $exists;
1329
1330 $dbh->do('ALTER TABLE marc_tag_structure drop primary key');
1331 $dbh->do('ALTER TABLE marc_tag_structure ADD PRIMARY KEY ( frameworkcode, tagfield )');
1332
1333 $dbh->do('ALTER TABLE marc_subfield_structure drop primary key');
1334 $dbh->do('ALTER TABLE marc_subfield_structure ADD PRIMARY KEY ( frameworkcode, tagfield, tagsubfield )');
1335
1336 # Get list of columns from marc_word table
1337 my %marc_word;
1338 my %nullenabled;
1339 $sth = $dbh->prepare("show columns from marc_word");
1340 $sth->execute;
1341 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1342 {
1343     $marc_word{$column} = $type;
1344     $nullenabled{$column} = $null;
1345 }
1346 if ($marc_word{subfieldid}) {
1347         #create field tagsubfield, copy tag+subfieldid, then drop tag and subfieldid
1348         print "Modifying marc_word (concat on tag and subfield for better perfs)\n" unless $silent;
1349         $dbh->do("ALTER TABLE `marc_word` ADD `tagsubfield` CHAR( 4 ) NOT NULL AFTER `bibid`");
1350         $dbh->do("update marc_word set tagsubfield=concat(tag,subfieldid)");
1351         $dbh->do("alter table marc_word drop tag");
1352         $dbh->do("alter table marc_word drop subfieldid");
1353         $dbh->do("create index Search_Marc on marc_word (tagsubfield,word)");
1354 }
1355 # Populate tables with required data
1356
1357 # fill aqbasket if it's empty and aqorder is not
1358 # => it means it has just been created & must be filled
1359 $sth = $dbh->prepare("select count(*) from aqbasket");
1360 $sth->execute;
1361 if ($sth->fetchrow == 0) {
1362         $sth = $dbh->prepare("select count(*) from aqorders");
1363         $sth->execute;
1364         if ($sth->fetchrow >0) {
1365                 print "Populating new table aqbasket\n";
1366                 print "IMPORTANT NOTE: error message \"Duplicate entry 'X' for key 1\" may appear. it should not be a real trouble\n";
1367                 $sth=$dbh->prepare("select distinct basketno,booksellerid,authorisedby,entrydate,booksellerinvoicenumber from aqorders");
1368                 $sth->execute;
1369                 my ($basketno,$booksellerid,$authorisedby,$entrydate,$booksellerinvoicenumber);
1370                 my $sth2 = $dbh->prepare("insert into aqbasket (basketno,creationdate,booksellerid,authorisedby,booksellerinvoicenumber) values (?,?,?,?,?)");
1371                 while (($basketno,$booksellerid,$authorisedby,$entrydate,$booksellerinvoicenumber) = $sth->fetchrow) {
1372                         print "$basketno,$entrydate,$booksellerid,$authorisedby,$booksellerinvoicenumber\n";
1373                         $sth2->execute($basketno,$entrydate,$booksellerid,$authorisedby,$booksellerinvoicenumber);
1374                 }
1375         }
1376 }
1377 foreach my $table ( keys %tabledata ) {
1378     print "Checking for data required in table $table...\n" unless $silent;
1379     my $tablerows = $tabledata{$table};
1380     foreach my $row (@$tablerows) {
1381         my $uniquefieldrequired = $row->{uniquefieldrequired};
1382         my $uniquevalue         = $row->{$uniquefieldrequired};
1383         my $forceupdate         = $row->{forceupdate};
1384         my $sth                 =
1385           $dbh->prepare(
1386 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
1387         );
1388         $sth->execute($uniquevalue);
1389         if ($sth->rows) {
1390             foreach my $field (keys %$forceupdate) {
1391                 if ($forceupdate->{$field}) {
1392                     my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
1393                     $sth->execute($row->{$field}, $uniquevalue);
1394                 }
1395             }
1396         } else {
1397             print "Adding row to $table: " unless $silent;
1398             my @values;
1399             my $fieldlist;
1400             my $placeholders;
1401             foreach my $field ( keys %$row ) {
1402                 next if $field eq 'uniquefieldrequired';
1403                 next if $field eq 'forceupdate';
1404                 my $value = $row->{$field};
1405                 push @values, $value;
1406                 print "  $field => $value" unless $silent;
1407                 $fieldlist .= "$field,";
1408                 $placeholders .= "?,";
1409             }
1410             print "\n" unless $silent;
1411             $fieldlist    =~ s/,$//;
1412             $placeholders =~ s/,$//;
1413             my $sth =
1414               $dbh->prepare(
1415                 "insert into $table ($fieldlist) values ($placeholders)");
1416             $sth->execute(@values);
1417         }
1418     }
1419 }
1420
1421 # at last, remove useless fields
1422 foreach $table ( keys %uselessfields ) {
1423         my @fields = split /,/,$uselessfields{$table};
1424         my $fields;
1425         my $exists;
1426         foreach my $fieldtodrop (@fields) {
1427                 $fieldtodrop =~ s/\t//g;
1428                 $fieldtodrop =~ s/\n//g;
1429                 $exists =0;
1430                 $sth = $dbh->prepare("show columns from $table");
1431                 $sth->execute;
1432                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1433                 {
1434                         $exists =1 if ($column eq $fieldtodrop);
1435                 }
1436                 if ($exists) {
1437                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
1438                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
1439                         $sth->execute;
1440                 }
1441         }
1442 }    # foreach
1443
1444
1445 $sth->finish;
1446
1447 exit;
1448
1449 # $Log$
1450 # Revision 1.104  2005/06/01 21:35:05  genjimoto
1451 # New Feature: catalogsearch() has a new parameter, $sqlstring. A developer puts into it whatever they want to tack onto the end of the where statement. See usage in opac-search.pl
1452 #
1453 # Revision 1.103  2005/05/04 09:04:52  tipaul
1454 # synch'ing 2.2 and head
1455 #
1456 # Revision 1.100.2.2  2005/03/29 15:41:43  tipaul
1457 # * new permissions : management & tools. You now have 2 new permissions :
1458 #       - management : means the user can manage library parameters, but NOT system parameters.
1459 #       - parameters : means the user can manage all parameters (including system parameters : marc structure, authorised values, system preferences. Was the only flag previously existing)
1460 #       - tools : means the user can import/export datas & edit barcodes.
1461 # note that for compatibility reasons, a user having "parameters" can access everything.
1462 # * new permission scheme. In every template new variables are available. They are written CAN_user_permission, with permission being one of the permission flag. templates can now show or hidde menu entries depending on user permissions. For example, a user with just circ permissions should have only the "circulation" button on home page. Templates are NOT updated in this version (except for system parameters, as proof of concept), they will be in the next ones. But the scheme is ready.
1463 #
1464 # Revision 1.100.2.1  2005/03/17 17:15:18  tipaul
1465 # defaulting opacstylesheet to '' instead of 'normal' (that is stupid)
1466 #
1467 # Revision 1.100  2004/12/10 16:11:32  tipaul
1468 # Improvement : adding a systempref to define default view in OPAC (either normal, MARC or ISBD). Created automatically during install or update. Check that you have a Koha >> parameters >> systempreferences >> BiblioDefaultView, Variable type : Choice, Variable options : normal|marc|isbd
1469 #
1470 # Revision 1.99  2004/12/02 17:17:00  tipaul
1471 # adding acquisition permission
1472 #
1473 # Revision 1.98  2004/11/26 20:26:49  tipaul
1474 # bugfix for auth_header creation
1475 #
1476 # Revision 1.97  2004/11/23 09:11:08  tipaul
1477 # adding itemcallnumber entry
1478 #
1479 # Revision 1.96  2004/11/16 13:03:45  tipaul
1480 # removing ldap systempref, it's now in C4/Auth_with_ldap.pm separate package
1481 #
1482 # Revision 1.95  2004/11/08 19:57:32  tipaul
1483 # bugfix
1484 #
1485 # Revision 1.94  2004/09/06 10:00:29  tipaul
1486 # adding a "location" field to the library.
1487 # This field is useful when the callnumber contains no information on the room where the item is stored.
1488 # With this field, we now have 3 levels of informations to find a book :
1489 # * the branch.
1490 # * the location.
1491 # * the callnumber.
1492 #
1493 # This should be versatile enough to solve any storing method.
1494 # This hack is quite simple, due to the nice Biblio.pm API. The MARC => koha db link is automatically managed. Just add the link in the parameters section.
1495 #
1496 # Revision 1.93  2004/08/12 14:50:50  tipaul
1497 # bugfixes
1498 #
1499 # Revision 1.92  2004/08/06 16:38:42  tipaul
1500 # changing DB structure to calculate next issue number.
1501 # Seems to work fine.
1502 #
1503 # Still misses the date calculation & the test of end of subscription (maybe for monday ?)
1504 #
1505 # Revision 1.91  2004/07/15 09:52:28  tipaul
1506 # Acquisition & Suggestion :
1507 # * acquisition rewritte : create a aqbasket table to deal with "bookseller order header".
1508 # * add "close basket" feature : a closed basket can't be modified
1509 # * suggestion feature : manage suggestions in acquisition (after suggestion filled in OPAC)
1510 #
1511 # Revision 1.90  2004/07/06 08:24:18  tipaul
1512 # adding 2 free fields that can be used for sorting purposes
1513 #
1514 # Revision 1.89  2004/07/02 15:55:08  tipaul
1515 # Adding 2 new fields, called "sort1" and "sort2"
1516 # They can be used for sorting & statistics reasons by the library.
1517 #
1518 # Revision 1.88  2004/06/26 23:34:26  rangi
1519 # Fixing typo
1520 #
1521 # Revision 1.87  2004/06/23 13:03:09  tipaul
1522 # fixes in DB structure
1523 #
1524 # Revision 1.86  2004/06/22 11:30:57  tipaul
1525 # adding -s (silent) flag, to have a silent install.
1526 # only updater will be verbose
1527 #
1528 # Revision 1.85  2004/06/17 15:19:44  tipaul
1529 # missing Marc_Search index on marc_word
1530 #
1531 # Revision 1.84  2004/06/17 08:25:21  tipaul
1532 # DB modifs : merging tag & subfield in marc_word table
1533 #
1534 # Revision 1.83  2004/06/10 08:32:02  tipaul
1535 # MARC authority management (continued)
1536 #
1537 # Revision 1.82  2004/06/03 12:46:58  tipaul
1538 # * frameworks and itemtypes are independant
1539 #
1540 # WARNING : will work only if applied to a 2.0 base. some modifs have been done since last commit that will NOT be applied if you run updatedatabase again.
1541 #
1542 # Revision 1.81  2004/05/28 09:56:21  tipaul
1543 # bugfix
1544 #
1545 # Revision 1.80  2004/05/28 08:32:00  tipaul
1546 # adding :
1547 # * MARC authority file
1548 # * seealso & hidden in MARC biblio structure.
1549 #
1550 # Revision 1.79  2004/05/18 09:50:07  tipaul
1551 # *** empty log message ***
1552 #
1553 # Revision 1.78  2004/05/10 09:29:33  tipaul
1554 # css is now the default theme for OPAC.
1555 # It will be the theme used for improvements and new things in OPAC.
1556 #
1557 # Revision 1.77  2004/05/06 14:56:51  tipaul
1558 # adding table issuingrules (previously called categoryitem
1559 #
1560 # Revision 1.76  2004/05/03 09:32:25  tipaul
1561 # adding printcirculationsplit parameter (already existed, but was not in systempref by defaul)
1562 #
1563 # Revision 1.75  2004/04/14 19:49:00  tipaul
1564 # seealso field set to 255 chars
1565 #
1566 # Revision 1.74  2004/03/11 16:10:16  tipaul
1567 # *** empty log message ***
1568 #
1569 # Revision 1.73  2004/03/06 20:26:13  tipaul
1570 # adding seealso feature in MARC searches
1571 #