UpdateDatabases for 3.0.2
[koha.git] / installer / data / mysql / updatedatabase30.pl
1 #!/usr/bin/perl
2
3
4 # Database Updater
5 # This script checks for required updates to the database.
6
7 # Part of the Koha Library Software www.koha.org
8 # Licensed under the GPL.
9
10 # Bugs/ToDo:
11 # - Would also be a good idea to offer to do a backup at this time...
12
13 # NOTE:  If you do something more than once in here, make it table driven.
14
15 # NOTE: Please keep the version in kohaversion.pl up-to-date!
16
17 use strict;
18 # use warnings;
19
20 # CPAN modules
21 use DBI;
22 use Getopt::Long;
23 # Koha modules
24 use C4::Context;
25 use C4::Installer;
26
27 use MARC::Record;
28 use MARC::File::XML ( BinaryEncoding => 'utf8' );
29  
30 # FIXME - The user might be installing a new database, so can't rely
31 # on /etc/koha.conf anyway.
32
33 my $debug = 0;
34
35 my (
36     $sth, $sti,
37     $query,
38     %existingtables,    # tables already in database
39     %types,
40     $table,
41     $column,
42     $type, $null, $key, $default, $extra,
43     $prefitem,          # preference item in systempreferences table
44 );
45
46 my $silent;
47 GetOptions(
48     's' =>\$silent
49     );
50 my $dbh = C4::Context->dbh;
51 $|=1; # flushes output
52
53 =item
54
55     Deal with virtualshelves
56
57 =cut
58
59 my $DBversion = '3.00.01.000';
60 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
61     print "Upgrade to $DBversion done (start of 3.0.1)\n";
62     SetVersion ($DBversion);
63 }
64
65 $DBversion = '3.00.01.001';
66 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
67     # use statistics where available
68     $dbh->do("
69         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
70     ");
71     $dbh->do("
72         UPDATE issues iss
73         SET issuedate = (
74             SELECT max(datetime)
75             FROM statistics 
76             WHERE type = 'issue'
77             AND itemnumber = iss.itemnumber
78             AND borrowernumber = iss.borrowernumber
79         )
80         WHERE issuedate IS NULL;
81     ");  
82     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
83
84     # default to last renewal date
85     $dbh->do("
86         UPDATE issues
87         SET issuedate = lastreneweddate
88         WHERE issuedate IS NULL
89         and lastreneweddate IS NOT NULL
90     ");
91
92     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
93     if ($num_bad_issuedates > 0) {
94         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
95                      "Please check the issues table in your database.";
96     }
97     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)";
98     SetVersion($DBversion);
99 }
100
101 $DBversion = "3.00.01.002";
102 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
103     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowRenewalLimitOverride', '0', 'if ON, allows renewal limits to be overridden on the circulation screen',NULL,'YesNo')");
104     print "Upgrade to $DBversion done (add new syspref)\n";
105     SetVersion ($DBversion);
106 }
107
108 $DBversion = "3.00.01.003";
109 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
110         my $search=$dbh->selectall_arrayref("select * from systempreferences where variable='dontmerge'");
111         if (@$search){
112                 my $search=$dbh->selectall_arrayref("select * from systempreferences where variable='MergeAuthoritiesOnUpdate'");
113                 if (@$search){
114                 $dbh->do("DELETE FROM systempreferences set variable='dontmerge'");
115                 }
116                 else {
117                 $dbh->do("UPDATE systempreferences set variable='MergeAuthoritiesOnUpdate' ,value=1-value*1 WHERE variable='dontmerge'");
118                 }
119         }
120         else {
121         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('MergeAuthoritiesOnUpdate', '1', 'if ON, Updating authorities will automatically updates biblios',NULL,'YesNo')");
122         }
123     print "Upgrade to $DBversion done (add new syspref MergeAuthoritiesOnUpdate)\n";
124     SetVersion ($DBversion);
125 }
126
127 $DBversion = "3.00.01.004";
128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
129   if (lc(C4::Context->preference('marcflavour')) eq "unimarc"){
130     $dbh->do("INSERT IGNORE INTO `marc_tag_structure` (`tagfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `authorised_value`, `frameworkcode`) VALUES ('099', 'Informations locales', '', 0, 0, '', '');");
131     $dbh->do("INSERT IGNORE INTO `marc_tag_structure` (`frameworkcode`,`tagfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `authorised_value`) SELECT DISTINCT(frameworkcode),'099', 'Informations locales', '', 0, 0, '' from biblio_framework");
132     $dbh->do(<<ENDOFSQL);
133 INSERT IGNORE INTO marc_subfield_structure (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `seealso`, `link`, `defaultvalue`,frameworkcode )
134 VALUES ('099', 'c', 'date creation notice (koha)', '', 0, 0, 'biblio.datecreated', -1, '', '', '', NULL, 0, '', '', NULL, ''),
135 ('099', 'd', 'date modification notice (koha)', '', 0, 0, 'biblio.timestamp', -1, '', '', '', NULL, 0, '', '', NULL, ''),
136 ('995', '2', 'Perdu', '', 0, 0, 'items.itemlost', 10, '', '', '', NULL, 1, '', NULL, NULL, '');
137 ENDOFSQL
138     $dbh->do(<<ENDOFSQL1);
139 INSERT IGNORE INTO marc_subfield_structure (`frameworkcode`,`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, seealso, link, defaultvalue )
140 SELECT DISTINCT(frameworkcode), '099', 'c', 'date creation notice (koha)', '', 0, 0, 'biblio.datecreated', -1, '', '', '', NULL, 0, '', '', NULL from biblio_framework;
141 ENDOFSQL1
142     $dbh->do(<<ENDOFSQL2);
143 INSERT IGNORE INTO marc_subfield_structure (`frameworkcode`,`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, seealso, link, defaultvalue )
144 SELECT DISTINCT(frameworkcode), '099', 'd', 'date modification notice (koha)', '', 0, 0, 'biblio.timestamp', -1, '', '', '', NULL, 0, '', '', NULL from biblio_framework;
145 ENDOFSQL2
146     $dbh->do(<<ENDOFSQL3);
147 INSERT IGNORE INTO marc_subfield_structure (`frameworkcode`,`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, seealso, link, defaultvalue )
148 SELECT DISTINCT(frameworkcode), '995', '2', 'Perdu', '', 0, 0, 'items.itemlost', 10, '', '', '', NULL, 1, '', NULL, NULL from biblio_framework;
149 ENDOFSQL3
150       print "Upgrade to $DBversion done (updates MARC framework structure)\n";
151     }
152     SetVersion ($DBversion);
153 }
154
155 $DBversion = "3.00.01.005";
156 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
157    $dbh->do(<<ENDOFNOTFORLOANOVERRIDE);
158 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowNotForLoanOverride', '0', 'if ON, enables the librarian to choose when they want to check out a notForLoan regular item',NULL,'YesNo')
159 ENDOFNOTFORLOANOVERRIDE
160       print "Upgrade to $DBversion done (Adding AllowNotForLoanOverride System preference)\n";
161 }
162
163 $DBversion = "3.00.01.005";
164 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
165     $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine`");
166     print "Upgrade to $DBversion done (Adding a field in issuingrules table)\n";
167     SetVersion ($DBversion);
168 }
169
170 $DBversion = "3.00.01.006";
171 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
172     $dbh->do("ALTER TABLE `aqbudget` CHANGE `aqbudgetid` `aqbudgetid` INT( 11 ) NOT NULL AUTO_INCREMENT");
173     print "Upgrade to $DBversion done (Change the field)\n";
174     SetVersion ($DBversion);
175 }
176
177 $DBversion = "3.00.01.007";
178 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
179     $dbh->do(<<ENDOFRENEWAL);
180 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RenewalPeriodBase', 'date_due', 'Set whether the renewal date should be counted from the date_due or from the moment the Patron asks for renewal ','date_due|now','Choice');
181 ENDOFRENEWAL
182     print "Upgrade to $DBversion done (Change the field)\n";
183     SetVersion ($DBversion);
184 }
185 $DBversion = "3.00.02.001";
186 #01.00.005';
187 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
188     $dbh->do("
189         INSERT INTO `letter` (module, code, name, title, content)
190         VALUES('reserves', 'HOLD', 'Hold Available for Pickup', 'Hold Available for Pickup at <<branches.branchname>>', 'Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nYou have a hold available for pickup as of <<reserves.waitingdate>>:\r\n\r\nTitle: <<biblio.title>>\r\nAuthor: <<biblio.author>>\r\nCopy: <<items.copynumber>>\r\nLocation: <<branches.branchname>>\r\n<<branches.branchaddress1>>\r\n<<branches.branchaddress2>>\r\n<<branches.branchaddress3>>')
191     ");
192     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
193     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
194     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
195     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
196     SetVersion ($DBversion);
197 }
198
199 $DBversion = "3.00.02.002";
200 #$DBversion = '3.01.00.006';
201 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
202     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
203     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
204     SetVersion ($DBversion);
205 }
206
207 $DBversion = "3.00.02.003";
208 #$DBversion = "3.01.00.007";
209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
210     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
211     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
212     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
213     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
214     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
215     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
216     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
217     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
218     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
219     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
220     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
221     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
222     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
223     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
224     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
225     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
226     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
227     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
228     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
229     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
230     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
231     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10', explanation='Enter a specific hash for NoZebra indexes. Enter : \\\'indexname\\\' => \\\'100a,245a,500*\\\',\\\'index2\\\' => \\\'...\\\'' WHERE variable='NoZebraIndexes'");
232     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
233     SetVersion ($DBversion);
234 }
235
236
237 $DBversion = "3.00.02.004";
238 #$DBversion = "3.01.00.009";
239 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
240     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
241     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
242     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
243 }
244
245 $DBversion = "3.00.02.005";
246 #$DBversion = '3.01.00.010';
247 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
248     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
249     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
250     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
251     SetVersion ($DBversion);
252 }
253
254 $DBversion = "3.00.02.006";
255 #$DBversion = '3.01.00.011';
256 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
257
258     # Yes, the old value was ^M terminated.
259     my $bad_value = "function prepareEmailPopup(){\r\n  if (!document.getElementById) return false;\r\n  if (!document.getElementById('reserveemail')) return false;\r\n  rsvlink = document.getElementById('reserveemail');\r\n  rsvlink.onclick = function() {\r\n      doReservePopup();\r\n      return false;\r\n  }\r\n}\r\n\r\nfunction doReservePopup(){\r\n}\r\n\r\nfunction prepareReserveList(){\r\n}\r\n\r\naddLoadEvent(prepareEmailPopup);\r\naddLoadEvent(prepareReserveList);";
260
261     my $intranetuserjs = C4::Context->preference('intranetuserjs');
262     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
263         my $sql = <<'END_SQL';
264 UPDATE systempreferences
265 SET value = ''
266 WHERE variable = 'intranetuserjs'
267 END_SQL
268         $dbh->do($sql);
269     }
270     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
271     SetVersion($DBversion);
272 }
273
274
275 $DBversion = "3.00.02.007";
276 #$DBversion = '3.01.00.015';
277 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
278     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
279
280     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
281
282     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
283
284     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
285
286     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
287     SetVersion ($DBversion);
288 }
289
290
291
292 $DBversion = "3.00.02.008";
293 #$DBversion = "3.01.00.018";
294 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
295     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
296     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
297     SetVersion ($DBversion);
298 }
299
300
301 $DBversion = "3.00.02.009";
302 #$DBversion = '3.01.00.023';
303 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
304     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
305     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
306     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
307     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
308     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
309     SetVersion ($DBversion);
310 }
311
312 $DBversion = '3.00.02.010';
313 #$DBversion = '3.01.00.027';
314 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
315     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
316     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
317     SetVersion ($DBversion);
318 }
319
320 #$DBversion = '3.01.00.028';
321 $DBversion = '3.00.02.011';
322 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
323     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
324     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
325     print "Upgrade to $DBversion done (added AmazonReviews)\n";
326     SetVersion ($DBversion);
327 }
328
329 #$DBversion = '3.01.00.029';
330 $DBversion = '3.00.02.012';
331 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
332     $dbh->do(q( UPDATE language_rfc4646_to_iso639
333                 SET iso639_2_code = 'spa'
334                 WHERE rfc4646_subtag = 'es'
335                 AND   iso639_2_code = 'rus' )
336             );
337     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
338     SetVersion ($DBversion);
339 }
340
341 =item DropAllForeignKeys($table)
342
343   Drop all foreign keys of the table $table
344
345 =cut
346
347 sub DropAllForeignKeys {
348     my ($table) = @_;
349     # get the table description
350     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
351     $sth->execute;
352     my $vsc_structure = $sth->fetchrow;
353     # split on CONSTRAINT keyword
354     my @fks = split /CONSTRAINT /,$vsc_structure;
355     # parse each entry
356     foreach (@fks) {
357         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
358         $_ = /(.*) FOREIGN KEY.*/;
359         my $id = $1;
360         if ($id) {
361             # we have found 1 foreign, drop it
362             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
363             $id="";
364         }
365     }
366 }
367
368
369 =item TransformToNum
370
371   Transform the Koha version from a 4 parts string
372   to a number, with just 1 .
373
374 =cut
375
376 sub TransformToNum {
377     my $version = shift;
378     # remove the 3 last . to have a Perl number
379     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
380     return $version;
381 }
382
383 =item SetVersion
384
385     set the DBversion in the systempreferences
386
387 =cut
388
389 sub SetVersion {
390     my $kohaversion = TransformToNum(shift);
391     if (C4::Context->preference('Version')) {
392       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
393       $finish->execute($kohaversion);
394     } else {
395       my $finish=$dbh->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')");
396       $finish->execute($kohaversion);
397     }
398 }
399 exit;
400