Bug 11879: DBRev 21.06.00.007
[koha.git] / installer / data / mysql / updatedatabase.pl
1 #!/usr/bin/perl
2
3 # Database Updater
4 # This script checks for required updates to the database.
5
6 # Parts copyright Catalyst IT 2011
7
8 # Part of the Koha Library Software www.koha-community.org
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 #
22
23 # Bugs/ToDo:
24 # - Would also be a good idea to offer to do a backup at this time...
25
26 # NOTE:  If you do something more than once in here, make it table driven.
27
28 # NOTE: Please keep the version in kohaversion.pl up-to-date!
29
30 use Modern::Perl;
31
32 use feature 'say';
33
34 # CPAN modules
35 use DBI;
36 use Getopt::Long;
37 # Koha modules
38 use C4::Context;
39 use C4::Installer;
40 use Koha::Database;
41 use Koha;
42 use Koha::DateUtils;
43
44 use MARC::Record;
45 use MARC::File::XML ( BinaryEncoding => 'utf8' );
46
47 use File::Path qw[remove_tree]; # perl core module
48 use File::Slurp;
49
50 # FIXME - The user might be installing a new database, so can't rely
51 # on /etc/koha.conf anyway.
52
53 my (
54     $sth,
55     $query,
56     $table,
57     $type,
58 );
59
60 my $schema = Koha::Database->new()->schema();
61
62 my $silent;
63 GetOptions(
64     's' =>\$silent
65     );
66 my $dbh = C4::Context->dbh;
67 $|=1; # flushes output
68
69 local $dbh->{RaiseError} = 0;
70
71 # Record the version we are coming from
72
73 my $original_version = C4::Context->preference("Version");
74
75 # Deal with virtualshelves
76 my $DBversion = "3.00.00.001";
77 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
78     # update virtualshelves table to
79     #
80     $dbh->do("ALTER TABLE `bookshelf` RENAME `virtualshelves`");
81     $dbh->do("ALTER TABLE `shelfcontents` RENAME `virtualshelfcontents`");
82     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD `biblionumber` INT( 11 ) NOT NULL default '0' AFTER shelfnumber");
83     $dbh->do("UPDATE `virtualshelfcontents` SET biblionumber=(SELECT biblionumber FROM items WHERE items.itemnumber=virtualshelfcontents.itemnumber)");
84     # drop all foreign keys : otherwise, we can't drop itemnumber field.
85     DropAllForeignKeys('virtualshelfcontents');
86     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD KEY biblionumber (biblionumber)");
87     # create the new foreign keys (on biblionumber)
88     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `virtualshelfcontents_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE");
89     # re-create the foreign key on virtualshelf
90     $dbh->do("ALTER TABLE `virtualshelfcontents` ADD CONSTRAINT `shelfcontents_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
91     $dbh->do("ALTER TABLE `virtualshelfcontents` DROP `itemnumber`");
92     print "Upgrade to $DBversion done (virtualshelves)\n";
93     SetVersion ($DBversion);
94 }
95
96
97 $DBversion = "3.00.00.002";
98 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
99     $dbh->do("DROP TABLE sessions");
100     $dbh->do("CREATE TABLE `sessions` (
101   `id` varchar(32) NOT NULL,
102   `a_session` text NOT NULL,
103   UNIQUE KEY `id` (`id`)
104 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
105     print "Upgrade to $DBversion done (sessions uses CGI::session, new table structure for sessions)\n";
106     SetVersion ($DBversion);
107 }
108
109
110 $DBversion = "3.00.00.003";
111 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
112     if (C4::Context->preference("opaclanguages") eq "fr") {
113         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ReservesNeedReturns','0','Si ce paramètre est mis à 1, une réservation posée sur un exemplaire présent sur le site devra être passée en retour pour être disponible. Sinon, elle sera automatiquement disponible, Koha considère que le bibliothécaire place la réservation en ayant le document en mains','','YesNo')");
114     } else {
115         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ReservesNeedReturns','0','If set, a reserve done on an item available in this branch need a check-in, otherwise, a reserve on a specific item, that is on the branch & available is considered as available','','YesNo')");
116     }
117     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
118     SetVersion ($DBversion);
119 }
120
121
122 $DBversion = "3.00.00.004";
123 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
124     $dbh->do("INSERT INTO `systempreferences` VALUES ('DebugLevel','2','set the level of error info sent to the browser. 0=none, 1=some, 2=most','0|1|2','Choice')");
125     print "Upgrade to $DBversion done (adding DebugLevel systempref, in 'Admin' tab)\n";
126     SetVersion ($DBversion);
127 }
128
129 $DBversion = "3.00.00.005";
130 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
131     $dbh->do("CREATE TABLE `tags` (
132                     `entry` varchar(255) NOT NULL default '',
133                     `weight` bigint(20) NOT NULL default 0,
134                     PRIMARY KEY  (`entry`)
135                     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
136                 ");
137         $dbh->do("CREATE TABLE `nozebra` (
138                 `server` varchar(20)     NOT NULL,
139                 `indexname` varchar(40)  NOT NULL,
140                 `value` varchar(250)     NOT NULL,
141                 `biblionumbers` longtext NOT NULL,
142                 KEY `indexname` (`server`,`indexname`),
143                 KEY `value` (`server`,`value`))
144                 ENGINE=InnoDB DEFAULT CHARSET=utf8;
145                 ");
146     print "Upgrade to $DBversion done (adding tags and nozebra tables )\n";
147     SetVersion ($DBversion);
148 }
149
150 $DBversion = "3.00.00.006";
151 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
152     sanitize_zero_date('issues', 'issuedate');
153     print "Upgrade to $DBversion done (filled issues.issuedate with timestamp)\n";
154     SetVersion ($DBversion);
155 }
156
157 $DBversion = "3.00.00.007";
158 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
159     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SessionStorage','mysql','Use mysql or a temporary file for storing session data','mysql|tmp','Choice')");
160     print "Upgrade to $DBversion done (set SessionStorage variable)\n";
161     SetVersion ($DBversion);
162 }
163
164 $DBversion = "3.00.00.008";
165 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
166     $dbh->do("ALTER TABLE `biblio` ADD `datecreated` DATE NOT NULL AFTER `timestamp` ;");
167     $dbh->do("UPDATE biblio SET datecreated=timestamp");
168     print "Upgrade to $DBversion done (biblio creation date)\n";
169     SetVersion ($DBversion);
170 }
171
172 $DBversion = "3.00.00.009";
173 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
174
175     # Create backups of call number columns
176     # in case default migration needs to be customized
177     #
178     # UPGRADE NOTE: temp_upg_biblioitems_call_num should be dropped
179     #               after call numbers have been transformed to the new structure
180     #
181     # Not bothering to do the same with deletedbiblioitems -- assume
182     # default is good enough.
183     $dbh->do("CREATE TABLE `temp_upg_biblioitems_call_num` AS
184               SELECT `biblioitemnumber`, `biblionumber`,
185                      `classification`, `dewey`, `subclass`,
186                      `lcsort`, `ccode`
187               FROM `biblioitems`");
188
189     # biblioitems changes
190     $dbh->do("ALTER TABLE `biblioitems` CHANGE COLUMN `volumeddesc` `volumedesc` TEXT,
191                                     ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
192                                     ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
193                                     ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
194                                     ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
195                                     ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
196                                     ADD `totalissues` INT(10) AFTER `cn_sort`");
197
198     # default mapping of call number columns:
199     #   cn_class = concatentation of classification + dewey,
200     #              trimmed to fit -- assumes that most users do not
201     #              populate both classification and dewey in a single record
202     #   cn_item  = subclass
203     #   cn_source = left null
204     #   cn_sort = lcsort
205     #
206     # After upgrade, cn_sort will have to be set based on whatever
207     # default call number scheme user sets as a preference.  Misc
208     # script will be added at some point to do that.
209     #
210     $dbh->do("UPDATE `biblioitems`
211               SET cn_class = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
212                     cn_item = subclass,
213                     `cn_sort` = `lcsort`
214             ");
215
216     # Now drop the old call number columns
217     $dbh->do("ALTER TABLE `biblioitems` DROP COLUMN `classification`,
218                                         DROP COLUMN `dewey`,
219                                         DROP COLUMN `subclass`,
220                                         DROP COLUMN `lcsort`,
221                                         DROP COLUMN `ccode`");
222
223     # deletedbiblio changes
224     $dbh->do("ALTER TABLE `deletedbiblio` ALTER COLUMN `frameworkcode` SET DEFAULT '',
225                                         DROP COLUMN `marc`,
226                                         ADD `datecreated` DATE NOT NULL AFTER `timestamp`");
227     $dbh->do("UPDATE deletedbiblio SET datecreated = timestamp");
228
229     # deletedbiblioitems changes
230     $dbh->do("ALTER TABLE `deletedbiblioitems`
231                         MODIFY `publicationyear` TEXT,
232                         CHANGE `volumeddesc` `volumedesc` TEXT,
233                         MODIFY `collectiontitle` MEDIUMTEXT DEFAULT NULL AFTER `volumedesc`,
234                         MODIFY `collectionissn` TEXT DEFAULT NULL AFTER `collectiontitle`,
235                         MODIFY `collectionvolume` MEDIUMTEXT DEFAULT NULL AFTER `collectionissn`,
236                         MODIFY `editionstatement` TEXT DEFAULT NULL AFTER `collectionvolume`,
237                         MODIFY `editionresponsibility` TEXT DEFAULT NULL AFTER `editionstatement`,
238                         MODIFY `place` VARCHAR(255) DEFAULT NULL AFTER `size`,
239                         MODIFY `marc` LONGBLOB,
240                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `url`,
241                         ADD `cn_class` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
242                         ADD `cn_item` VARCHAR(10) DEFAULT NULL AFTER `cn_class`,
243                         ADD `cn_suffix` VARCHAR(10) DEFAULT NULL AFTER `cn_item`,
244                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_suffix`,
245                         ADD `totalissues` INT(10) AFTER `cn_sort`,
246                         ADD `marcxml` LONGTEXT NOT NULL AFTER `totalissues`,
247                         ADD KEY `isbn` (`isbn`),
248                         ADD KEY `publishercode` (`publishercode`)
249                     ");
250
251     $dbh->do("UPDATE `deletedbiblioitems`
252                 SET `cn_class` = SUBSTR(TRIM(CONCAT_WS(' ', `classification`, `dewey`)), 1, 30),
253                `cn_item` = `subclass`,
254                 `cn_sort` = `lcsort`
255             ");
256     $dbh->do("ALTER TABLE `deletedbiblioitems`
257                         DROP COLUMN `classification`,
258                         DROP COLUMN `dewey`,
259                         DROP COLUMN `subclass`,
260                         DROP COLUMN `lcsort`,
261                         DROP COLUMN `ccode`
262             ");
263
264     # deleteditems changes
265     $dbh->do("ALTER TABLE `deleteditems`
266                         MODIFY `barcode` VARCHAR(20) DEFAULT NULL,
267                         MODIFY `price` DECIMAL(8,2) DEFAULT NULL,
268                         MODIFY `replacementprice` DECIMAL(8,2) DEFAULT NULL,
269                         DROP `bulk`,
270                         MODIFY `itemcallnumber` VARCHAR(30) DEFAULT NULL AFTER `wthdrawn`,
271                         MODIFY `holdingbranch` VARCHAR(10) DEFAULT NULL,
272                         DROP `interim`,
273                         MODIFY `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER `paidfor`,
274                         DROP `cutterextra`,
275                         ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
276                         ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
277                         ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
278                         ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
279                         ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`,
280                         MODIFY `marc` LONGBLOB AFTER `uri`,
281                         DROP KEY `barcode`,
282                         DROP KEY `itembarcodeidx`,
283                         DROP KEY `itembinoidx`,
284                         DROP KEY `itembibnoidx`,
285                         ADD UNIQUE KEY `delitembarcodeidx` (`barcode`),
286                         ADD KEY `delitembinoidx` (`biblioitemnumber`),
287                         ADD KEY `delitembibnoidx` (`biblionumber`),
288                         ADD KEY `delhomebranch` (`homebranch`),
289                         ADD KEY `delholdingbranch` (`holdingbranch`)");
290     $dbh->do("UPDATE deleteditems SET `ccode` = `itype`");
291     $dbh->do("ALTER TABLE deleteditems DROP `itype`");
292     $dbh->do("UPDATE `deleteditems` SET `cn_sort` = `itemcallnumber`");
293
294     # items changes
295     $dbh->do("ALTER TABLE `items` ADD `cn_source` VARCHAR(10) DEFAULT NULL AFTER `onloan`,
296                                 ADD `cn_sort` VARCHAR(30) DEFAULT NULL AFTER `cn_source`,
297                                 ADD `ccode` VARCHAR(10) DEFAULT NULL AFTER `cn_sort`,
298                                 ADD `materials` VARCHAR(10) DEFAULT NULL AFTER `ccode`,
299                                 ADD `uri` VARCHAR(255) DEFAULT NULL AFTER `materials`
300             ");
301     $dbh->do("ALTER TABLE `items`
302                         DROP KEY `itembarcodeidx`,
303                         ADD UNIQUE KEY `itembarcodeidx` (`barcode`)");
304
305     # map items.itype to items.ccode and
306     # set cn_sort to itemcallnumber -- as with biblioitems.cn_sort,
307     # will have to be subsequently updated per user's default
308     # classification scheme
309     $dbh->do("UPDATE `items` SET `cn_sort` = `itemcallnumber`,
310                             `ccode` = `itype`");
311
312     $dbh->do("ALTER TABLE `items` DROP `cutterextra`,
313                                 DROP `itype`");
314
315     print "Upgrade to $DBversion done (major changes to biblio, biblioitems, items, and deleted* versions of same\n";
316     SetVersion ($DBversion);
317 }
318
319 $DBversion = "3.00.00.010";
320 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
321     $dbh->do("CREATE INDEX `userid` ON borrowers (`userid`) ");
322     print "Upgrade to $DBversion done (userid index added)\n";
323     SetVersion ($DBversion);
324 }
325
326 $DBversion = "3.00.00.011";
327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
328     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categorycode` `categorycode` varchar(10) ");
329     $dbh->do("ALTER TABLE `branchcategories` CHANGE `categoryname` `categoryname` varchar(32) ");
330     $dbh->do("ALTER TABLE `branchcategories` ADD COLUMN `categorytype` varchar(16) ");
331     $dbh->do("UPDATE `branchcategories` SET `categorytype` = 'properties'");
332     $dbh->do("ALTER TABLE `branchrelations` CHANGE `categorycode` `categorycode` varchar(10) ");
333     print "Upgrade to $DBversion done (added branchcategory type)\n";
334     SetVersion ($DBversion);
335 }
336
337 $DBversion = "3.00.00.012";
338 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
339     $dbh->do("CREATE TABLE `class_sort_rules` (
340                                `class_sort_rule` varchar(10) NOT NULL default '',
341                                `description` mediumtext,
342                                `sort_routine` varchar(30) NOT NULL default '',
343                                PRIMARY KEY (`class_sort_rule`),
344                                UNIQUE KEY `class_sort_rule_idx` (`class_sort_rule`)
345                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
346     $dbh->do("CREATE TABLE `class_sources` (
347                                `cn_source` varchar(10) NOT NULL default '',
348                                `description` mediumtext,
349                                `used` tinyint(4) NOT NULL default 0,
350                                `class_sort_rule` varchar(10) NOT NULL default '',
351                                PRIMARY KEY (`cn_source`),
352                                UNIQUE KEY `cn_source_idx` (`cn_source`),
353                                KEY `used_idx` (`used`),
354                                CONSTRAINT `class_source_ibfk_1` FOREIGN KEY (`class_sort_rule`)
355                                           REFERENCES `class_sort_rules` (`class_sort_rule`)
356                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
357     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type)
358               VALUES('DefaultClassificationSource','ddc',
359                      'Default classification scheme used by the collection. E.g., Dewey, LCC, etc.', NULL,'free')");
360     $dbh->do("INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
361                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
362                                ('lcc', 'Default filing rules for LCC', 'LCC'),
363                                ('generic', 'Generic call number filing rules', 'Generic')");
364     $dbh->do("INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`) VALUES
365                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey'),
366                             ('lcc', 'Library of Congress Classification', 1, 'lcc'),
367                             ('udc', 'Universal Decimal Classification', 0, 'generic'),
368                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic'),
369                             ('z', 'Other/Generic Classification Scheme', 0, 'generic')");
370     print "Upgrade to $DBversion done (classification sources added)\n";
371     SetVersion ($DBversion);
372 }
373
374 $DBversion = "3.00.00.013";
375 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
376     $dbh->do("CREATE TABLE `import_batches` (
377               `import_batch_id` int(11) NOT NULL auto_increment,
378               `template_id` int(11) default NULL,
379               `branchcode` varchar(10) default NULL,
380               `num_biblios` int(11) NOT NULL default 0,
381               `num_items` int(11) NOT NULL default 0,
382               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
383               `overlay_action` enum('replace', 'create_new', 'use_template') NOT NULL default 'create_new',
384               `import_status` enum('staging', 'staged', 'importing', 'imported', 'reverting', 'reverted', 'cleaned') NOT NULL default 'staging',
385               `batch_type` enum('batch', 'z3950') NOT NULL default 'batch',
386               `file_name` varchar(100),
387               `comments` mediumtext,
388               PRIMARY KEY (`import_batch_id`),
389               KEY `branchcode` (`branchcode`)
390               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
391     $dbh->do("CREATE TABLE `import_records` (
392               `import_record_id` int(11) NOT NULL auto_increment,
393               `import_batch_id` int(11) NOT NULL,
394               `branchcode` varchar(10) default NULL,
395               `record_sequence` int(11) NOT NULL default 0,
396               `upload_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
397               `import_date` DATE default NULL,
398               `marc` longblob NOT NULL,
399               `marcxml` longtext NOT NULL,
400               `marcxml_old` longtext NOT NULL,
401               `record_type` enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio',
402               `overlay_status` enum('no_match', 'auto_match', 'manual_match', 'match_applied') NOT NULL default 'no_match',
403               `status` enum('error', 'staged', 'imported', 'reverted', 'items_reverted') NOT NULL default 'staged',
404               `import_error` mediumtext,
405               `encoding` varchar(40) NOT NULL default '',
406               `z3950random` varchar(40) default NULL,
407               PRIMARY KEY (`import_record_id`),
408               CONSTRAINT `import_records_ifbk_1` FOREIGN KEY (`import_batch_id`)
409                           REFERENCES `import_batches` (`import_batch_id`) ON DELETE CASCADE ON UPDATE CASCADE,
410               KEY `branchcode` (`branchcode`),
411               KEY `batch_sequence` (`import_batch_id`, `record_sequence`)
412               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
413     $dbh->do("CREATE TABLE `import_record_matches` (
414               `import_record_id` int(11) NOT NULL,
415               `candidate_match_id` int(11) NOT NULL,
416               `score` int(11) NOT NULL default 0,
417               CONSTRAINT `import_record_matches_ibfk_1` FOREIGN KEY (`import_record_id`)
418                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
419               KEY `record_score` (`import_record_id`, `score`)
420               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
421     $dbh->do("CREATE TABLE `import_biblios` (
422               `import_record_id` int(11) NOT NULL,
423               `matched_biblionumber` int(11) default NULL,
424               `control_number` varchar(25) default NULL,
425               `original_source` varchar(25) default NULL,
426               `title` varchar(128) default NULL,
427               `author` varchar(80) default NULL,
428               `isbn` varchar(14) default NULL,
429               `issn` varchar(9) default NULL,
430               `has_items` tinyint(1) NOT NULL default 0,
431               CONSTRAINT `import_biblios_ibfk_1` FOREIGN KEY (`import_record_id`)
432                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
433               KEY `matched_biblionumber` (`matched_biblionumber`),
434               KEY `title` (`title`),
435               KEY `isbn` (`isbn`)
436               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
437     $dbh->do("CREATE TABLE `import_items` (
438               `import_items_id` int(11) NOT NULL auto_increment,
439               `import_record_id` int(11) NOT NULL,
440               `itemnumber` int(11) default NULL,
441               `branchcode` varchar(10) default NULL,
442               `status` enum('error', 'staged', 'imported', 'reverted') NOT NULL default 'staged',
443               `marcxml` longtext NOT NULL,
444               `import_error` mediumtext,
445               PRIMARY KEY (`import_items_id`),
446               CONSTRAINT `import_items_ibfk_1` FOREIGN KEY (`import_record_id`)
447                           REFERENCES `import_records` (`import_record_id`) ON DELETE CASCADE ON UPDATE CASCADE,
448               KEY `itemnumber` (`itemnumber`),
449               KEY `branchcode` (`branchcode`)
450               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
451
452     $dbh->do("INSERT INTO `import_batches`
453                 (`overlay_action`, `import_status`, `batch_type`, `file_name`)
454               SELECT distinct 'create_new', 'staged', 'z3950', `file`
455               FROM   `marc_breeding`");
456
457     $dbh->do("INSERT INTO `import_records`
458                 (`import_batch_id`, `import_record_id`, `record_sequence`, `marc`, `record_type`, `status`,
459                 `encoding`, `z3950random`, `marcxml`, `marcxml_old`)
460               SELECT `import_batch_id`, `id`, 1, `marc`, 'biblio', 'staged', `encoding`, `z3950random`, '', ''
461               FROM `marc_breeding`
462               JOIN `import_batches` ON (`file_name` = `file`)");
463
464     $dbh->do("INSERT INTO `import_biblios`
465                 (`import_record_id`, `title`, `author`, `isbn`)
466               SELECT `import_record_id`, `title`, `author`, `isbn`
467               FROM   `marc_breeding`
468               JOIN   `import_records` ON (`import_record_id` = `id`)");
469
470     $dbh->do("UPDATE `import_batches`
471               SET `num_biblios` = (
472               SELECT COUNT(*)
473               FROM `import_records`
474               WHERE `import_batch_id` = `import_batches`.`import_batch_id`
475               )");
476
477     $dbh->do("DROP TABLE `marc_breeding`");
478
479     print "Upgrade to $DBversion done (import_batches et al. added)\n";
480     SetVersion ($DBversion);
481 }
482
483 $DBversion = "3.00.00.014";
484 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
485     $dbh->do("ALTER TABLE subscription ADD lastbranch VARCHAR(4)");
486     print "Upgrade to $DBversion done (userid index added)\n";
487     SetVersion ($DBversion);
488 }
489
490 $DBversion = "3.00.00.015";
491 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
492     $dbh->do("CREATE TABLE `saved_sql` (
493            `id` int(11) NOT NULL auto_increment,
494            `borrowernumber` int(11) default NULL,
495            `date_created` datetime default NULL,
496            `last_modified` datetime default NULL,
497            `savedsql` text,
498            `last_run` datetime default NULL,
499            `report_name` varchar(255) default NULL,
500            `type` varchar(255) default NULL,
501            `notes` text,
502            PRIMARY KEY  (`id`),
503            KEY boridx (`borrowernumber`)
504         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
505     $dbh->do("CREATE TABLE `saved_reports` (
506            `id` int(11) NOT NULL auto_increment,
507            `report_id` int(11) default NULL,
508            `report` longtext,
509            `date_run` datetime default NULL,
510            PRIMARY KEY  (`id`)
511         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
512     print "Upgrade to $DBversion done (saved_sql and saved_reports added)\n";
513     SetVersion ($DBversion);
514 }
515
516 $DBversion = "3.00.00.016";
517 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
518     $dbh->do(" CREATE TABLE reports_dictionary (
519           id int(11) NOT NULL auto_increment,
520           name varchar(255) default NULL,
521           description text,
522           date_created datetime default NULL,
523           date_modified datetime default NULL,
524           saved_sql text,
525           area int(11) default NULL,
526           PRIMARY KEY  (id)
527         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
528     print "Upgrade to $DBversion done (reports_dictionary) added)\n";
529     SetVersion ($DBversion);
530 }
531
532 $DBversion = "3.00.00.017";
533 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
534     $dbh->do("ALTER TABLE action_logs DROP PRIMARY KEY");
535     $dbh->do("ALTER TABLE action_logs ADD KEY  timestamp (timestamp,user)");
536     $dbh->do("ALTER TABLE action_logs ADD action_id INT(11) NOT NULL FIRST");
537     $dbh->do("UPDATE action_logs SET action_id = if (\@a, \@a:=\@a+1, \@a:=1)");
538     $dbh->do("ALTER TABLE action_logs MODIFY action_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY");
539     print "Upgrade to $DBversion done (added column to action_logs)\n";
540     SetVersion ($DBversion);
541 }
542
543 $DBversion = "3.00.00.018";
544 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
545     $dbh->do("ALTER TABLE `zebraqueue`
546                     ADD `done` INT NOT NULL DEFAULT '0',
547                     ADD `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
548             ");
549     print "Upgrade to $DBversion done (adding timestamp and done columns to zebraque table to improve problem tracking) added)\n";
550     SetVersion ($DBversion);
551 }
552
553 $DBversion = "3.00.00.019";
554 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
555     $dbh->do("ALTER TABLE biblio MODIFY biblionumber INT(11) NOT NULL AUTO_INCREMENT");
556     $dbh->do("ALTER TABLE biblioitems MODIFY biblioitemnumber INT(11) NOT NULL AUTO_INCREMENT");
557     $dbh->do("ALTER TABLE items MODIFY itemnumber INT(11) NOT NULL AUTO_INCREMENT");
558     print "Upgrade to $DBversion done (made bib/item PKs auto_increment)\n";
559     SetVersion ($DBversion);
560 }
561
562 $DBversion = "3.00.00.020";
563 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
564     $dbh->do("ALTER TABLE deleteditems
565               DROP KEY `delitembarcodeidx`,
566               ADD KEY `delitembarcodeidx` (`barcode`)");
567     print "Upgrade to $DBversion done (dropped uniqueness of key on deleteditems.barcode)\n";
568     SetVersion ($DBversion);
569 }
570
571 $DBversion = "3.00.00.021";
572 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
573     $dbh->do("ALTER TABLE items CHANGE homebranch homebranch VARCHAR(10)");
574     $dbh->do("ALTER TABLE deleteditems CHANGE homebranch homebranch VARCHAR(10)");
575     $dbh->do("ALTER TABLE statistics CHANGE branch branch VARCHAR(10)");
576     $dbh->do("ALTER TABLE subscription CHANGE lastbranch lastbranch VARCHAR(10)");
577     print "Upgrade to $DBversion done (extended missed branchcode columns to 10 chars)\n";
578     SetVersion ($DBversion);
579 }
580
581 $DBversion = "3.00.00.022";
582 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
583     $dbh->do("ALTER TABLE items
584                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
585     $dbh->do("ALTER TABLE deleteditems
586                 ADD `damaged` tinyint(1) default NULL AFTER notforloan");
587     print "Upgrade to $DBversion done (adding damaged column to items table)\n";
588     SetVersion ($DBversion);
589 }
590
591 $DBversion = "3.00.00.023";
592 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
593      $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
594          VALUES ('yuipath','http://yui.yahooapis.com/2.3.1/build','Insert the path to YUI libraries','','free')");
595     print "Upgrade to $DBversion done (adding new system preference for controlling YUI path)\n";
596     SetVersion ($DBversion);
597 }
598 $DBversion = "3.00.00.024";
599 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
600     $dbh->do("ALTER TABLE biblioitems CHANGE  itemtype itemtype VARCHAR(10)");
601     print "Upgrade to $DBversion done (changing itemtype to (10))\n";
602     SetVersion ($DBversion);
603 }
604
605 $DBversion = "3.00.00.025";
606 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
607     $dbh->do("ALTER TABLE items ADD COLUMN itype VARCHAR(10)");
608     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itype VARCHAR(10) AFTER uri");
609     if(C4::Context->preference('item-level_itypes')){
610         $dbh->do('update items,biblioitems set items.itype=biblioitems.itemtype where items.biblionumber=biblioitems.biblionumber and itype is null');
611     }
612     print "Upgrade to $DBversion done (reintroduce items.itype - fill from itemtype)\n ";
613     SetVersion ($DBversion);
614 }
615
616 $DBversion = "3.00.00.026";
617 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
618     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
619        VALUES ('HomeOrHoldingBranch','homebranch','homebranch|holdingbranch','With independent branches turned on this decides whether to check the items holdingbranch or homebranch at circulatilon','choice')");
620     print "Upgrade to $DBversion done (adding new system preference for choosing whether homebranch or holdingbranch is checked in circulation)\n";
621     SetVersion ($DBversion);
622 }
623
624 $DBversion = "3.00.00.027";
625 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
626     $dbh->do("CREATE TABLE `marc_matchers` (
627                 `matcher_id` int(11) NOT NULL auto_increment,
628                 `code` varchar(10) NOT NULL default '',
629                 `description` varchar(255) NOT NULL default '',
630                 `record_type` varchar(10) NOT NULL default 'biblio',
631                 `threshold` int(11) NOT NULL default 0,
632                 PRIMARY KEY (`matcher_id`),
633                 KEY `code` (`code`),
634                 KEY `record_type` (`record_type`)
635               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
636     $dbh->do("CREATE TABLE `matchpoints` (
637                 `matcher_id` int(11) NOT NULL,
638                 `matchpoint_id` int(11) NOT NULL auto_increment,
639                 `search_index` varchar(30) NOT NULL default '',
640                 `score` int(11) NOT NULL default 0,
641                 PRIMARY KEY (`matchpoint_id`),
642                 CONSTRAINT `matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
643                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE
644               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
645     $dbh->do("CREATE TABLE `matchpoint_components` (
646                 `matchpoint_id` int(11) NOT NULL,
647                 `matchpoint_component_id` int(11) NOT NULL auto_increment,
648                 sequence int(11) NOT NULL default 0,
649                 tag varchar(3) NOT NULL default '',
650                 subfields varchar(40) NOT NULL default '',
651                 offset int(4) NOT NULL default 0,
652                 length int(4) NOT NULL default 0,
653                 PRIMARY KEY (`matchpoint_component_id`),
654                 KEY `by_sequence` (`matchpoint_id`, `sequence`),
655                 CONSTRAINT `matchpoint_components_ifbk_1` FOREIGN KEY (`matchpoint_id`)
656                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
657               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
658     $dbh->do("CREATE TABLE `matchpoint_component_norms` (
659                 `matchpoint_component_id` int(11) NOT NULL,
660                 `sequence`  int(11) NOT NULL default 0,
661                 `norm_routine` varchar(50) NOT NULL default '',
662                 KEY `matchpoint_component_norms` (`matchpoint_component_id`, `sequence`),
663                 CONSTRAINT `matchpoint_component_norms_ifbk_1` FOREIGN KEY (`matchpoint_component_id`)
664                            REFERENCES `matchpoint_components` (`matchpoint_component_id`) ON DELETE CASCADE ON UPDATE CASCADE
665               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
666     $dbh->do("CREATE TABLE `matcher_matchpoints` (
667                 `matcher_id` int(11) NOT NULL,
668                 `matchpoint_id` int(11) NOT NULL,
669                 CONSTRAINT `matcher_matchpoints_ifbk_1` FOREIGN KEY (`matcher_id`)
670                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
671                 CONSTRAINT `matcher_matchpoints_ifbk_2` FOREIGN KEY (`matchpoint_id`)
672                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
673               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
674     $dbh->do("CREATE TABLE `matchchecks` (
675                 `matcher_id` int(11) NOT NULL,
676                 `matchcheck_id` int(11) NOT NULL auto_increment,
677                 `source_matchpoint_id` int(11) NOT NULL,
678                 `target_matchpoint_id` int(11) NOT NULL,
679                 PRIMARY KEY (`matchcheck_id`),
680                 CONSTRAINT `matcher_matchchecks_ifbk_1` FOREIGN KEY (`matcher_id`)
681                            REFERENCES `marc_matchers` (`matcher_id`) ON DELETE CASCADE ON UPDATE CASCADE,
682                 CONSTRAINT `matcher_matchchecks_ifbk_2` FOREIGN KEY (`source_matchpoint_id`)
683                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE,
684                 CONSTRAINT `matcher_matchchecks_ifbk_3` FOREIGN KEY (`target_matchpoint_id`)
685                            REFERENCES `matchpoints` (`matchpoint_id`) ON DELETE CASCADE ON UPDATE CASCADE
686               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
687     print "Upgrade to $DBversion done (added C4::Matcher serialization tables)\n ";
688     SetVersion ($DBversion);
689 }
690
691 $DBversion = "3.00.00.028";
692 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
693     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
694        VALUES ('canreservefromotherbranches','1','','With Independent branches on, can a user from one library reserve an item from another library','YesNo')");
695     print "Upgrade to $DBversion done (adding new system preference for changing reserve/holds behaviour with independent branches)\n";
696     SetVersion ($DBversion);
697 }
698
699
700 $DBversion = "3.00.00.029";
701 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
702     $dbh->do("ALTER TABLE `import_batches` ADD `matcher_id` int(11) NULL AFTER `import_batch_id`");
703     print "Upgrade to $DBversion done (adding matcher_id to import_batches)\n";
704     SetVersion ($DBversion);
705 }
706
707 $DBversion = "3.00.00.030";
708 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
709     $dbh->do("
710 CREATE TABLE services_throttle (
711   service_type varchar(10) NOT NULL default '',
712   service_count varchar(45) default NULL,
713   PRIMARY KEY  (service_type)
714 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
715 ");
716     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
717        VALUES ('FRBRizeEditions',0,'','If ON, Koha will query one or more ISBN web services for associated ISBNs and display an Editions tab on the details pages','YesNo')");
718  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
719        VALUES ('XISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the OCLC xISBN web service in the Editions tab on the detail pages. See: http://www.worldcat.org/affiliate/webservices/xisbn/app.jsp','YesNo')");
720  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
721        VALUES ('OCLCAffiliateID','','','Use with FRBRizeEditions and XISBN. You can sign up for an AffiliateID here: http://www.worldcat.org/wcpa/do/AffiliateUserServices?method=initSelfRegister','free')");
722  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
723        VALUES ('XISBNDailyLimit',499,'','The xISBN Web service is free for non-commercial use when usage does not exceed 500 requests per day','free')");
724  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
725        VALUES ('PINESISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use PINES OISBN web service in the Editions tab on the detail pages.','YesNo')");
726  $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
727        VALUES ('ThingISBN',0,'','Use with FRBRizeEditions. If ON, Koha will use the ThingISBN web service in the Editions tab on the detail pages.','YesNo')");
728     print "Upgrade to $DBversion done (adding services throttle table and sysprefs for xISBN)\n";
729     SetVersion ($DBversion);
730 }
731
732 $DBversion = "3.00.00.031";
733 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
734
735 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryStemming',1,'If ON, enables query stemming',NULL,'YesNo')");
736 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryFuzzy',1,'If ON, enables fuzzy option for searches',NULL,'YesNo')");
737 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QueryWeightFields',1,'If ON, enables field weighting',NULL,'YesNo')");
738 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WebBasedSelfCheck',0,'If ON, enables the web-based self-check system',NULL,'YesNo')");
739 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('numSearchResults',20,'Specify the maximum number of results to display on a page of results',NULL,'free')");
740 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACnumSearchResults',20,'Specify the maximum number of results to display on a page of results',NULL,'free')");
741 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('maxItemsInSearchResults',20,'Specify the maximum number of items to display for each result on a page of results',NULL,'free')");
742 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortField',NULL,'Specify the default field used for sorting','relevance|popularity|call_number|pubdate|acqdate|title|author','Choice')");
743 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('defaultSortOrder',NULL,'Specify the default sort order','asc|dsc|az|za','Choice')");
744 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortField',NULL,'Specify the default field used for sorting','relevance|popularity|call_number|pubdate|acqdate|title|author','Choice')");
745 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACdefaultSortOrder',NULL,'Specify the default sort order','asc|dsc|za|az','Choice')");
746 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('staffClientBaseURL','','Specify the base URL of the staff client',NULL,'free')");
747 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('minPasswordLength',3,'Specify the minimum length of a patron/staff password',NULL,'free')");
748 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('noItemTypeImages',0,'If ON, disables item-type images',NULL,'YesNo')");
749 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('emailLibrarianWhenHoldIsPlaced',0,'If ON, emails the librarian whenever a hold is placed',NULL,'YesNo')");
750 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('holdCancelLength','','Specify how many days before a hold is canceled',NULL,'free')");
751 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('libraryAddress','','The address to use for printing receipts, overdues, etc. if different than physical address',NULL,'free')");
752 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesMode','test','Choose the fines mode, test or production','test|production','Choice')");
753 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('globalDueDate','','If set, allows a global static due date for all checkouts',NULL,'free')");
754 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeInputFilter','','If set, allows specification of a item barcode input filter','cuecat','Choice')");
755 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('singleBranchMode',0,'Operate in Single-branch mode, hide branch selection in the OPAC',NULL,'YesNo')");
756 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('URLLinkText','','Text to display as the link anchor in the OPAC',NULL,'free')");
757 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACSubscriptionDisplay','economical','Specify how to display subscription information in the OPAC','economical|off|full','Choice')");
758 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACDisplayExtendedSubInfo',1,'If ON, extended subscription information is displayed in the OPAC',NULL,'YesNo')");
759 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACViewOthersSuggestions',0,'If ON, allows all suggestions to be displayed in the OPAC',NULL,'YesNo')");
760 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACURLOpenInNewWindow',0,'If ON, URLs in the OPAC open in a new window',NULL,'YesNo')");
761 $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACUserCSS',0,'Add CSS to be included in the OPAC',NULL,'free')");
762
763     print "Upgrade to $DBversion done (adding additional system preference)\n";
764     SetVersion ($DBversion);
765 }
766
767 $DBversion = "3.00.00.032";
768 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
769     $dbh->do("UPDATE `marc_subfield_structure` SET `kohafield` = 'items.wthdrawn' WHERE `kohafield` = 'items.withdrawn'");
770     print "Upgrade to $DBversion done (fixed MARC framework references to items.withdrawn)\n";
771     SetVersion ($DBversion);
772 }
773
774 $DBversion = "3.00.00.033";
775 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
776     $dbh->do("INSERT INTO `userflags` VALUES(17,'staffaccess','Modify login / permissions for staff users',0)");
777     print "Upgrade to $DBversion done (Adding permissions flag for staff member access modification.  )\n";
778     SetVersion ($DBversion);
779 }
780
781 $DBversion = "3.00.00.034";
782 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
783     $dbh->do("ALTER TABLE `virtualshelves` ADD COLUMN `sortfield` VARCHAR(16) ");
784     print "Upgrade to $DBversion done (Adding sortfield for Virtual Shelves.  )\n";
785     SetVersion ($DBversion);
786 }
787
788 $DBversion = "3.00.00.035";
789 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
790     $dbh->do("UPDATE marc_subfield_structure
791               SET authorised_value = 'cn_source'
792               WHERE kohafield IN ('items.cn_source', 'biblioitems.cn_source')
793               AND (authorised_value is NULL OR authorised_value = '')");
794     print "Upgrade to $DBversion done (MARC frameworks: make classification source a drop-down)\n";
795     SetVersion ($DBversion);
796 }
797
798 $DBversion = "3.00.00.036";
799 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
800     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACItemsResultsDisplay','statuses','statuses : show only the status of items in result list. itemdisplay : show full location of items (branch+location+callnumber) as in staff interface','statuses|itemdetails','Choice');");
801     print "Upgrade to $DBversion done (OPACItemsResultsDisplay systempreference added)\n";
802     SetVersion ($DBversion);
803 }
804
805 $DBversion = "3.00.00.037";
806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
807     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactfirstname` varchar(255)");
808     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactsurname` varchar(255)");
809     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress1` varchar(255)");
810     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress2` varchar(255)");
811     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactaddress3` varchar(255)");
812     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactzipcode` varchar(50)");
813     $dbh->do("ALTER TABLE `borrowers` ADD COLUMN `altcontactphone` varchar(50)");
814     print "Upgrade to $DBversion done (Adding Alternative Contact Person information to borrowers table)\n";
815     SetVersion ($DBversion);
816 }
817
818 $DBversion = "3.00.00.038";
819 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
820     $dbh->do("UPDATE `systempreferences` set explanation='Choose the fines mode, off, test (emails admin report) or production (accrue overdue fines).  Requires fines cron script' , options='off|test|production' where variable='finesMode'");
821     $dbh->do("DELETE FROM `systempreferences` WHERE variable='hideBiblioNumber'");
822     print "Upgrade to $DBversion done ('alter finesMode systempreference, remove superfluous syspref.')\n";
823     SetVersion ($DBversion);
824 }
825
826 $DBversion = "3.00.00.039";
827 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
828     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('uppercasesurnames',0,'If ON, surnames are converted to upper case in patron entry form',NULL,'YesNo')");
829     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('CircControl','ItemHomeLibrary','Specify the agency that controls the circulation and fines policy','PickupLibrary|PatronLibrary|ItemHomeLibrary','Choice')");
830     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('finesCalendar','noFinesWhenClosed','Specify whether to use the Calendar in calculating duedates and fines','ignoreCalendar|noFinesWhenClosed','Choice')");
831     # $dbh->do("DELETE FROM `systempreferences` WHERE variable='HomeOrHoldingBranch'"); # Bug #2752
832     print "Upgrade to $DBversion done ('add circ sysprefs CircControl, finesCalendar, and uppercasesurnames, and delete HomeOrHoldingBranch.')\n";
833     SetVersion ($DBversion);
834 }
835
836 $DBversion = "3.00.00.040";
837 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
838         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('previousIssuesDefaultSortOrder','asc','Specify the sort order of Previous Issues on the circulation page','asc|desc','Choice')");
839         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('todaysIssuesDefaultSortOrder','desc','Specify the sort order of Todays Issues on the circulation page','asc|desc','Choice')");
840         print "Upgrade to $DBversion done ('add circ sysprefs todaysIssuesDefaultSortOrder and previousIssuesDefaultSortOrder.')\n";
841     SetVersion ($DBversion);
842 }
843
844
845 $DBversion = "3.00.00.041";
846 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
847     # Strictly speaking it is not necessary to explicitly change
848     # NULL values to 0, because the ALTER TABLE statement will do that.
849     # However, setting them first avoids a warning.
850     $dbh->do("UPDATE items SET notforloan = 0 WHERE notforloan IS NULL");
851     $dbh->do("UPDATE items SET damaged = 0 WHERE damaged IS NULL");
852     $dbh->do("UPDATE items SET itemlost = 0 WHERE itemlost IS NULL");
853     $dbh->do("UPDATE items SET wthdrawn = 0 WHERE wthdrawn IS NULL");
854     $dbh->do("ALTER TABLE items
855                 MODIFY notforloan tinyint(1) NOT NULL default 0,
856                 MODIFY damaged    tinyint(1) NOT NULL default 0,
857                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
858                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
859     $dbh->do("UPDATE deleteditems SET notforloan = 0 WHERE notforloan IS NULL");
860     $dbh->do("UPDATE deleteditems SET damaged = 0 WHERE damaged IS NULL");
861     $dbh->do("UPDATE deleteditems SET itemlost = 0 WHERE itemlost IS NULL");
862     $dbh->do("UPDATE deleteditems SET wthdrawn = 0 WHERE wthdrawn IS NULL");
863     $dbh->do("ALTER TABLE deleteditems
864                 MODIFY notforloan tinyint(1) NOT NULL default 0,
865                 MODIFY damaged    tinyint(1) NOT NULL default 0,
866                 MODIFY itemlost   tinyint(1) NOT NULL default 0,
867                 MODIFY wthdrawn   tinyint(1) NOT NULL default 0");
868         print "Upgrade to $DBversion done (disallow NULL in several item status columns)\n";
869     SetVersion ($DBversion);
870 }
871
872 $DBversion = "3.00.00.04";
873 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
874     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
875         print "Upgrade to $DBversion done (disallow NULL in aqbooksellers.name; part of fix for bug 1251)\n";
876     SetVersion ($DBversion);
877 }
878
879 $DBversion = "3.00.00.043";
880 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
881     $dbh->do("ALTER TABLE `currency` ADD `symbol` varchar(5) default NULL AFTER currency, ADD `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP AFTER symbol");
882         print "Upgrade to $DBversion done (currency table: add symbol and timestamp columns)\n";
883     SetVersion ($DBversion);
884 }
885
886 $DBversion = "3.00.00.044";
887 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
888     $dbh->do("ALTER TABLE deletedborrowers
889   ADD `altcontactfirstname` varchar(255) default NULL,
890   ADD `altcontactsurname` varchar(255) default NULL,
891   ADD `altcontactaddress1` varchar(255) default NULL,
892   ADD `altcontactaddress2` varchar(255) default NULL,
893   ADD `altcontactaddress3` varchar(255) default NULL,
894   ADD `altcontactzipcode` varchar(50) default NULL,
895   ADD `altcontactphone` varchar(50) default NULL
896   ");
897   $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES
898 ('OPACBaseURL',NULL,'Specify the Base URL of the OPAC, e.g., opac.mylibrary.com, the http:// will be added automatically by Koha.',NULL,'Free'),
899 ('language','en','Set the default language in the staff client.',NULL,'Languages'),
900 ('QueryAutoTruncate',1,'If ON, query truncation is enabled by default',NULL,'YesNo'),
901 ('QueryRemoveStopwords',0,'If ON, stopwords listed in the Administration area will be removed from queries',NULL,'YesNo')
902   ");
903         print "Upgrade to $DBversion done (syncing deletedborrowers table with borrowers table)\n";
904     SetVersion ($DBversion);
905 }
906
907 #-- http://www.w3.org/International/articles/language-tags/
908
909 #-- RFC4646
910 $DBversion = "3.00.00.045";
911 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
912     $dbh->do("
913 CREATE TABLE language_subtag_registry (
914         subtag varchar(25),
915         type varchar(25), -- language-script-region-variant-extension-privateuse
916         description varchar(25), -- only one of the possible descriptions for ease of reference, see language_descriptions for the complete list
917         added date,
918         KEY `subtag` (`subtag`)
919 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
920
921 #-- TODO: add suppress_scripts
922 #-- this maps three letter codes defined in iso639.2 back to their
923 #-- two letter equivilents in rfc4646 (LOC maintains iso639+)
924  $dbh->do("CREATE TABLE language_rfc4646_to_iso639 (
925         rfc4646_subtag varchar(25),
926         iso639_2_code varchar(25),
927         KEY `rfc4646_subtag` (`rfc4646_subtag`)
928 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
929
930  $dbh->do("CREATE TABLE language_descriptions (
931         subtag varchar(25),
932         type varchar(25),
933         lang varchar(25),
934         description varchar(255),
935         KEY `lang` (`lang`)
936 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
937
938 #-- bi-directional support, keyed by script subcode
939  $dbh->do("CREATE TABLE language_script_bidi (
940         rfc4646_subtag varchar(25), -- script subtag, Arab, Hebr, etc.
941         bidi varchar(3), -- rtl ltr
942         KEY `rfc4646_subtag` (`rfc4646_subtag`)
943 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
944
945 #-- BIDI Stuff, Arabic and Hebrew
946  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
947 VALUES( 'Arab', 'rtl')");
948  $dbh->do("INSERT INTO language_script_bidi(rfc4646_subtag,bidi)
949 VALUES( 'Hebr', 'rtl')");
950
951 #-- TODO: need to map language subtags to script subtags for detection
952 #-- of bidi when script is not specified (like ar, he)
953  $dbh->do("CREATE TABLE language_script_mapping (
954         language_subtag varchar(25),
955         script_subtag varchar(25),
956         KEY `language_subtag` (`language_subtag`)
957 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
958
959 #-- Default mappings between script and language subcodes
960  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
961 VALUES( 'ar', 'Arab')");
962  $dbh->do("INSERT INTO language_script_mapping(language_subtag,script_subtag)
963 VALUES( 'he', 'Hebr')");
964
965         print "Upgrade to $DBversion done (adding language subtag registry and basic BiDi support NOTE: You should import the subtag registry SQL)\n";
966     SetVersion ($DBversion);
967 }
968
969 $DBversion = "3.00.00.046";
970 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
971     $dbh->do("ALTER TABLE `subscription` CHANGE `numberlength` `numberlength` int(11) default '0' ,
972                  CHANGE `weeklength` `weeklength` int(11) default '0'");
973     $dbh->do("CREATE TABLE `serialitems` (`serialid` int(11) NOT NULL, `itemnumber` int(11) NOT NULL, UNIQUE KEY `serialididx` (`serialid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
974     $dbh->do("INSERT INTO `serialitems` SELECT `serialid`,`itemnumber` from serial where NOT ISNULL(itemnumber) && itemnumber <> '' && itemnumber NOT LIKE '%,%'");
975         print "Upgrade to $DBversion done (Add serialitems table to link serial issues to items. )\n";
976     SetVersion ($DBversion);
977 }
978
979 $DBversion = "3.00.00.047";
980 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
981     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacRenewalAllowed',0,'If ON, users can renew their issues directly from their OPAC account',NULL,'YesNo');");
982         print "Upgrade to $DBversion done ( Added OpacRenewalAllowed syspref )\n";
983     SetVersion ($DBversion);
984 }
985
986 $DBversion = "3.00.00.048";
987 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
988     $dbh->do("ALTER TABLE `items` ADD `more_subfields_xml` longtext default NULL AFTER `itype`");
989         print "Upgrade to $DBversion done (added items.more_subfields_xml)\n";
990     SetVersion ($DBversion);
991 }
992
993 $DBversion = "3.00.00.049";
994 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
995         $dbh->do("ALTER TABLE `z3950servers` ADD `encoding` text default NULL AFTER type ");
996         print "Upgrade to $DBversion done ( Added encoding field to z3950servers table )\n";
997     SetVersion ($DBversion);
998 }
999
1000 $DBversion = "3.00.00.050";
1001 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1002     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHighlightedWords','0','If Set, query matched terms are highlighted in OPAC',NULL,'YesNo');");
1003         print "Upgrade to $DBversion done ( Added OpacHighlightedWords syspref )\n";
1004     SetVersion ($DBversion);
1005 }
1006
1007 $DBversion = "3.00.00.051";
1008 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1009     $dbh->do("UPDATE systempreferences SET explanation = 'Define the current theme for the OPAC interface.' WHERE variable = 'opacthemes';");
1010         print "Upgrade to $DBversion done ( Corrected opacthemes explanation. )\n";
1011     SetVersion ($DBversion);
1012 }
1013
1014 $DBversion = "3.00.00.052";
1015 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1016     $dbh->do("ALTER TABLE `deleteditems` ADD `more_subfields_xml` LONGTEXT DEFAULT NULL AFTER `itype`");
1017         print "Upgrade to $DBversion done ( Adding missing column to deleteditems table. )\n";
1018     SetVersion ($DBversion);
1019 }
1020
1021 $DBversion = "3.00.00.053";
1022 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1023     $dbh->do("CREATE TABLE `printers_profile` (
1024             `prof_id` int(4) NOT NULL auto_increment,
1025             `printername` varchar(40) NOT NULL,
1026             `tmpl_id` int(4) NOT NULL,
1027             `paper_bin` varchar(20) NOT NULL,
1028             `offset_horz` float default NULL,
1029             `offset_vert` float default NULL,
1030             `creep_horz` float default NULL,
1031             `creep_vert` float default NULL,
1032             `unit` char(20) NOT NULL default 'POINT',
1033             PRIMARY KEY  (`prof_id`),
1034             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1035             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1036             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1037     $dbh->do("CREATE TABLE `labels_profile` (
1038             `tmpl_id` int(4) NOT NULL,
1039             `prof_id` int(4) NOT NULL,
1040             UNIQUE KEY `tmpl_id` (`tmpl_id`),
1041             UNIQUE KEY `prof_id` (`prof_id`)
1042             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1043     print "Upgrade to $DBversion done ( Printer Profile tables added )\n";
1044     SetVersion ($DBversion);
1045 }
1046
1047 $DBversion = "3.00.00.054";
1048 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1049     $dbh->do("UPDATE systempreferences SET options = 'incremental|annual|hbyymmincr|OFF', explanation = 'Used to autogenerate a barcode: incremental will be of the form 1, 2, 3; annual of the form 2007-0001, 2007-0002; hbyymmincr of the form HB08010001 where HB = Home Branch' WHERE variable = 'autoBarcode';");
1050         print "Upgrade to $DBversion done ( Added another barcode autogeneration sequence to barcode.pl. )\n";
1051     SetVersion ($DBversion);
1052 }
1053
1054 $DBversion = "3.00.00.055";
1055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1056     $dbh->do("ALTER TABLE `zebraqueue` ADD KEY `zebraqueue_lookup` (`server`, `biblio_auth_number`, `operation`, `done`)");
1057         print "Upgrade to $DBversion done ( Added index on zebraqueue. )\n";
1058     SetVersion ($DBversion);
1059 }
1060 $DBversion = "3.00.00.056";
1061 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1062     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
1063         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('995', 'v', 'Note sur le N° de périodique','Note sur le N° de périodique', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1064     } else {
1065         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('952', 'h', 'Serial Enumeration / chronology','Serial Enumeration / chronology', 0, 0, 'items.enumchron', 10, '', '', '', 0, 0, '', '', '', NULL) ");
1066     }
1067     $dbh->do("ALTER TABLE `items` ADD `enumchron` VARCHAR(80) DEFAULT NULL;");
1068     print "Upgrade to $DBversion done ( Added item.enumchron column, and framework map to 952h )\n";
1069     SetVersion ($DBversion);
1070 }
1071
1072 $DBversion = "3.00.00.057";
1073 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1074     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH','0','if ON, OAI-PMH server is enabled',NULL,'YesNo');");
1075     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:archiveID','KOHA-OAI-TEST','OAI-PMH archive identification',NULL,'Free');");
1076     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:MaxCount','50','OAI-PMH maximum number of records by answer to ListRecords and ListIdentifiers queries',NULL,'Integer');");
1077     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:Set','SET,Experimental set\r\nSET:SUBSET,Experimental subset','OAI-PMH exported set, the set name is followed by a comma and a short description, one set by line',NULL,'Free');");
1078     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OAI-PMH:Subset',\"itemtype='BOOK'\",'Restrict answer to matching raws of the biblioitems table (experimental)',NULL,'Free');");
1079     SetVersion ($DBversion);
1080 }
1081
1082 $DBversion = "3.00.00.058";
1083 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1084     $dbh->do("ALTER TABLE `opac_news`
1085                 CHANGE `lang` `lang` VARCHAR( 25 )
1086                 CHARACTER SET utf8
1087                 COLLATE utf8_general_ci
1088                 NOT NULL default ''");
1089         print "Upgrade to $DBversion done ( lang field in opac_news made longer )\n";
1090     SetVersion ($DBversion);
1091 }
1092
1093 $DBversion = "3.00.00.059";
1094 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1095
1096     $dbh->do("CREATE TABLE IF NOT EXISTS `labels_templates` (
1097             `tmpl_id` int(4) NOT NULL auto_increment,
1098             `tmpl_code` char(100)  default '',
1099             `tmpl_desc` char(100) default '',
1100             `page_width` float default '0',
1101             `page_height` float default '0',
1102             `label_width` float default '0',
1103             `label_height` float default '0',
1104             `topmargin` float default '0',
1105             `leftmargin` float default '0',
1106             `cols` int(2) default '0',
1107             `rows` int(2) default '0',
1108             `colgap` float default '0',
1109             `rowgap` float default '0',
1110             `active` int(1) default NULL,
1111             `units` char(20)  default 'PX',
1112             `fontsize` int(4) NOT NULL default '3',
1113             PRIMARY KEY  (`tmpl_id`)
1114             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1115     $dbh->do("CREATE TABLE  IF NOT EXISTS `printers_profile` (
1116             `prof_id` int(4) NOT NULL auto_increment,
1117             `printername` varchar(40) NOT NULL,
1118             `tmpl_id` int(4) NOT NULL,
1119             `paper_bin` varchar(20) NOT NULL,
1120             `offset_horz` float default NULL,
1121             `offset_vert` float default NULL,
1122             `creep_horz` float default NULL,
1123             `creep_vert` float default NULL,
1124             `unit` char(20) NOT NULL default 'POINT',
1125             PRIMARY KEY  (`prof_id`),
1126             UNIQUE KEY `printername` (`printername`,`tmpl_id`,`paper_bin`),
1127             CONSTRAINT `printers_profile_pnfk_1` FOREIGN KEY (`tmpl_id`) REFERENCES `labels_templates` (`tmpl_id`) ON DELETE CASCADE ON UPDATE CASCADE
1128             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
1129     print "Upgrade to $DBversion done ( Added labels_templates table if it did not exist. )\n";
1130     SetVersion ($DBversion);
1131 }
1132
1133 $DBversion = "3.00.00.060";
1134 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1135     $dbh->do("CREATE TABLE IF NOT EXISTS `patronimage` (
1136             `cardnumber` varchar(16) NOT NULL,
1137             `mimetype` varchar(15) NOT NULL,
1138             `imagefile` mediumblob NOT NULL,
1139             PRIMARY KEY  (`cardnumber`),
1140             CONSTRAINT `patronimage_fk1` FOREIGN KEY (`cardnumber`) REFERENCES `borrowers` (`cardnumber`) ON DELETE CASCADE ON UPDATE CASCADE
1141             ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1142         print "Upgrade to $DBversion done ( Added patronimage table. )\n";
1143     SetVersion ($DBversion);
1144 }
1145
1146 $DBversion = "3.00.00.061";
1147 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1148     $dbh->do("ALTER TABLE labels_templates ADD COLUMN font char(10) NOT NULL DEFAULT 'TR';");
1149         print "Upgrade to $DBversion done ( Added font column to labels_templates )\n";
1150     SetVersion ($DBversion);
1151 }
1152
1153 $DBversion = "3.00.00.062";
1154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1155     $dbh->do("CREATE TABLE `old_issues` (
1156                 `borrowernumber` int(11) default NULL,
1157                 `itemnumber` int(11) default NULL,
1158                 `date_due` date default NULL,
1159                 `branchcode` varchar(10) default NULL,
1160                 `issuingbranch` varchar(18) default NULL,
1161                 `returndate` date default NULL,
1162                 `lastreneweddate` date default NULL,
1163                 `return` varchar(4) default NULL,
1164                 `renewals` tinyint(4) default NULL,
1165                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1166                 `issuedate` date default NULL,
1167                 KEY `old_issuesborridx` (`borrowernumber`),
1168                 KEY `old_issuesitemidx` (`itemnumber`),
1169                 KEY `old_bordate` (`borrowernumber`,`timestamp`),
1170                 CONSTRAINT `old_issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1171                     ON DELETE SET NULL ON UPDATE SET NULL,
1172                 CONSTRAINT `old_issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1173                     ON DELETE SET NULL ON UPDATE SET NULL
1174                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1175     $dbh->do("CREATE TABLE `old_reserves` (
1176                 `borrowernumber` int(11) default NULL,
1177                 `reservedate` date default NULL,
1178                 `biblionumber` int(11) default NULL,
1179                 `constrainttype` varchar(1) default NULL,
1180                 `branchcode` varchar(10) default NULL,
1181                 `notificationdate` date default NULL,
1182                 `reminderdate` date default NULL,
1183                 `cancellationdate` date default NULL,
1184                 `reservenotes` mediumtext,
1185                 `priority` smallint(6) default NULL,
1186                 `found` varchar(1) default NULL,
1187                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1188                 `itemnumber` int(11) default NULL,
1189                 `waitingdate` date default NULL,
1190                 KEY `old_reserves_borrowernumber` (`borrowernumber`),
1191                 KEY `old_reserves_biblionumber` (`biblionumber`),
1192                 KEY `old_reserves_itemnumber` (`itemnumber`),
1193                 KEY `old_reserves_branchcode` (`branchcode`),
1194                 CONSTRAINT `old_reserves_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1195                     ON DELETE SET NULL ON UPDATE SET NULL,
1196                 CONSTRAINT `old_reserves_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`)
1197                     ON DELETE SET NULL ON UPDATE SET NULL,
1198                 CONSTRAINT `old_reserves_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`)
1199                     ON DELETE SET NULL ON UPDATE SET NULL
1200                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1201
1202     # move closed transactions to old_* tables
1203     $dbh->do("INSERT INTO old_issues SELECT * FROM issues WHERE returndate IS NOT NULL");
1204     $dbh->do("DELETE FROM issues WHERE returndate IS NOT NULL");
1205     $dbh->do("INSERT INTO old_reserves SELECT * FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1206     $dbh->do("DELETE FROM reserves WHERE cancellationdate IS NOT NULL OR found = 'F'");
1207
1208         print "Upgrade to $DBversion done ( Added old_issues and old_reserves tables )\n";
1209     SetVersion ($DBversion);
1210 }
1211
1212 $DBversion = "3.00.00.063";
1213 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1214     $dbh->do("ALTER TABLE deleteditems
1215                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT DEFAULT NULL,
1216                 ADD COLUMN enumchron VARCHAR(80) DEFAULT NULL AFTER more_subfields_xml,
1217                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1218     $dbh->do("ALTER TABLE items
1219                 CHANGE COLUMN booksellerid booksellerid MEDIUMTEXT,
1220                 ADD COLUMN copynumber SMALLINT(6) DEFAULT NULL AFTER enumchron;");
1221         print "Upgrade to $DBversion done ( Changed items.booksellerid and deleteditems.booksellerid to MEDIUMTEXT and added missing items.copynumber and deleteditems.copynumber to fix Bug 1927)\n";
1222     SetVersion ($DBversion);
1223 }
1224
1225 $DBversion = "3.00.00.064";
1226 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1227     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AmazonLocale','US','Use to set the Locale of your Amazon.com Web Services','US|CA|DE|FR|JP|UK','Choice');");
1228     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSAccessKeyID','','See:  http://aws.amazon.com','','free');");
1229     $dbh->do("DELETE FROM `systempreferences` WHERE variable='AmazonDevKey';");
1230     $dbh->do("DELETE FROM `systempreferences` WHERE variable='XISBNAmazonSimilarItems';");
1231     $dbh->do("DELETE FROM `systempreferences` WHERE variable='OPACXISBNAmazonSimilarItems';");
1232     print "Upgrade to $DBversion done (IMPORTANT: Upgrading to Amazon.com Associates Web Service 4.0 ) \n";
1233     SetVersion ($DBversion);
1234 }
1235
1236 $DBversion = "3.00.00.065";
1237 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1238     $dbh->do("CREATE TABLE `patroncards` (
1239                 `cardid` int(11) NOT NULL auto_increment,
1240                 `batch_id` varchar(10) NOT NULL default '1',
1241                 `borrowernumber` int(11) NOT NULL,
1242                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1243                 PRIMARY KEY  (`cardid`),
1244                 KEY `patroncards_ibfk_1` (`borrowernumber`),
1245                 CONSTRAINT `patroncards_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1246                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
1247     print "Upgrade to $DBversion done (Adding patroncards table for patroncards generation feature. ) \n";
1248     SetVersion ($DBversion);
1249 }
1250
1251 $DBversion = "3.00.00.066";
1252 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1253     $dbh->do("ALTER TABLE `virtualshelfcontents` MODIFY `dateadded` timestamp NOT NULL
1254 DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP;
1255 ");
1256     print "Upgrade to $DBversion done (fix for bug 1873: virtualshelfcontents dateadded column empty. ) \n";
1257     SetVersion ($DBversion);
1258 }
1259
1260 $DBversion = "3.00.00.067";
1261 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1262     $dbh->do("UPDATE systempreferences SET explanation = 'Enable patron images for the Staff Client', type = 'YesNo' WHERE variable = 'patronimages'");
1263     print "Upgrade to $DBversion done (Updating patronimages syspref to reflect current kohastructure.sql. ) \n";
1264     SetVersion ($DBversion);
1265 }
1266
1267 $DBversion = "3.00.00.068";
1268 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1269     $dbh->do("CREATE TABLE `permissions` (
1270                 `module_bit` int(11) NOT NULL DEFAULT 0,
1271                 `code` varchar(30) DEFAULT NULL,
1272                 `description` varchar(255) DEFAULT NULL,
1273                 PRIMARY KEY  (`module_bit`, `code`),
1274                 CONSTRAINT `permissions_ibfk_1` FOREIGN KEY (`module_bit`) REFERENCES `userflags` (`bit`)
1275                     ON DELETE CASCADE ON UPDATE CASCADE
1276               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1277     $dbh->do("CREATE TABLE `user_permissions` (
1278                 `borrowernumber` int(11) NOT NULL DEFAULT 0,
1279                 `module_bit` int(11) NOT NULL DEFAULT 0,
1280                 `code` varchar(30) DEFAULT NULL,
1281                 CONSTRAINT `user_permissions_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1282                     ON DELETE CASCADE ON UPDATE CASCADE,
1283                 CONSTRAINT `user_permissions_ibfk_2` FOREIGN KEY (`module_bit`, `code`)
1284                     REFERENCES `permissions` (`module_bit`, `code`)
1285                     ON DELETE CASCADE ON UPDATE CASCADE
1286               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1287
1288     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
1289     (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
1290     (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
1291     (13, 'edit_calendar', 'Define days when the library is closed'),
1292     (13, 'moderate_comments', 'Moderate patron comments'),
1293     (13, 'edit_notices', 'Define notices'),
1294     (13, 'edit_notice_status_triggers', 'Set notice/status triggers for overdue items'),
1295     (13, 'view_system_logs', 'Browse the system logs'),
1296     (13, 'inventory', 'Perform inventory (stocktaking) of your catalogue'),
1297     (13, 'stage_marc_import', 'Stage MARC records into the reservoir'),
1298     (13, 'manage_staged_marc', 'Managed staged MARC records, including completing and reversing imports'),
1299     (13, 'export_catalog', 'Export bibliographic and holdings data'),
1300     (13, 'import_patrons', 'Import patron data'),
1301     (13, 'delete_anonymize_patrons', 'Delete old borrowers and anonymize circulation history (deletes borrower reading history)'),
1302     (13, 'batch_upload_patron_images', 'Upload patron images in batch or one at a time'),
1303     (13, 'schedule_tasks', 'Schedule tasks to run')");
1304
1305     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('GranularPermissions','0','Use detailed staff user permissions',NULL,'YesNo')");
1306
1307     print "Upgrade to $DBversion done (adding permissions and user_permissions tables and GranularPermissions syspref) \n";
1308     SetVersion ($DBversion);
1309 }
1310 $DBversion = "3.00.00.069";
1311 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1312     $dbh->do("ALTER TABLE labels_conf CHANGE COLUMN class classification int(1) DEFAULT NULL;");
1313         print "Upgrade to $DBversion done ( Correcting columname in labels_conf )\n";
1314     SetVersion ($DBversion);
1315 }
1316
1317 $DBversion = "3.00.00.070";
1318 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1319     $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='yuipath'");
1320     $sth->execute;
1321     my ($value) = $sth->fetchrow;
1322     $value =~ s/2.3.1/2.5.1/;
1323     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='yuipath';");
1324         print "Update yuipath syspref to 2.5.1 if necessary\n";
1325     SetVersion ($DBversion);
1326 }
1327
1328 $DBversion = "3.00.00.071";
1329 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1330     $dbh->do(" ALTER TABLE `subscription` ADD `serialsadditems` TINYINT( 1 ) NOT NULL DEFAULT '0';");
1331     # fill the new field with the previous systempreference value, then drop the syspref
1332     my $sth = $dbh->prepare("SELECT value FROM systempreferences WHERE variable='serialsadditems'");
1333     $sth->execute;
1334     my ($serialsadditems) = $sth->fetchrow();
1335     $dbh->do("UPDATE subscription SET serialsadditems=$serialsadditems");
1336     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1337     print "Upgrade to $DBversion done ( moving serialsadditems from syspref to subscription )\n";
1338     SetVersion ($DBversion);
1339 }
1340
1341 $DBversion = "3.00.00.072";
1342 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1343     $dbh->do("ALTER TABLE labels_conf ADD COLUMN formatstring mediumtext DEFAULT NULL AFTER printingtype");
1344         print "Upgrade to $DBversion done ( Adding format string to labels generator. )\n";
1345     SetVersion ($DBversion);
1346 }
1347
1348 $DBversion = "3.00.00.073";
1349 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1350         $dbh->do("DROP TABLE IF EXISTS `tags_all`;");
1351         $dbh->do(q#
1352         CREATE TABLE `tags_all` (
1353           `tag_id`         int(11) NOT NULL auto_increment,
1354           `borrowernumber` int(11) NOT NULL,
1355           `biblionumber`   int(11) NOT NULL,
1356           `term`      varchar(255) NOT NULL,
1357           `language`       int(4) default NULL,
1358           `date_created` datetime  NOT NULL,
1359           PRIMARY KEY  (`tag_id`),
1360           KEY `tags_borrowers_fk_1` (`borrowernumber`),
1361           KEY `tags_biblionumber_fk_1` (`biblionumber`),
1362           CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`)
1363                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1364           CONSTRAINT `tags_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1365                 REFERENCES `biblio`     (`biblionumber`)  ON DELETE CASCADE ON UPDATE CASCADE
1366         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1367         #);
1368         $dbh->do("DROP TABLE IF EXISTS `tags_approval`;");
1369         $dbh->do(q#
1370         CREATE TABLE `tags_approval` (
1371           `term`   varchar(255) NOT NULL,
1372           `approved`     int(1) NOT NULL default '0',
1373           `date_approved` datetime       default NULL,
1374           `approved_by` int(11)          default NULL,
1375           `weight_total` int(9) NOT NULL default '1',
1376           PRIMARY KEY  (`term`),
1377           KEY `tags_approval_borrowers_fk_1` (`approved_by`),
1378           CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`)
1379                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE
1380         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1381         #);
1382         $dbh->do("DROP TABLE IF EXISTS `tags_index`;");
1383         $dbh->do(q#
1384         CREATE TABLE `tags_index` (
1385           `term`    varchar(255) NOT NULL,
1386           `biblionumber` int(11) NOT NULL,
1387           `weight`        int(9) NOT NULL default '1',
1388           PRIMARY KEY  (`term`,`biblionumber`),
1389           KEY `tags_index_biblionumber_fk_1` (`biblionumber`),
1390           CONSTRAINT `tags_index_term_fk_1` FOREIGN KEY (`term`)
1391                 REFERENCES `tags_approval` (`term`)  ON DELETE CASCADE ON UPDATE CASCADE,
1392           CONSTRAINT `tags_index_biblionumber_fk_1` FOREIGN KEY (`biblionumber`)
1393                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
1394         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1395         #);
1396         $dbh->do(q#
1397         INSERT INTO `systempreferences` VALUES
1398                 ('BakerTaylorBookstoreURL','','','URL template for \"My Libary Bookstore\" links, to which the \"key\" value is appended, and \"https://\" is prepended.  It should include your hostname and \"Parent Number\".  Make this variable empty to turn MLB links off.  Example: ocls.mylibrarybookstore.com/MLB/actions/searchHandler.do?nextPage=bookDetails&parentNum=10923&key=',''),
1399                 ('BakerTaylorEnabled','0','','Enable or disable all Baker & Taylor features.','YesNo'),
1400                 ('BakerTaylorPassword','','','Baker & Taylor Password for Content Cafe (external content)','Textarea'),
1401                 ('BakerTaylorUsername','','','Baker & Taylor Username for Content Cafe (external content)','Textarea'),
1402                 ('TagsEnabled','1','','Enables or disables all tagging features.  This is the main switch for tags.','YesNo'),
1403                 ('TagsExternalDictionary',NULL,'','Path on server to local ispell executable, used to set $Lingua::Ispell::path  This dictionary is used as a \"whitelist\" of pre-allowed tags.',''),
1404                 ('TagsInputOnDetail','1','','Allow users to input tags from the detail page.',         'YesNo'),
1405                 ('TagsInputOnList',  '0','','Allow users to input tags from the search results list.', 'YesNo'),
1406                 ('TagsModeration',  NULL,'','Require tags from patrons to be approved before becoming visible.','YesNo'),
1407                 ('TagsShowOnDetail','10','','Number of tags to display on detail page.  0 is off.',        'Integer'),
1408                 ('TagsShowOnList',   '6','','Number of tags to display on search results list.  0 is off.','Integer')
1409         #);
1410         print "Upgrade to $DBversion done (Baker/Taylor,Tags: sysprefs and tables (tags_all, tags_index, tags_approval)) \n";
1411         SetVersion ($DBversion);
1412 }
1413
1414 $DBversion = "3.00.00.074";
1415 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1416     $dbh->do( q(update itemtypes set imageurl = concat( 'npl/', imageurl )
1417                   where imageurl not like 'http%'
1418                     and imageurl is not NULL
1419                     and imageurl != '') );
1420     print "Upgrade to $DBversion done (updating imagetype.imageurls to reflect new icon locations.)\n";
1421     SetVersion ($DBversion);
1422 }
1423
1424 $DBversion = "3.00.00.075";
1425 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1426     $dbh->do( q(alter table authorised_values add imageurl varchar(200) default NULL) );
1427     print "Upgrade to $DBversion done (adding imageurl field to authorised_values table)\n";
1428     SetVersion ($DBversion);
1429 }
1430
1431 $DBversion = "3.00.00.076";
1432 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1433     $dbh->do("ALTER TABLE import_batches
1434               ADD COLUMN nomatch_action enum('create_new', 'ignore') NOT NULL default 'create_new' AFTER overlay_action");
1435     $dbh->do("ALTER TABLE import_batches
1436               ADD COLUMN item_action enum('always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore')
1437                   NOT NULL default 'always_add' AFTER nomatch_action");
1438     $dbh->do("ALTER TABLE import_batches
1439               MODIFY overlay_action  enum('replace', 'create_new', 'use_template', 'ignore')
1440                   NOT NULL default 'create_new'");
1441     $dbh->do("ALTER TABLE import_records
1442               MODIFY status  enum('error', 'staged', 'imported', 'reverted', 'items_reverted',
1443                                   'ignored') NOT NULL default 'staged'");
1444     $dbh->do("ALTER TABLE import_items
1445               MODIFY status enum('error', 'staged', 'imported', 'reverted', 'ignored') NOT NULL default 'staged'");
1446
1447         print "Upgrade to $DBversion done (changes to import_batches and import_records)\n";
1448         SetVersion ($DBversion);
1449 }
1450
1451 $DBversion = "3.00.00.077";
1452 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1453     # drop these tables only if they exist and none of them are empty
1454     # these tables are not defined in the packaged 2.2.9, but since it is believed
1455     # that at least one library may be using them in a post-2.2.9 but pre-3.0 Koha,
1456     # some care is taken.
1457     my ($print_error) = $dbh->{PrintError};
1458     $dbh->{PrintError} = 0;
1459     my ($raise_error) = $dbh->{RaiseError};
1460     $dbh->{RaiseError} = 1;
1461
1462     my $count = 0;
1463     my $do_drop = 1;
1464     eval { $count = $dbh->do("SELECT 1 FROM categorytable"); };
1465     if ($count > 0) {
1466         $do_drop = 0;
1467     }
1468     eval { $count = $dbh->do("SELECT 1 FROM mediatypetable"); };
1469     if ($count > 0) {
1470         $do_drop = 0;
1471     }
1472     eval { $count = $dbh->do("SELECT 1 FROM subcategorytable"); };
1473     if ($count > 0) {
1474         $do_drop = 0;
1475     }
1476
1477     if ($do_drop) {
1478         $dbh->do("DROP TABLE IF EXISTS `categorytable`");
1479         $dbh->do("DROP TABLE IF EXISTS `mediatypetable`");
1480         $dbh->do("DROP TABLE IF EXISTS `subcategorytable`");
1481     }
1482
1483     $dbh->{PrintError} = $print_error;
1484     $dbh->{RaiseError} = $raise_error;
1485         print "Upgrade to $DBversion done (drop categorytable, subcategorytable, and mediatypetable)\n";
1486         SetVersion ($DBversion);
1487 }
1488
1489 $DBversion = "3.00.00.078";
1490 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1491     my ($print_error) = $dbh->{PrintError};
1492     $dbh->{PrintError} = 0;
1493
1494     unless ($dbh->do("SELECT 1 FROM browser")) {
1495         $dbh->{PrintError} = $print_error;
1496         $dbh->do("CREATE TABLE `browser` (
1497                     `level` int(11) NOT NULL,
1498                     `classification` varchar(20) NOT NULL,
1499                     `description` varchar(255) NOT NULL,
1500                     `number` bigint(20) NOT NULL,
1501                     `endnode` tinyint(4) NOT NULL
1502                   ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1503     }
1504     $dbh->{PrintError} = $print_error;
1505         print "Upgrade to $DBversion done (add browser table if not already present)\n";
1506         SetVersion ($DBversion);
1507 }
1508
1509 $DBversion = "3.00.00.079";
1510 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1511  my ($print_error) = $dbh->{PrintError};
1512     $dbh->{PrintError} = 0;
1513
1514     $dbh->do("INSERT INTO `systempreferences` (variable, value,options,type, explanation)VALUES
1515         ('AddPatronLists','categorycode','categorycode|category_type','Choice','Allow user to choose what list to pick up from when adding patrons')");
1516     print "Upgrade to $DBversion done (add browser table if not already present)\n";
1517         SetVersion ($DBversion);
1518 }
1519
1520 $DBversion = "3.00.00.080";
1521 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1522     $dbh->do("ALTER TABLE subscription CHANGE monthlength monthlength int(11) default '0'");
1523     $dbh->do("ALTER TABLE deleteditems MODIFY marc LONGBLOB AFTER copynumber");
1524     $dbh->do("ALTER TABLE aqbooksellers CHANGE name name mediumtext NOT NULL");
1525         print "Upgrade to $DBversion done (catch up on DB schema changes since alpha and beta)\n";
1526         SetVersion ($DBversion);
1527 }
1528
1529 $DBversion = "3.00.00.081";
1530 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1531     $dbh->do("CREATE TABLE `borrower_attribute_types` (
1532                 `code` varchar(10) NOT NULL,
1533                 `description` varchar(255) NOT NULL,
1534                 `repeatable` tinyint(1) NOT NULL default 0,
1535                 `unique_id` tinyint(1) NOT NULL default 0,
1536                 `opac_display` tinyint(1) NOT NULL default 0,
1537                 `password_allowed` tinyint(1) NOT NULL default 0,
1538                 `staff_searchable` tinyint(1) NOT NULL default 0,
1539                 `authorised_value_category` varchar(10) default NULL,
1540                 PRIMARY KEY  (`code`)
1541               ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1542     $dbh->do("CREATE TABLE `borrower_attributes` (
1543                 `borrowernumber` int(11) NOT NULL,
1544                 `code` varchar(10) NOT NULL,
1545                 `attribute` varchar(30) default NULL,
1546                 `password` varchar(30) default NULL,
1547                 KEY `borrowernumber` (`borrowernumber`),
1548                 KEY `code_attribute` (`code`, `attribute`),
1549                 CONSTRAINT `borrower_attributes_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
1550                     ON DELETE CASCADE ON UPDATE CASCADE,
1551                 CONSTRAINT `borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`)
1552                     ON DELETE CASCADE ON UPDATE CASCADE
1553             ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1554     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ExtendedPatronAttributes','0','Use extended patron IDs and attributes',NULL,'YesNo')");
1555     print "Upgrade to $DBversion done (added borrower_attributes and  borrower_attribute_types)\n";
1556  SetVersion ($DBversion);
1557 }
1558
1559 $DBversion = "3.00.00.082";
1560 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1561     $dbh->do( q(alter table accountlines add column lastincrement decimal(28,6) default NULL) );
1562     print "Upgrade to $DBversion done (adding lastincrement column to accountlines table)\n";
1563     SetVersion ($DBversion);
1564 }
1565
1566 $DBversion = "3.00.00.083";
1567 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1568     $dbh->do( qq(UPDATE systempreferences SET value='local' where variable='yuipath' and value like "%/intranet-tmpl/prog/%"));
1569     print "Upgrade to $DBversion done (Changing yuipath behaviour in managing a local value)\n";
1570     SetVersion ($DBversion);
1571 }
1572 $DBversion = "3.00.00.084";
1573     if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1574     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RenewSerialAddsSuggestion','0','if ON, adds a new suggestion at serial subscription renewal',NULL,'YesNo')");
1575     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('GoogleJackets','0','if ON, displays jacket covers from Google Books API',NULL,'YesNo')");
1576     print "Upgrade to $DBversion done (add new sysprefs)\n";
1577     SetVersion ($DBversion);
1578 }
1579
1580 $DBversion = "3.00.00.085";
1581 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1582     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1583         $dbh->do("UPDATE marc_subfield_structure SET tab = 0 WHERE tab =  9 AND tagfield = '037'");
1584         $dbh->do("UPDATE marc_subfield_structure SET tab = 1 WHERE tab =  6 AND tagfield in ('100', '110', '111', '130')");
1585         $dbh->do("UPDATE marc_subfield_structure SET tab = 2 WHERE tab =  6 AND tagfield in ('240', '243')");
1586         $dbh->do("UPDATE marc_subfield_structure SET tab = 4 WHERE tab =  6 AND tagfield in ('400', '410', '411', '440')");
1587         $dbh->do("UPDATE marc_subfield_structure SET tab = 5 WHERE tab =  9 AND tagfield = '584'");
1588         $dbh->do("UPDATE marc_subfield_structure SET tab = 7 WHERE tab = -6 AND tagfield = '760'");
1589     }
1590     print "Upgrade to $DBversion done (move editing tab of various MARC21 subfields)\n";
1591     SetVersion ($DBversion);
1592 }
1593
1594 $DBversion = "3.00.00.086";
1595 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1596         $dbh->do(
1597         "CREATE TABLE `tmp_holdsqueue` (
1598         `biblionumber` int(11) default NULL,
1599         `itemnumber` int(11) default NULL,
1600         `barcode` varchar(20) default NULL,
1601         `surname` mediumtext NOT NULL,
1602         `firstname` text,
1603         `phone` text,
1604         `borrowernumber` int(11) NOT NULL,
1605         `cardnumber` varchar(16) default NULL,
1606         `reservedate` date default NULL,
1607         `title` mediumtext,
1608         `itemcallnumber` varchar(30) default NULL,
1609         `holdingbranch` varchar(10) default NULL,
1610         `pickbranch` varchar(10) default NULL,
1611         `notes` text
1612         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
1613
1614         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RandomizeHoldsQueueWeight','0','if ON, the holds queue in circulation will be randomized, either based on all location codes, or by the location codes specified in StaticHoldsQueueWeight',NULL,'YesNo')");
1615         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaticHoldsQueueWeight','0','Specify a list of library location codes separated by commas -- the list of codes will be traversed and weighted with first values given higher weight for holds fulfillment -- alternatively, if RandomizeHoldsQueueWeight is set, the list will be randomly selective',NULL,'TextArea')");
1616
1617         print "Upgrade to $DBversion done (Table structure for table `tmp_holdsqueue`)\n";
1618         SetVersion ($DBversion);
1619 }
1620
1621 $DBversion = "3.00.00.087";
1622 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1623     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailOpacUser','0','','Sends notification emails containing new account details to patrons - when account is created.','YesNo')" );
1624     $dbh->do("INSERT INTO `systempreferences` VALUES ('AutoEmailPrimaryAddress','OFF','email|emailpro|B_email|cardnumber|OFF','Defines the default email address where Account Details emails are sent.','Choice')");
1625     print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1626     SetVersion ($DBversion);
1627 }
1628
1629 $DBversion = "3.00.00.088";
1630 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1631         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACShelfBrowser','1','','Enable/disable Shelf Browser on item details page','YesNo')");
1632         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('OPACItemHolds','1','Allow OPAC users to place hold on specific items. If OFF, users can only request next available copy.','','YesNo')");
1633         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('XSLTDetailsDisplay','0','','Enable XSL stylesheet control over details page display on OPAC WARNING: MARC21 Only','YesNo')");
1634         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('XSLTResultsDisplay','0','','Enable XSL stylesheet control over results page display on OPAC WARNING: MARC21 Only','YesNo')");
1635         print "Upgrade to $DBversion done (added 2 new 'AutoEmailOpacUser' sysprefs)\n";
1636     SetVersion ($DBversion);
1637 }
1638
1639 $DBversion = "3.00.00.089";
1640 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1641         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AdvancedSearchTypes','itemtypes','itemtypes|ccode','Select which set of fields comprise the Type limit in the advanced search','Choice')");
1642         print "Upgrade to $DBversion done (added new AdvancedSearchTypes syspref)\n";
1643     SetVersion ($DBversion);
1644 }
1645
1646 $DBversion = "3.00.00.090";
1647 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1648     $dbh->do("
1649         CREATE TABLE `branch_borrower_circ_rules` (
1650           `branchcode` VARCHAR(10) NOT NULL,
1651           `categorycode` VARCHAR(10) NOT NULL,
1652           `maxissueqty` int(4) default NULL,
1653           PRIMARY KEY (`categorycode`, `branchcode`),
1654           CONSTRAINT `branch_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1655             ON DELETE CASCADE ON UPDATE CASCADE,
1656           CONSTRAINT `branch_borrower_circ_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1657             ON DELETE CASCADE ON UPDATE CASCADE
1658         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1659     ");
1660     $dbh->do("
1661         CREATE TABLE `default_borrower_circ_rules` (
1662           `categorycode` VARCHAR(10) NOT NULL,
1663           `maxissueqty` int(4) default NULL,
1664           PRIMARY KEY (`categorycode`),
1665           CONSTRAINT `borrower_borrower_circ_rules_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
1666             ON DELETE CASCADE ON UPDATE CASCADE
1667         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1668     ");
1669     $dbh->do("
1670         CREATE TABLE `default_branch_circ_rules` (
1671           `branchcode` VARCHAR(10) NOT NULL,
1672           `maxissueqty` int(4) default NULL,
1673           PRIMARY KEY (`branchcode`),
1674           CONSTRAINT `default_branch_circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`)
1675             ON DELETE CASCADE ON UPDATE CASCADE
1676         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1677     ");
1678     $dbh->do("
1679         CREATE TABLE `default_circ_rules` (
1680             `singleton` enum('singleton') NOT NULL default 'singleton',
1681             `maxissueqty` int(4) default NULL,
1682             PRIMARY KEY (`singleton`)
1683         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1684     ");
1685     print "Upgrade to $DBversion done (added several circ rules tables)\n";
1686     SetVersion ($DBversion);
1687 }
1688
1689
1690 $DBversion = "3.00.00.091";
1691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1692     $dbh->do(<<'END_SQL');
1693 ALTER TABLE borrowers
1694 ADD `smsalertnumber` varchar(50) default NULL
1695 END_SQL
1696
1697     $dbh->do(<<'END_SQL');
1698 CREATE TABLE `message_attributes` (
1699   `message_attribute_id` int(11) NOT NULL auto_increment,
1700   `message_name` varchar(20) NOT NULL default '',
1701   `takes_days` tinyint(1) NOT NULL default '0',
1702   PRIMARY KEY  (`message_attribute_id`),
1703   UNIQUE KEY `message_name` (`message_name`)
1704 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1705 END_SQL
1706
1707     $dbh->do(<<'END_SQL');
1708 CREATE TABLE `message_transport_types` (
1709   `message_transport_type` varchar(20) NOT NULL,
1710   PRIMARY KEY  (`message_transport_type`)
1711 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1712 END_SQL
1713
1714     $dbh->do(<<'END_SQL');
1715 CREATE TABLE `message_transports` (
1716   `message_attribute_id` int(11) NOT NULL,
1717   `message_transport_type` varchar(20) NOT NULL,
1718   `is_digest` tinyint(1) NOT NULL default '0',
1719   `letter_module` varchar(20) NOT NULL default '',
1720   `letter_code` varchar(20) NOT NULL default '',
1721   PRIMARY KEY  (`message_attribute_id`,`message_transport_type`,`is_digest`),
1722   KEY `message_transport_type` (`message_transport_type`),
1723   KEY `letter_module` (`letter_module`,`letter_code`),
1724   CONSTRAINT `message_transports_ibfk_1` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1725   CONSTRAINT `message_transports_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE,
1726   CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`) REFERENCES `letter` (`module`, `code`) ON DELETE CASCADE ON UPDATE CASCADE
1727 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1728 END_SQL
1729
1730     $dbh->do(<<'END_SQL');
1731 CREATE TABLE `borrower_message_preferences` (
1732   `borrower_message_preference_id` int(11) NOT NULL auto_increment,
1733   `borrowernumber` int(11) NOT NULL default '0',
1734   `message_attribute_id` int(11) default '0',
1735   `days_in_advance` int(11) default '0',
1736   `wants_digets` tinyint(1) NOT NULL default '0',
1737   PRIMARY KEY  (`borrower_message_preference_id`),
1738   KEY `borrowernumber` (`borrowernumber`),
1739   KEY `message_attribute_id` (`message_attribute_id`),
1740   CONSTRAINT `borrower_message_preferences_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1741   CONSTRAINT `borrower_message_preferences_ibfk_2` FOREIGN KEY (`message_attribute_id`) REFERENCES `message_attributes` (`message_attribute_id`) ON DELETE CASCADE ON UPDATE CASCADE
1742 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1743 END_SQL
1744
1745     $dbh->do(<<'END_SQL');
1746 CREATE TABLE `borrower_message_transport_preferences` (
1747   `borrower_message_preference_id` int(11) NOT NULL default '0',
1748   `message_transport_type` varchar(20) NOT NULL default '0',
1749   PRIMARY KEY  (`borrower_message_preference_id`,`message_transport_type`),
1750   KEY `message_transport_type` (`message_transport_type`),
1751   CONSTRAINT `borrower_message_transport_preferences_ibfk_1` FOREIGN KEY (`borrower_message_preference_id`) REFERENCES `borrower_message_preferences` (`borrower_message_preference_id`) ON DELETE CASCADE ON UPDATE CASCADE,
1752   CONSTRAINT `borrower_message_transport_preferences_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE CASCADE ON UPDATE CASCADE
1753 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1754 END_SQL
1755
1756     $dbh->do(<<'END_SQL');
1757 CREATE TABLE `message_queue` (
1758   `message_id` int(11) NOT NULL auto_increment,
1759   `borrowernumber` int(11) NOT NULL,
1760   `subject` text,
1761   `content` text,
1762   `message_transport_type` varchar(20) NOT NULL,
1763   `status` enum('sent','pending','failed','deleted') NOT NULL default 'pending',
1764   `time_queued` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
1765   KEY `message_id` (`message_id`),
1766   KEY `borrowernumber` (`borrowernumber`),
1767   KEY `message_transport_type` (`message_transport_type`),
1768   CONSTRAINT `messageq_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1769   CONSTRAINT `messageq_ibfk_2` FOREIGN KEY (`message_transport_type`) REFERENCES `message_transport_types` (`message_transport_type`) ON DELETE RESTRICT ON UPDATE CASCADE
1770 ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1771 END_SQL
1772
1773     $dbh->do(<<'END_SQL');
1774 INSERT INTO `systempreferences`
1775   (variable,value,explanation,options,type)
1776 VALUES
1777 ('EnhancedMessagingPreferences',0,'If ON, allows patrons to select to receive additional messages about items due or nearly due.','','YesNo')
1778 END_SQL
1779
1780     $dbh->do( <<'END_SQL');
1781 INSERT INTO `letter`
1782 (module, code, name, title, content)
1783 VALUES
1784 ('circulation','DUE','Item Due Reminder','Item Due Reminder','Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nThe following item is now due:\r\n\r\n<<biblio.title>> by <<biblio.author>>'),
1785 ('circulation','DUEDGST','Item Due Reminder (Digest)','Item Due Reminder','You have <<count>> items due'),
1786 ('circulation','PREDUE','Advance Notice of Item Due','Advance Notice of Item Due','Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nThe following item will be due soon:\r\n\r\n<<biblio.title>> by <<biblio.author>>'),
1787 ('circulation','PREDUEDGST','Advance Notice of Item Due (Digest)','Advance Notice of Item Due','You have <<count>> items due soon'),
1788 ('circulation','EVENT','Upcoming Library Event','Upcoming Library Event','Dear <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nThis is a reminder of an upcoming library event in which you have expressed interest.');
1789 END_SQL
1790
1791     my @sql_scripts = (
1792         'installer/data/mysql/en/mandatory/message_transport_types.sql',
1793         'installer/data/mysql/en/optional/sample_notices_message_attributes.sql',
1794         'installer/data/mysql/en/optional/sample_notices_message_transports.sql',
1795     );
1796
1797     my $installer = C4::Installer->new();
1798     foreach my $script ( @sql_scripts ) {
1799         my $full_path = $installer->get_file_path_from_name($script);
1800         my $error = $installer->load_sql($full_path);
1801         warn $error if $error;
1802     }
1803
1804     print "Upgrade to $DBversion done (Table structure for table `message_queue`, `message_transport_types`, `message_attributes`, `message_transports`, `borrower_message_preferences`, and `borrower_message_transport_preferences`.  Alter `borrowers` table,\n";
1805     SetVersion ($DBversion);
1806 }
1807
1808 $DBversion = "3.00.00.092";
1809 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1810     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowOnShelfHolds', '0', '', 'Allow hold requests to be placed on items that are not on loan', 'YesNo')");
1811     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES('AllowHoldsOnDamagedItems', '1', '', 'Allow hold requests to be placed on damaged items', 'YesNo')");
1812         print "Upgrade to $DBversion done (added new AllowOnShelfHolds syspref)\n";
1813     SetVersion ($DBversion);
1814 }
1815
1816 $DBversion = "3.00.00.093";
1817 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1818     $dbh->do("ALTER TABLE `items` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1819     $dbh->do("ALTER TABLE `deleteditems` MODIFY COLUMN `copynumber` VARCHAR(32) DEFAULT NULL");
1820         print "Upgrade to $DBversion done (Change data type of items.copynumber to allow free text)\n";
1821     SetVersion ($DBversion);
1822 }
1823
1824 $DBversion = "3.00.00.094";
1825 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1826     $dbh->do("ALTER TABLE `marc_subfield_structure` MODIFY `tagsubfield` VARCHAR(1) NOT NULL DEFAULT '' COLLATE utf8_bin");
1827         print "Upgrade to $DBversion done (Change Collation of marc_subfield_structure to allow mixed case in subfield labels.)\n";
1828     SetVersion ($DBversion);
1829 }
1830
1831 $DBversion = "3.00.00.095";
1832 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1833     if (C4::Context->preference("marcflavour") eq 'MARC21') {
1834         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'MEETI_NAME' WHERE authtypecode = 'Meeting Name'");
1835         $dbh->do("UPDATE marc_subfield_structure SET authtypecode = 'CORPO_NAME' WHERE authtypecode = 'CORP0_NAME'");
1836     }
1837         print "Upgrade to $DBversion done (fix invalid authority types in MARC21 frameworks [bug 2254])\n";
1838     SetVersion ($DBversion);
1839 }
1840
1841 $DBversion = "3.00.00.096";
1842 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1843     $sth = $dbh->prepare("SHOW COLUMNS FROM borrower_message_preferences LIKE 'wants_digets'");
1844     $sth->execute();
1845     if (my $row = $sth->fetchrow_hashref) {
1846         $dbh->do("ALTER TABLE borrower_message_preferences CHANGE wants_digets wants_digest tinyint(1) NOT NULL default 0");
1847     }
1848         print "Upgrade to $DBversion done (fix name borrower_message_preferences.wants_digest)\n";
1849     SetVersion ($DBversion);
1850 }
1851
1852 $DBversion = '3.00.00.097';
1853 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1854
1855     $dbh->do('ALTER TABLE message_queue ADD to_address   mediumtext default NULL');
1856     $dbh->do('ALTER TABLE message_queue ADD from_address mediumtext default NULL');
1857     $dbh->do('ALTER TABLE message_queue ADD content_type text');
1858     $dbh->do('ALTER TABLE message_queue CHANGE borrowernumber borrowernumber int(11) default NULL');
1859
1860     print "Upgrade to $DBversion done (updating 4 fields in message_queue table)\n";
1861     SetVersion($DBversion);
1862 }
1863
1864 $DBversion = '3.00.00.098';
1865 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1866
1867     $dbh->do(q(DELETE FROM message_transport_types WHERE message_transport_type = 'rss'));
1868     $dbh->do(q(DELETE FROM message_transports WHERE message_transport_type = 'rss'));
1869
1870     print "Upgrade to $DBversion done (removing unused RSS message_transport_type)\n";
1871     SetVersion($DBversion);
1872 }
1873
1874 $DBversion = '3.00.00.099';
1875 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1876     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('OpacSuppression', '0', '', 'Turn ON the OPAC Suppression feature, requires further setup, ask your system administrator for details', 'YesNo')");
1877     print "Upgrade to $DBversion done (Adding OpacSuppression syspref)\n";
1878     SetVersion($DBversion);
1879 }
1880
1881 $DBversion = '3.00.00.100';
1882 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1883         $dbh->do('ALTER TABLE virtualshelves ADD COLUMN lastmodified timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP');
1884     print "Upgrade to $DBversion done (Adding lastmodified column to virtualshelves)\n";
1885     SetVersion($DBversion);
1886 }
1887
1888 $DBversion = '3.00.00.101';
1889 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1890         $dbh->do('ALTER TABLE `overduerules` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1891         $dbh->do('ALTER TABLE `deletedborrowers` CHANGE `categorycode` `categorycode` VARCHAR(10) NOT NULL');
1892     print "Upgrade to $DBversion done (Updating columnd definitions for patron category codes in notice/statsu triggers and deletedborrowers tables.)\n";
1893     SetVersion($DBversion);
1894 }
1895
1896 $DBversion = '3.00.00.102';
1897 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1898         $dbh->do('ALTER TABLE serialitems MODIFY `serialid` int(11) NOT NULL AFTER itemnumber' );
1899         $dbh->do('ALTER TABLE serialitems DROP KEY serialididx' );
1900         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT UNIQUE KEY serialitemsidx (itemnumber)' );
1901         # before setting constraint, delete any unvalid data
1902         $dbh->do('DELETE from serialitems WHERE serialid not in (SELECT serial.serialid FROM serial)');
1903         $dbh->do('ALTER TABLE serialitems ADD CONSTRAINT serialitems_sfk_1 FOREIGN KEY (serialid) REFERENCES serial (serialid) ON DELETE CASCADE ON UPDATE CASCADE' );
1904     print "Upgrade to $DBversion done (Updating serialitems table to allow for multiple items per serial fixing kohabug 2380)\n";
1905     SetVersion($DBversion);
1906 }
1907
1908 $DBversion = "3.00.00.103";
1909 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1910     $dbh->do("DELETE FROM systempreferences WHERE variable='serialsadditems'");
1911     print "Upgrade to $DBversion done ( Verifying the removal of serialsadditems from syspref fixing kohabug 2219)\n";
1912     SetVersion ($DBversion);
1913 }
1914
1915 $DBversion = "3.00.00.104";
1916 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1917     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1918     print "Upgrade to $DBversion done (remove superseded 'noOPACHolds' system preference per bug 2413)\n";
1919     SetVersion ($DBversion);
1920 }
1921
1922 $DBversion = '3.00.00.105';
1923 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
1924
1925     # it is possible that this syspref is already defined since the feature was added some time ago.
1926     unless ( $dbh->do(q(SELECT variable FROM systempreferences WHERE variable = 'SMSSendDriver')) ) {
1927         $dbh->do(<<'END_SQL');
1928 INSERT INTO `systempreferences`
1929   (variable,value,explanation,options,type)
1930 VALUES
1931 ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')
1932 END_SQL
1933     }
1934     print "Upgrade to $DBversion done (added SMSSendDriver system preference)\n";
1935     SetVersion($DBversion);
1936 }
1937
1938 $DBversion = "3.00.00.106";
1939 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1940     $dbh->do("DELETE FROM systempreferences WHERE variable='noOPACHolds'");
1941
1942 # db revision 105 didn't apply correctly, so we're rolling this into 106
1943         $dbh->do("INSERT INTO `systempreferences`
1944    (variable,value,explanation,options,type)
1945         VALUES
1946         ('SMSSendDriver','','Sets which SMS::Send driver is used to send SMS messages.','','free')");
1947
1948     print "Upgrade to $DBversion done (remove default '0000-00-00' in subscriptionhistory.enddate field)\n";
1949     $dbh->do("ALTER TABLE `subscriptionhistory` CHANGE `enddate` `enddate` DATE NULL DEFAULT NULL ");
1950
1951     sanitize_zero_date('subscriptionhistory', 'enddate');
1952
1953     SetVersion ($DBversion);
1954 }
1955
1956 $DBversion = '3.00.00.107';
1957 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1958     $dbh->do(<<'END_SQL');
1959 UPDATE systempreferences
1960   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming on collections with large numbers of items.' )
1961   WHERE variable = 'OPACShelfBrowser'
1962     AND explanation NOT LIKE '%WARNING%'
1963 END_SQL
1964     $dbh->do(<<'END_SQL');
1965 UPDATE systempreferences
1966   SET explanation = CONCAT( explanation, '. WARNING: this feature is very resource consuming.' )
1967   WHERE variable = 'CataloguingLog'
1968     AND explanation NOT LIKE '%WARNING%'
1969 END_SQL
1970     $dbh->do(<<'END_SQL');
1971 UPDATE systempreferences
1972   SET explanation = CONCAT( explanation, '. WARNING: using NoZebra on even modest sized collections is very slow.' )
1973   WHERE variable = 'NoZebra'
1974     AND explanation NOT LIKE '%WARNING%'
1975 END_SQL
1976     print "Upgrade to $DBversion done (warning added to OPACShelfBrowser system preference)\n";
1977     SetVersion ($DBversion);
1978 }
1979
1980 $DBversion = '3.01.00.000';
1981 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
1982     print "Upgrade to $DBversion done (start of 3.1)\n";
1983     SetVersion ($DBversion);
1984 }
1985
1986 $DBversion = '3.01.00.001';
1987 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
1988     $dbh->do("
1989         CREATE TABLE hold_fill_targets (
1990             `borrowernumber` int(11) NOT NULL,
1991             `biblionumber` int(11) NOT NULL,
1992             `itemnumber` int(11) NOT NULL,
1993             `source_branchcode`  varchar(10) default NULL,
1994             `item_level_request` tinyint(4) NOT NULL default 0,
1995             PRIMARY KEY `itemnumber` (`itemnumber`),
1996             KEY `bib_branch` (`biblionumber`, `source_branchcode`),
1997             CONSTRAINT `hold_fill_targets_ibfk_1` FOREIGN KEY (`borrowernumber`)
1998                 REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
1999             CONSTRAINT `hold_fill_targets_ibfk_2` FOREIGN KEY (`biblionumber`)
2000                 REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2001             CONSTRAINT `hold_fill_targets_ibfk_3` FOREIGN KEY (`itemnumber`)
2002                 REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
2003             CONSTRAINT `hold_fill_targets_ibfk_4` FOREIGN KEY (`source_branchcode`)
2004                 REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2005         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2006     ");
2007     $dbh->do("
2008         ALTER TABLE tmp_holdsqueue
2009             ADD item_level_request tinyint(4) NOT NULL default 0
2010     ");
2011
2012     print "Upgrade to $DBversion done (add hold_fill_targets table and a column to tmp_holdsqueue)\n";
2013     SetVersion($DBversion);
2014 }
2015
2016 $DBversion = '3.01.00.002';
2017 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2018     # use statistics where available
2019     $dbh->do("
2020         ALTER TABLE statistics ADD KEY  tmp_stats (type, itemnumber, borrowernumber)
2021     ");
2022     $dbh->do("
2023         UPDATE issues iss
2024         SET issuedate = (
2025             SELECT max(datetime)
2026             FROM statistics
2027             WHERE type = 'issue'
2028             AND itemnumber = iss.itemnumber
2029             AND borrowernumber = iss.borrowernumber
2030         )
2031         WHERE issuedate IS NULL;
2032     ");
2033     $dbh->do("ALTER TABLE statistics DROP KEY tmp_stats");
2034
2035     # default to last renewal date
2036     $dbh->do("
2037         UPDATE issues
2038         SET issuedate = lastreneweddate
2039         WHERE issuedate IS NULL
2040         and lastreneweddate IS NOT NULL
2041     ");
2042
2043     my $num_bad_issuedates = $dbh->selectrow_array("SELECT COUNT(*) FROM issues WHERE issuedate IS NULL");
2044     if ($num_bad_issuedates > 0) {
2045         print STDERR "After the upgrade to $DBversion, there are still $num_bad_issuedates loan(s) with a NULL (blank) loan date. ",
2046                      "Please check the issues table in your database.";
2047     }
2048     print "Upgrade to $DBversion done (bug 2582: set null issues.issuedate to lastreneweddate)\n";
2049     SetVersion($DBversion);
2050 }
2051
2052 $DBversion = "3.01.00.003";
2053 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2054     $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')");
2055     print "Upgrade to $DBversion done (add new syspref)\n";
2056     SetVersion ($DBversion);
2057 }
2058
2059 $DBversion = '3.01.00.004';
2060 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2061     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACDisplayRequestPriority','0','Show patrons the priority level on holds in the OPAC','','YesNo')");
2062     print "Upgrade to $DBversion done (added OPACDisplayRequestPriority system preference)\n";
2063     SetVersion ($DBversion);
2064 }
2065
2066 $DBversion = '3.01.00.005';
2067 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2068     $dbh->do("
2069         INSERT INTO `letter` (module, code, name, title, content)
2070         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>>')
2071     ");
2072     $dbh->do("INSERT INTO `message_attributes` (message_attribute_id, message_name, takes_days) values(4, 'Hold Filled', 0)");
2073     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'sms', 0, 'reserves', 'HOLD')");
2074     $dbh->do("INSERT INTO `message_transports` (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) values(4, 'email', 0, 'reserves', 'HOLD')");
2075     print "Upgrade to $DBversion done (Add letter for holds notifications)\n";
2076     SetVersion ($DBversion);
2077 }
2078
2079 $DBversion = '3.01.00.006';
2080 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2081     $dbh->do("ALTER TABLE `biblioitems` ADD KEY issn (issn)");
2082     print "Upgrade to $DBversion done (add index on biblioitems.issn)\n";
2083     SetVersion ($DBversion);
2084 }
2085
2086 $DBversion = "3.01.00.007";
2087 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2088     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetmainUserblock'");
2089     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='intranetuserjs'");
2090     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacheader'");
2091     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacMainUserBlock'");
2092     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='OpacNav'");
2093     $dbh->do("UPDATE `systempreferences` SET options='70|10' WHERE variable='opacuserjs'");
2094     $dbh->do("UPDATE `systempreferences` SET options='30|10', type='Textarea' WHERE variable='OAI-PMH:Set'");
2095     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetstylesheet'");
2096     $dbh->do("UPDATE `systempreferences` SET options='50' WHERE variable='intranetcolorstylesheet'");
2097     $dbh->do("UPDATE `systempreferences` SET options='10' WHERE variable='globalDueDate'");
2098     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='numSearchResults'");
2099     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='OPACnumSearchResults'");
2100     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='ReservesMaxPickupDelay'");
2101     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='TransfersMaxDaysWarning'");
2102     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='StaticHoldsQueueWeight'");
2103     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='holdCancelLength'");
2104     $dbh->do("UPDATE `systempreferences` SET type='Integer' WHERE variable='XISBNDailyLimit'");
2105     $dbh->do("UPDATE `systempreferences` SET type='Float' WHERE variable='gist'");
2106     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorUsername'");
2107     $dbh->do("UPDATE `systempreferences` SET type='Free' WHERE variable='BakerTaylorPassword'");
2108     $dbh->do("UPDATE `systempreferences` SET type='Textarea', options='70|10' WHERE variable='ISBD'");
2109     $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'");
2110     print "Upgrade to $DBversion done (fix display of many sysprefs)\n";
2111     SetVersion ($DBversion);
2112 }
2113
2114 $DBversion = '3.01.00.008';
2115 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2116
2117     $dbh->do("CREATE TABLE branch_transfer_limits (
2118                           limitId int(8) NOT NULL auto_increment,
2119                           toBranch varchar(4) NOT NULL,
2120                           fromBranch varchar(4) NOT NULL,
2121                           itemtype varchar(4) NOT NULL,
2122                           PRIMARY KEY  (limitId)
2123                           ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
2124                         );
2125
2126     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'UseBranchTransferLimits', '0', '', 'If ON, Koha will will use the rules defined in branch_transfer_limits to decide if an item transfer should be allowed.', 'YesNo')");
2127
2128     print "Upgrade to $DBversion done (added branch_transfer_limits table and UseBranchTransferLimits system preference)\n";
2129     SetVersion ($DBversion);
2130 }
2131
2132 $DBversion = "3.01.00.009";
2133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2134     $dbh->do("ALTER TABLE permissions MODIFY `code` varchar(64) DEFAULT NULL");
2135     $dbh->do("ALTER TABLE user_permissions MODIFY `code` varchar(64) DEFAULT NULL");
2136     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'circulate_remaining_permissions', 'Remaining circulation permissions')");
2137     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'override_renewals', 'Override blocked renewals')");
2138     print "Upgrade to $DBversion done (added subpermissions for circulate permission)\n";
2139 }
2140
2141 $DBversion = '3.01.00.010';
2142 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2143     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `attribute` VARCHAR(64) DEFAULT NULL");
2144     $dbh->do("ALTER TABLE `borrower_attributes` MODIFY COLUMN `password` VARCHAR(64) DEFAULT NULL");
2145     print "Upgrade to $DBversion done (bug 2687: increase length of borrower attribute fields)\n";
2146     SetVersion ($DBversion);
2147 }
2148
2149 $DBversion = '3.01.00.011';
2150 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2151
2152     # Yes, the old value was ^M terminated.
2153     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);";
2154
2155     my $intranetuserjs = C4::Context->preference('intranetuserjs');
2156     if ($intranetuserjs  and  $intranetuserjs eq $bad_value) {
2157         my $sql = <<'END_SQL';
2158 UPDATE systempreferences
2159 SET value = ''
2160 WHERE variable = 'intranetuserjs'
2161 END_SQL
2162         $dbh->do($sql);
2163     }
2164     print "Upgrade to $DBversion done (removed bogus intranetuserjs syspref)\n";
2165     SetVersion($DBversion);
2166 }
2167
2168 $DBversion = "3.01.00.012";
2169 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2170     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldPolicyOverride', '0', 'Allow staff to override hold policies when placing holds',NULL,'YesNo')");
2171     $dbh->do("
2172         CREATE TABLE `branch_item_rules` (
2173           `branchcode` varchar(10) NOT NULL,
2174           `itemtype` varchar(10) NOT NULL,
2175           `holdallowed` tinyint(1) default NULL,
2176           PRIMARY KEY  (`itemtype`,`branchcode`),
2177           KEY `branch_item_rules_ibfk_2` (`branchcode`),
2178           CONSTRAINT `branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
2179           CONSTRAINT `branch_item_rules_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
2180         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2181     ");
2182     $dbh->do("
2183         CREATE TABLE `default_branch_item_rules` (
2184           `itemtype` varchar(10) NOT NULL,
2185           `holdallowed` tinyint(1) default NULL,
2186           PRIMARY KEY  (`itemtype`),
2187           CONSTRAINT `default_branch_item_rules_ibfk_1` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE
2188         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2189     ");
2190     $dbh->do("
2191         ALTER TABLE default_branch_circ_rules
2192             ADD COLUMN holdallowed tinyint(1) NULL
2193     ");
2194     $dbh->do("
2195         ALTER TABLE default_circ_rules
2196             ADD COLUMN holdallowed tinyint(1) NULL
2197     ");
2198     print "Upgrade to $DBversion done (Add tables and system preferences for holds policies)\n";
2199     SetVersion ($DBversion);
2200 }
2201
2202 $DBversion = '3.01.00.013';
2203 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2204     $dbh->do("
2205         CREATE TABLE item_circulation_alert_preferences (
2206             id           int(11) AUTO_INCREMENT,
2207             branchcode   varchar(10) NOT NULL,
2208             categorycode varchar(10) NOT NULL,
2209             item_type    varchar(10) NOT NULL,
2210             notification varchar(16) NOT NULL,
2211             PRIMARY KEY (id),
2212             KEY (branchcode, categorycode, item_type, notification)
2213         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2214     ");
2215
2216     $dbh->do(q{ ALTER TABLE `message_queue` ADD metadata text DEFAULT NULL           AFTER content;  });
2217     $dbh->do(q{ ALTER TABLE `message_queue` ADD letter_code varchar(64) DEFAULT NULL AFTER metadata; });
2218
2219     $dbh->do(q{
2220         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2221         ('circulation','CHECKIN','Item Check-in','Check-ins','The following items have been checked in:\r\n----\r\n<<biblio.title>>\r\n----\r\nThank you.');
2222     });
2223     $dbh->do(q{
2224         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
2225         ('circulation','CHECKOUT','Item Checkout','Checkouts','The following items have been checked out:\r\n----\r\n<<biblio.title>>\r\n----\r\nThank you for visiting <<branches.branchname>>.');
2226     });
2227
2228     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (5, 'Item Check-in', 0);});
2229     $dbh->do(q{INSERT INTO message_attributes (message_attribute_id, message_name, takes_days) VALUES (6, 'Item Checkout', 0);});
2230
2231     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (5, 'email', 0, 'circulation', 'CHECKIN');});
2232     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (5, 'sms',   0, 'circulation', 'CHECKIN');});
2233     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (6, 'email', 0, 'circulation', 'CHECKOUT');});
2234     $dbh->do(q{INSERT INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES (6, 'sms',   0, 'circulation', 'CHECKOUT');});
2235
2236     print "Upgrade to $DBversion done (data for Email Checkout Slips project)\n";
2237          SetVersion ($DBversion);
2238 }
2239
2240 $DBversion = "3.01.00.014";
2241 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2242     $dbh->do("ALTER TABLE `branch_transfer_limits` CHANGE `itemtype` `itemtype` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");
2243     $dbh->do("ALTER TABLE `branch_transfer_limits` ADD `ccode` VARCHAR( 10 ) NULL ;");
2244     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2245     VALUES (
2246     'BranchTransferLimitsType', 'ccode', 'itemtype|ccode', 'When using branch transfer limits, choose whether to limit by itemtype or collection code.', 'Choice'
2247     );");
2248
2249     print "Upgrade to $DBversion done ( Updated table for Branch Transfer Limits)\n";
2250     SetVersion ($DBversion);
2251 }
2252
2253 $DBversion = '3.01.00.015';
2254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2255     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsClientCode', '0', 'Client Code for using Syndetics Solutions content','','free')");
2256
2257     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEnabled', '0', 'Turn on Syndetics Enhanced Content','','YesNo')");
2258
2259     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImages', '0', 'Display Cover Images from Syndetics','','YesNo')");
2260
2261     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsTOC', '0', 'Display Table of Content information from Syndetics','','YesNo')");
2262
2263     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSummary', '0', 'Display Summary Information from Syndetics','','YesNo')");
2264
2265     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsEditions', '0', 'Display Editions from Syndetics','','YesNo')");
2266
2267     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsExcerpt', '0', 'Display Excerpts and first chapters on OPAC from Syndetics','','YesNo')");
2268
2269     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsReviews', '0', 'Display Reviews on OPAC from Syndetics','','YesNo')");
2270
2271     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAuthorNotes', '0', 'Display Notes about the Author on OPAC from Syndetics','','YesNo')");
2272
2273     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsAwards', '0', 'Display Awards on OPAC from Syndetics','','YesNo')");
2274
2275     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsSeries', '0', 'Display Series information on OPAC from Syndetics','','YesNo')");
2276
2277     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SyndeticsCoverImageSize', 'MC', 'Choose the size of the Syndetics Cover Image to display on the OPAC detail page, MC is Medium, LC is Large','MC|LC','Choice')");
2278
2279     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonCoverImages', '0', 'Display cover images on OPAC from Amazon Web Services','','YesNo')");
2280
2281     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonCoverImages', '0', 'Display Cover Images in Staff Client from Amazon Web Services','','YesNo')");
2282
2283     $dbh->do("UPDATE systempreferences SET variable='AmazonEnabled' WHERE variable = 'AmazonContent'");
2284
2285     $dbh->do("UPDATE systempreferences SET variable='OPACAmazonEnabled' WHERE variable = 'OPACAmazonContent'");
2286
2287     print "Upgrade to $DBversion done (added Syndetics Enhanced Content system preferences)\n";
2288     SetVersion ($DBversion);
2289 }
2290
2291 $DBversion = "3.01.00.016";
2292 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2293     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('Babeltheque',0,'Turn ON Babeltheque content  - See babeltheque.com to subscribe to this service','','YesNo')");
2294     print "Upgrade to $DBversion done (Added Babeltheque syspref)\n";
2295     SetVersion ($DBversion);
2296 }
2297
2298 $DBversion = "3.01.00.017";
2299 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2300     $dbh->do("ALTER TABLE `subscription` ADD `staffdisplaycount` VARCHAR(10) NULL;");
2301     $dbh->do("ALTER TABLE `subscription` ADD `opacdisplaycount` VARCHAR(10) NULL;");
2302     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2303     VALUES (
2304     'StaffSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the Staff client', 'Integer'
2305     );");
2306         $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` )
2307     VALUES (
2308     'OPACSerialIssueDisplayCount', '3', '', 'Number of serial issues to display per subscription in the OPAC', 'Integer'
2309     );");
2310
2311     print "Upgrade to $DBversion done ( Updated table for Serials Display)\n";
2312     SetVersion ($DBversion);
2313 }
2314
2315 $DBversion = "3.01.00.018";
2316 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2317     $dbh->do("ALTER TABLE deletedborrowers ADD `smsalertnumber` varchar(50) default NULL");
2318     print "Upgrade to $DBversion done (added deletedborrowers.smsalertnumber, missed in 3.00.00.091)\n";
2319     SetVersion ($DBversion);
2320 }
2321
2322 $DBversion = "3.01.00.019";
2323 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2324         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowCheckoutName','0','Displays in the OPAC the name of patron who has checked out the material. WARNING: Most sites should leave this off. It is intended for corporate or special sites which need to track who has the item.','','YesNo')");
2325     print "Upgrade to $DBversion done (adding OPACShowCheckoutName systempref)\n";
2326     SetVersion ($DBversion);
2327 }
2328
2329 $DBversion = "3.01.00.020";
2330 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2331     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesID','','See:http://librarything.com/forlibraries/','','free')");
2332     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesEnabled','0','Enable or Disable Library Thing for Libraries Features','','YesNo')");
2333     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('LibraryThingForLibrariesTabbedView','0','Put LibraryThingForLibraries Content in Tabs.','','YesNo')");
2334     print "Upgrade to $DBversion done (adding LibraryThing for Libraries sysprefs)\n";
2335     SetVersion ($DBversion);
2336 }
2337
2338 $DBversion = "3.01.00.021";
2339 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2340     my $enable_reviews = C4::Context->preference('OPACAmazonEnabled') ? '1' : '0';
2341     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAmazonReviews', '$enable_reviews', 'Display Amazon readers reviews on OPAC','','YesNo')");
2342     print "Upgrade to $DBversion done (adding OPACAmazonReviews syspref)\n";
2343     SetVersion ($DBversion);
2344 }
2345
2346 $DBversion = '3.01.00.022';
2347 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2348     $dbh->do("ALTER TABLE `labels_conf` MODIFY COLUMN `formatstring` mediumtext DEFAULT NULL");
2349     print "Upgrade to $DBversion done (bug 2945: increase size of labels_conf.formatstring)\n";
2350     SetVersion ($DBversion);
2351 }
2352
2353 $DBversion = '3.01.00.023';
2354 if ( C4::Context->preference('Version') < TransformToNum($DBversion) ) {
2355     $dbh->do("ALTER TABLE biblioitems        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2356     $dbh->do("ALTER TABLE deletedbiblioitems MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2357     $dbh->do("ALTER TABLE import_biblios     MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2358     $dbh->do("ALTER TABLE suggestions        MODIFY COLUMN isbn VARCHAR(30) DEFAULT NULL");
2359     print "Upgrade to $DBversion done (bug 2765: increase width of isbn column in several tables)\n";
2360     SetVersion ($DBversion);
2361 }
2362
2363 $DBversion = "3.01.00.024";
2364 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2365     $dbh->do("ALTER TABLE labels MODIFY COLUMN batch_id int(10) NOT NULL default 1;");
2366     print "Upgrade to $DBversion done (change labels.batch_id from varchar to int)\n";
2367     SetVersion ($DBversion);
2368 }
2369
2370 $DBversion = '3.01.00.025';
2371 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2372     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'ceilingDueDate', '', '', 'If set, date due will not be past this date.  Enter date according to the dateformat System Preference', 'free')");
2373
2374     print "Upgrade to $DBversion done (added ceilingDueDate system preference)\n";
2375     SetVersion ($DBversion);
2376 }
2377
2378 $DBversion = '3.01.00.026';
2379 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2380     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'numReturnedItemsToShow', '20', '', 'Number of returned items to show on the check-in page', 'Integer')");
2381
2382     print "Upgrade to $DBversion done (added numReturnedItemsToShow system preference)\n";
2383     SetVersion ($DBversion);
2384 }
2385
2386 $DBversion = '3.01.00.027';
2387 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2388     $dbh->do("ALTER TABLE zebraqueue CHANGE `biblio_auth_number` `biblio_auth_number` bigint(20) unsigned NOT NULL default 0");
2389     print "Upgrade to $DBversion done (Increased size of zebraqueue biblio_auth_number to address bug 3148.)\n";
2390     SetVersion ($DBversion);
2391 }
2392
2393 $DBversion = '3.01.00.028';
2394 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2395     my $enable_reviews = C4::Context->preference('AmazonEnabled') ? '1' : '0';
2396     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AmazonReviews', '$enable_reviews', 'Display Amazon reviews on staff interface','','YesNo')");
2397     print "Upgrade to $DBversion done (added AmazonReviews)\n";
2398     SetVersion ($DBversion);
2399 }
2400
2401 $DBversion = '3.01.00.029';
2402 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2403     $dbh->do(q( UPDATE language_rfc4646_to_iso639
2404                 SET iso639_2_code = 'spa'
2405                 WHERE rfc4646_subtag = 'es'
2406                 AND   iso639_2_code = 'rus' )
2407             );
2408     print "Upgrade to $DBversion done (fixed bug 2599: using Spanish search limit retrieves Russian results)\n";
2409     SetVersion ($DBversion);
2410 }
2411
2412 $DBversion = "3.01.00.030";
2413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2414     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'AllowNotForLoanOverride', '0', '', 'If ON, Koha will allow the librarian to loan a not for loan item.', 'YesNo')");
2415     print "Upgrade to $DBversion done (added AllowNotForLoanOverride system preference)\n";
2416     SetVersion ($DBversion);
2417 }
2418
2419 $DBversion = "3.01.00.031";
2420 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2421     $dbh->do("ALTER TABLE branch_transfer_limits
2422               MODIFY toBranch   varchar(10) NOT NULL,
2423               MODIFY fromBranch varchar(10) NOT NULL,
2424               MODIFY itemtype   varchar(10) NULL");
2425     print "Upgrade to $DBversion done (fix column widths in branch_transfer_limits)\n";
2426     SetVersion ($DBversion);
2427 }
2428
2429 $DBversion = "3.01.00.032";
2430 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2431     $dbh->do(<<ENDOFRENEWAL);
2432 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RenewalPeriodBase', 'now', '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');
2433 ENDOFRENEWAL
2434     print "Upgrade to $DBversion done (Change the field)\n";
2435     SetVersion ($DBversion);
2436 }
2437
2438 $DBversion = "3.01.00.033";
2439 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2440     $dbh->do(q/
2441         ALTER TABLE borrower_message_preferences
2442         MODIFY borrowernumber int(11) default NULL,
2443         ADD    categorycode varchar(10) default NULL AFTER borrowernumber,
2444         ADD KEY `categorycode` (`categorycode`),
2445         ADD CONSTRAINT `borrower_message_preferences_ibfk_3`
2446                        FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`)
2447                        ON DELETE CASCADE ON UPDATE CASCADE
2448     /);
2449     print "Upgrade to $DBversion done (DB changes to allow patron category defaults for messaging preferences)\n";
2450     SetVersion ($DBversion);
2451 }
2452
2453 $DBversion = "3.01.00.034";
2454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2455     $dbh->do("ALTER TABLE `subscription` ADD COLUMN `graceperiod` INT(11) NOT NULL default '0';");
2456     print "Upgrade to $DBversion done (Adding graceperiod column to subscription table)\n";
2457     SetVersion ($DBversion);
2458 }
2459
2460 $DBversion = '3.01.00.035';
2461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2462     $dbh->do(q{ ALTER TABLE `subscription` ADD location varchar(80) NULL DEFAULT '' AFTER callnumber; });
2463    print "Upgrade to $DBversion done (Adding location to subscription table)\n";
2464     SetVersion ($DBversion);
2465 }
2466
2467 $DBversion = '3.01.00.036';
2468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2469     $dbh->do("UPDATE systempreferences SET explanation = 'Choose the default detail view in the staff interface; choose between normal, labeled_marc, marc or isbd'
2470               WHERE variable = 'IntranetBiblioDefaultView'
2471               AND   explanation = 'IntranetBiblioDefaultView'");
2472     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = 'normal|marc|isbd|labeled_marc'
2473               WHERE variable = 'IntranetBiblioDefaultView'");
2474     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewISBD','1','Allow display of ISBD view of bibiographic records','','YesNo')");
2475     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewLabeledMARC','0','Allow display of labeled MARC view of bibiographic records','','YesNo')");
2476     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('viewMARC','1','Allow display of MARC view of bibiographic records','','YesNo')");
2477     print "Upgrade to $DBversion done (new viewISBD, viewLabeledMARC, viewMARC sysprefs and tweak IntranetBiblioDefaultView)\n";
2478     SetVersion ($DBversion);
2479 }
2480
2481 $DBversion = '3.01.00.037';
2482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2483     $dbh->do('ALTER TABLE authorised_values ADD KEY `lib` (`lib`)');
2484     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('FilterBeforeOverdueReport','0','Do not run overdue report until filter selected','','YesNo')");
2485     SetVersion ($DBversion);
2486     print "Upgrade to $DBversion done (added FilterBeforeOverdueReport syspref and new index on authorised_values)\n";
2487 }
2488
2489 $DBversion = "3.01.00.038";
2490 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2491     # update branches table
2492     #
2493     $dbh->do("ALTER TABLE branches ADD `branchzip` varchar(25) default NULL AFTER `branchaddress3`");
2494     $dbh->do("ALTER TABLE branches ADD `branchcity` mediumtext AFTER `branchzip`");
2495     $dbh->do("ALTER TABLE branches ADD `branchcountry` text AFTER `branchcity`");
2496     $dbh->do("ALTER TABLE branches ADD `branchurl` mediumtext AFTER `branchemail`");
2497     $dbh->do("ALTER TABLE branches ADD `branchnotes` mediumtext AFTER `branchprinter`");
2498     print "Upgrade to $DBversion done (add ZIP, city, country, URL, and notes column to branches)\n";
2499     SetVersion ($DBversion);
2500 }
2501
2502 $DBversion = '3.01.00.039';
2503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2504     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('SpineLabelFormat', '<itemcallnumber><copynumber>', '30|10', 'This preference defines the format for the quick spine label printer. Just list the fields you would like to see in the order you would like to see them, surrounded by <>, for example <itemcallnumber>.', 'Textarea')");
2505     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('SpineLabelAutoPrint', '0', '', 'If this setting is turned on, a print dialog will automatically pop up for the quick spine label printer.', 'YesNo')");
2506     SetVersion ($DBversion);
2507     print "Upgrade to $DBversion done (added SpineLabelFormat and SpineLabelAutoPrint sysprefs)\n";
2508 }
2509
2510 $DBversion = '3.01.00.040';
2511 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2512     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('AllowHoldDateInFuture','0','If set a date field is displayed on the Hold screen of the Staff Interface, allowing the hold date to be set in the future.','','YesNo')");
2513     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('OPACAllowHoldDateInFuture','0','If set, along with the AllowHoldDateInFuture system preference, OPAC users can set the date of a hold to be in the future.','','YesNo')");
2514     SetVersion ($DBversion);
2515     print "Upgrade to $DBversion done (AllowHoldDateInFuture and OPACAllowHoldDateInFuture sysprefs)\n";
2516 }
2517
2518 $DBversion = '3.01.00.041';
2519 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2520     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AWSPrivateKey','','See:  http://aws.amazon.com.  Note that this is required after 2009/08/15 in order to retrieve any enhanced content other than book covers from Amazon.','','free')");
2521     SetVersion ($DBversion);
2522     print "Upgrade to $DBversion done (added AWSPrivateKey syspref - note that if you use enhanced content from Amazon, this should be set right away.)\n";
2523 }
2524
2525 $DBversion = '3.01.00.042';
2526 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2527     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACFineNoRenewals','99999','Fine Limit above which user canmot renew books via OPAC','','Integer')");
2528     SetVersion ($DBversion);
2529     print "Upgrade to $DBversion done (added OPACFineNoRenewals syspref)\n";
2530 }
2531
2532 $DBversion = '3.01.00.043';
2533 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2534     $dbh->do('ALTER TABLE items ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2535     $dbh->do('UPDATE items SET permanent_location = location');
2536     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'NewItemsDefaultLocation', '', '', 'If set, all new items will have a location of the given Location Code ( Authorized Value type LOC )', '')");
2537     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'InProcessingToShelvingCart', '0', '', 'If set, when any item with a location code of PROC is ''checked in'', it''s location code will be changed to CART.', 'YesNo')");
2538     $dbh->do("INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'ReturnToShelvingCart', '0', '', 'If set, when any item is ''checked in'', it''s location code will be changed to CART.', 'YesNo')");
2539     SetVersion ($DBversion);
2540     print "Upgrade to $DBversion done (amended Item added NewItemsDefaultLocation, InProcessingToShelvingCart, ReturnToShelvingCart sysprefs)\n";
2541 }
2542
2543 $DBversion = '3.01.00.044';
2544 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2545     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES( 'DisplayClearScreenButton', '0', 'If set to yes, a clear screen button will appear on the circulation page.', 'If set to yes, a clear screen button will appear on the circulation page.', 'YesNo')");
2546     SetVersion ($DBversion);
2547     print "Upgrade to $DBversion done (added DisplayClearScreenButton system preference)\n";
2548 }
2549
2550 $DBversion = '3.01.00.045';
2551 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2552     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('HidePatronName', '0', '', 'If this is switched on, patron''s cardnumber will be shown instead of their name on the holds and catalog screens', 'YesNo')");
2553     SetVersion ($DBversion);
2554     print "Upgrade to $DBversion done (added a preference to hide the patrons name in the staff catalog)\n";
2555 }
2556
2557 $DBversion = "3.01.00.046";
2558 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2559     # update borrowers table
2560     #
2561     $dbh->do("ALTER TABLE borrowers ADD `country` text AFTER zipcode");
2562     $dbh->do("ALTER TABLE borrowers ADD `B_country` text AFTER B_zipcode");
2563     $dbh->do("ALTER TABLE deletedborrowers ADD `country` text AFTER zipcode");
2564     $dbh->do("ALTER TABLE deletedborrowers ADD `B_country` text AFTER B_zipcode");
2565     print "Upgrade to $DBversion done (add country and B_country to borrowers)\n";
2566     SetVersion ($DBversion);
2567 }
2568
2569 $DBversion = '3.01.00.047';
2570 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2571     $dbh->do("ALTER TABLE items MODIFY itemcallnumber varchar(255);");
2572     $dbh->do("ALTER TABLE deleteditems MODIFY itemcallnumber varchar(255);");
2573     $dbh->do("ALTER TABLE tmp_holdsqueue MODIFY itemcallnumber varchar(255);");
2574     SetVersion ($DBversion);
2575     print " Upgrade to $DBversion done (bug 2761: change max length of itemcallnumber to 255 from 30)\n";
2576 }
2577
2578 $DBversion = '3.01.00.048';
2579 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2580     $dbh->do("UPDATE userflags SET flagdesc='View Catalog (Librarian Interface)' WHERE bit=2;");
2581     $dbh->do("UPDATE userflags SET flagdesc='Edit Catalog (Modify bibliographic/holdings data)' WHERE bit=9;");
2582     $dbh->do("UPDATE userflags SET flagdesc='Allow to edit authorities' WHERE bit=14;");
2583     $dbh->do("UPDATE userflags SET flagdesc='Allow to access to the reports module' WHERE bit=16;");
2584     $dbh->do("UPDATE userflags SET flagdesc='Allow to manage serials subscriptions' WHERE bit=15;");
2585     SetVersion ($DBversion);
2586     print " Upgrade to $DBversion done (bug 2611: fix spelling/capitalization in permission flag descriptions)\n";
2587 }
2588
2589 $DBversion = '3.01.00.049';
2590 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2591     $dbh->do("UPDATE permissions SET description = 'Perform inventory (stocktaking) of your catalog' WHERE code = 'inventory';");
2592      SetVersion ($DBversion);
2593     print "Upgrade to $DBversion done (bug 2611: changed catalogue to catalog per the standard)\n";
2594 }
2595
2596 $DBversion = '3.01.00.050';
2597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2598     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACSearchForTitleIn','<li class=\"yuimenuitem\">\n<a target=\"_blank\" class=\"yuimenuitemlabel\" href=\"http://worldcat.org/search?q=TITLE\">Other Libraries (WorldCat)</a></li>\n<li class=\"yuimenuitem\">\n<a class=\"yuimenuitemlabel\" href=\"http://www.scholar.google.com/scholar?q=TITLE\" target=\"_blank\">Other Databases (Google Scholar)</a></li>\n<li class=\"yuimenuitem\">\n<a class=\"yuimenuitemlabel\" href=\"http://www.bookfinder.com/search/?author=AUTHOR&amp;title=TITLE&amp;st=xl&amp;ac=qr\" target=\"_blank\">Online Stores (Bookfinder.com)</a></li>','Enter the HTML that will appear in the ''Search for this title in'' box on the detail page in the OPAC.  Enter TITLE, AUTHOR, or ISBN in place of their respective variables in the URL.  Leave blank to disable ''More Searches'' menu.','70|10','Textarea');");
2599     SetVersion ($DBversion);
2600     print "Upgrade to $DBversion done (bug 1934: Add OPACSearchForTitleIn syspref)\n";
2601 }
2602
2603 $DBversion = '3.01.00.051';
2604 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2605     $dbh->do("UPDATE systempreferences SET explanation='Fine limit above which user cannot renew books via OPAC' WHERE variable='OPACFineNoRenewals';");
2606     $dbh->do("UPDATE systempreferences SET explanation='If set to ON, a clear screen button will appear on the circulation page.' WHERE variable='DisplayClearScreenButton';");
2607     SetVersion ($DBversion);
2608     print "Upgrade to $DBversion done (fixed typos in new sysprefs)\n";
2609 }
2610
2611 $DBversion = '3.01.00.052';
2612 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2613     $dbh->do('ALTER TABLE deleteditems ADD COLUMN permanent_location VARCHAR(80) DEFAULT NULL AFTER location');
2614     SetVersion ($DBversion);
2615     print "Upgrade to $DBversion done (bug 3481: add permanent_location column to deleteditems)\n";
2616 }
2617
2618 $DBversion = '3.01.00.053';
2619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2620     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/labels_upgrade.pl";
2621     system("perl $upgrade_script");
2622     print "Upgrade to $DBversion done (Migrated labels tables and data to new schema.) NOTE: All existing label batches have been assigned to the first branch in the list of branches. This is ONLY true of migrated label batches.\n";
2623     SetVersion ($DBversion);
2624 }
2625
2626 $DBversion = '3.01.00.054';
2627 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2628     $dbh->do("ALTER TABLE borrowers ADD `B_address2` text AFTER B_address");
2629     $dbh->do("ALTER TABLE borrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2630     $dbh->do("ALTER TABLE deletedborrowers ADD `B_address2` text AFTER B_address");
2631     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactcountry` text AFTER altcontactzipcode");
2632     SetVersion ($DBversion);
2633     print "Upgrade to $DBversion done (bug 1600, bug 3454: add altcontactcountry and B_address2 to borrowers and deletedborrowers)\n";
2634 }
2635
2636 $DBversion = '3.01.00.055';
2637 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2638     $dbh->do(qq|UPDATE systempreferences set explanation='Enter the HTML that will appear in the ''Search for this title in'' box on the detail page in the OPAC.  Enter {TITLE}, {AUTHOR}, or {ISBN} in place of their respective variables in the URL. Leave blank to disable ''More Searches'' menu.', value='<li><a  href="http://worldcat.org/search?q={TITLE}" target="_blank">Other Libraries (WorldCat)</a></li>\n<li><a href="http://www.scholar.google.com/scholar?q={TITLE}" target="_blank">Other Databases (Google Scholar)</a></li>\n<li><a href="http://www.bookfinder.com/search/?author={AUTHOR}&amp;title={TITLE}&amp;st=xl&amp;ac=qr" target="_blank">Online Stores (Bookfinder.com)</a></li>' WHERE variable='OPACSearchForTitleIn'|);
2639     SetVersion ($DBversion);
2640     print "Upgrade to $DBversion done (changed OPACSearchForTitleIn per requests in bug 1934)\n";
2641 }
2642
2643 $DBversion = '3.01.00.056';
2644 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2645     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACPatronDetails','1','If OFF the patron details tab in the OPAC is disabled.','','YesNo');");
2646     SetVersion ($DBversion);
2647     print "Upgrade to $DBversion done (Bug 1172 : Add OPACPatronDetails syspref)\n";
2648 }
2649
2650 $DBversion = '3.01.00.057';
2651 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2652     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACFinesTab','1','If OFF the patron fines tab in the OPAC is disabled.','','YesNo');");
2653     SetVersion ($DBversion);
2654     print "Upgrade to $DBversion done (Bug 2576 : Add OPACFinesTab syspref)\n";
2655 }
2656
2657 $DBversion = '3.01.00.058';
2658 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2659     $dbh->do("ALTER TABLE `language_subtag_registry` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2660     $dbh->do("ALTER TABLE `language_rfc4646_to_iso639` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2661     $dbh->do("ALTER TABLE `language_descriptions` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY;");
2662     SetVersion ($DBversion);
2663     print "Upgrade to $DBversion done (Added primary keys to language tables)\n";
2664 }
2665
2666 $DBversion = '3.01.00.059';
2667 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2668     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type)VALUES('DisplayOPACiconsXSLT', '1', '', 'If ON, displays the format, audience, type icons in XSLT MARC21 results and display pages.', 'YesNo')");
2669     SetVersion ($DBversion);
2670     print "Upgrade to $DBversion done (added DisplayOPACiconsXSLT sysprefs)\n";
2671 }
2672
2673 $DBversion = '3.01.00.060';
2674 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2675     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowAllMessageDeletion','0','Allow any Library to delete any message','','YesNo');");
2676     $dbh->do('DROP TABLE IF EXISTS messages');
2677     $dbh->do("CREATE TABLE messages ( `message_id` int(11) NOT NULL auto_increment,
2678         `borrowernumber` int(11) NOT NULL,
2679         `branchcode` varchar(4) default NULL,
2680         `message_type` varchar(1) NOT NULL,
2681         `message` text NOT NULL,
2682         `message_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
2683         PRIMARY KEY (`message_id`)
2684         ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
2685
2686         print "Upgrade to $DBversion done ( Added AllowAllMessageDeletion syspref and messages table )\n";
2687     SetVersion ($DBversion);
2688 }
2689
2690 $DBversion = '3.01.00.061';
2691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2692     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('ShowPatronImageInWebBasedSelfCheck', '0', 'If ON, displays patron image when a patron uses web-based self-checkout', '', 'YesNo')");
2693         print "Upgrade to $DBversion done ( Added ShowPatronImageInWebBasedSelfCheck system preference )\n";
2694     SetVersion ($DBversion);
2695 }
2696
2697 $DBversion = "3.01.00.062";
2698 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2699     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'manage_csv_profiles', 'Manage CSV export profiles')");
2700     $dbh->do(q/
2701         CREATE TABLE `export_format` (
2702           `export_format_id` int(11) NOT NULL auto_increment,
2703           `profile` varchar(255) NOT NULL,
2704           `description` mediumtext NOT NULL,
2705           `marcfields` mediumtext NOT NULL,
2706           PRIMARY KEY  (`export_format_id`)
2707         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Used for CSV export';
2708     /);
2709     print "Upgrade to $DBversion done (added csv export profiles)\n";
2710 }
2711
2712 $DBversion = "3.01.00.063";
2713 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2714     $dbh->do("
2715         CREATE TABLE `fieldmapping` (
2716           `id` int(11) NOT NULL auto_increment,
2717           `field` varchar(255) NOT NULL,
2718           `frameworkcode` char(4) NOT NULL default '',
2719           `fieldcode` char(3) NOT NULL,
2720           `subfieldcode` char(1) NOT NULL,
2721           PRIMARY KEY  (`id`)
2722         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2723              ");
2724     SetVersion ($DBversion);print "Upgrade to $DBversion done (Created table fieldmapping)\n";print "Upgrade to 3.01.00.064 done (Version number skipped: nothing done)\n";
2725 }
2726
2727 $DBversion = '3.01.00.065';
2728 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2729     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `renewalsallowed` smallint(6) NOT NULL default "0" AFTER `issuelength`;');
2730     $sth = $dbh->prepare("SELECT itemtype, renewalsallowed FROM itemtypes");
2731     $sth->execute();
2732
2733     my $sthupd = $dbh->prepare("UPDATE issuingrules SET renewalsallowed = ? WHERE itemtype = ?");
2734
2735     while(my $row = $sth->fetchrow_hashref){
2736         $sthupd->execute($row->{renewalsallowed}, $row->{itemtype});
2737     }
2738
2739     $dbh->do('ALTER TABLE itemtypes DROP COLUMN `renewalsallowed`;');
2740
2741     SetVersion ($DBversion);
2742     print "Upgrade to $DBversion done (Moving allowed renewals from itemtypes to issuingrule)\n";
2743 }
2744
2745 $DBversion = '3.01.00.066';
2746 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2747     $dbh->do('ALTER TABLE issuingrules ADD COLUMN `reservesallowed` smallint(6) NOT NULL default "0" AFTER `renewalsallowed`;');
2748
2749     my $maxreserves = C4::Context->preference('maxreserves');
2750     $sth = $dbh->prepare('UPDATE issuingrules SET reservesallowed = ?;');
2751     $sth->execute($maxreserves);
2752
2753     $dbh->do('DELETE FROM systempreferences WHERE variable = "maxreserves";');
2754
2755     $dbh->do("INSERT INTO systempreferences (variable,value, options, explanation, type) VALUES('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights','Choice')");
2756
2757     SetVersion ($DBversion);
2758     print "Upgrade to $DBversion done (Moving max allowed reserves from system preference to issuingrule)\n";
2759 }
2760
2761 $DBversion = "3.01.00.067";
2762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2763     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchmod', 'Perform batch modification of items')");
2764     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ( 13, 'batchdel', 'Perform batch deletion of items')");
2765     print "Upgrade to $DBversion done (added permissions for batch modification and deletion)\n";
2766     SetVersion ($DBversion);
2767 }
2768
2769 $DBversion = "3.01.00.068";
2770 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2771         $dbh->do("ALTER TABLE issuingrules ADD COLUMN `finedays` int(11) default NULL AFTER `fine` ");
2772         print "Upgrade to $DBversion done (Adding finedays in issuingrules table)\n";
2773     SetVersion ($DBversion);
2774 }
2775
2776
2777 $DBversion = "3.01.00.069";
2778 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2779         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('EnableOpacSearchHistory', '1', '', 'Enable or disable opac search history', 'YesNo')");
2780
2781         my $create = <<SEARCHHIST;
2782 CREATE TABLE IF NOT EXISTS `search_history` (
2783   `userid` int(11) NOT NULL,
2784   `sessionid` varchar(32) NOT NULL,
2785   `query_desc` varchar(255) NOT NULL,
2786   `query_cgi` varchar(255) NOT NULL,
2787   `total` int(11) NOT NULL,
2788   `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
2789   KEY `userid` (`userid`),
2790   KEY `sessionid` (`sessionid`)
2791 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Opac search history results';
2792 SEARCHHIST
2793         $dbh->do($create);
2794
2795         print "Upgrade to $DBversion done (added OPAC search history preference and table)\n";
2796 }
2797
2798 $DBversion = "3.01.00.070";
2799 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2800         $dbh->do("ALTER TABLE authorised_values ADD COLUMN `lib_opac` VARCHAR(80) default NULL AFTER `lib`");
2801         print "Upgrade to $DBversion done (Added a lib_opac field in authorised_values table)\n";
2802 }
2803
2804 $DBversion = "3.01.00.071";
2805 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2806         $dbh->do("ALTER TABLE `subscription` ADD `enddate` date default NULL");
2807         $dbh->do("ALTER TABLE subscriptionhistory CHANGE enddate histenddate DATE default NULL");
2808         print "Upgrade to $DBversion done ( Adding enddate to subscription)\n";
2809 }
2810
2811 # Acquisitions update
2812
2813 $DBversion = "3.01.00.072";
2814 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2815     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacPrivacy', '0', 'if ON, allows patrons to define their privacy rules (reading history)',NULL,'YesNo')");
2816     # create a new syspref for the 'Mr anonymous' patron
2817     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AnonymousPatron', '0', \"Set the identifier (borrowernumber) of the 'Mister anonymous' patron. Used for Suggestion and reading history privacy\",NULL,'')");
2818     # fill AnonymousPatron with AnonymousSuggestion value (copy)
2819     my $sth=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='AnonSuggestions'");
2820     $sth->execute;
2821     my ($value) = $sth->fetchrow() || 0;
2822     $dbh->do("UPDATE systempreferences SET value='$value' WHERE variable='AnonymousPatron'");
2823     # set AnonymousSuggestion do YesNo
2824     # 1st, set the value (1/True if it had a borrowernumber)
2825     $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='AnonSuggestions' AND value>0");
2826     # 2nd, change the type to Choice
2827     $dbh->do("UPDATE systempreferences SET type='YesNo' WHERE variable='AnonSuggestions'");
2828         # borrower reading record privacy : 0 : forever, 1 : laws, 2 : don't keep at all
2829     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
2830     print "Upgrade to $DBversion done (add new syspref and column in borrowers)\n";
2831     SetVersion ($DBversion);
2832 }
2833
2834 $DBversion = '3.01.00.073';
2835 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2836     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2837     $dbh->do(<<'END_SQL');
2838 CREATE TABLE IF NOT EXISTS `aqcontract` (
2839   `contractnumber` int(11) NOT NULL auto_increment,
2840   `contractstartdate` date default NULL,
2841   `contractenddate` date default NULL,
2842   `contractname` varchar(50) default NULL,
2843   `contractdescription` mediumtext,
2844   `booksellerid` int(11) not NULL,
2845     PRIMARY KEY  (`contractnumber`),
2846         CONSTRAINT `booksellerid_fk1` FOREIGN KEY (`booksellerid`)
2847         REFERENCES `aqbooksellers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
2848 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
2849 END_SQL
2850     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2851     print "Upgrade to $DBversion done (adding aqcontract table)\n";
2852     SetVersion ($DBversion);
2853 }
2854
2855 $DBversion = '3.01.00.074';
2856 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2857     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `basketname` varchar(50) default NULL AFTER `basketno`");
2858     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `note` mediumtext AFTER `basketname`");
2859     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `booksellernote` mediumtext AFTER `note`");
2860     $dbh->do("ALTER TABLE `aqbasket` ADD COLUMN `contractnumber` int(11) AFTER `booksellernote`");
2861     $dbh->do("ALTER TABLE `aqbasket` ADD FOREIGN KEY (`contractnumber`) REFERENCES `aqcontract` (`contractnumber`)");
2862     print "Upgrade to $DBversion done (edit aqbasket table done)\n";
2863     SetVersion ($DBversion);
2864 }
2865
2866 $DBversion = '3.01.00.075';
2867 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2868     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `uncertainprice` tinyint(1)");
2869
2870     print "Upgrade to $DBversion done (adding uncertainprices)\n";
2871     SetVersion ($DBversion);
2872 }
2873
2874 $DBversion = '3.01.00.076';
2875 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2876     $dbh->do('SET FOREIGN_KEY_CHECKS=0 ');
2877     $dbh->do("CREATE TABLE IF NOT EXISTS `aqbasketgroups` (
2878                          `id` int(11) NOT NULL auto_increment,
2879                          `name` varchar(50) default NULL,
2880                          `closed` tinyint(1) default NULL,
2881                          `booksellerid` int(11) NOT NULL,
2882                          PRIMARY KEY (`id`),
2883                          KEY `booksellerid` (`booksellerid`),
2884                          CONSTRAINT `aqbasketgroups_ibfk_1` FOREIGN KEY (`booksellerid`) REFERENCES `aqbooksellers` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
2885                          ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
2886     $dbh->do("ALTER TABLE aqbasket ADD COLUMN `basketgroupid` int(11)");
2887     $dbh->do("ALTER TABLE aqbasket ADD FOREIGN KEY (`basketgroupid`) REFERENCES `aqbasketgroups` (`id`) ON UPDATE CASCADE ON DELETE SET NULL");
2888     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('pdfformat','pdfformat::layout2pages','Controls what script is used for printing (basketgroups)','','free')");
2889     $dbh->do('SET FOREIGN_KEY_CHECKS=1 ');
2890     print "Upgrade to $DBversion done (adding basketgroups)\n";
2891     SetVersion ($DBversion);
2892 }
2893 $DBversion = '3.01.00.077';
2894 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
2895
2896     $dbh->do("SET FOREIGN_KEY_CHECKS=0 ");
2897     # create a mapping table holding the info we need to match orders to budgets
2898     $dbh->do('DROP TABLE IF EXISTS fundmapping');
2899     $dbh->do(
2900         q|CREATE TABLE fundmapping AS
2901         SELECT aqorderbreakdown.ordernumber, branchcode, bookfundid, budgetdate, entrydate
2902         FROM aqorderbreakdown JOIN aqorders ON aqorderbreakdown.ordernumber = aqorders.ordernumber|);
2903     # match the new type of the corresponding field
2904     $dbh->do('ALTER TABLE fundmapping modify column bookfundid varchar(30)');
2905     # System did not ensure budgetdate was valid historically
2906     sanitize_zero_date('fundmapping', 'budgetdate');
2907     $dbh->do(q|UPDATE fundmapping SET budgetdate = entrydate WHERE budgetdate IS NULL|);
2908     # We save the map in fundmapping in case you need later processing
2909     $dbh->do(q|ALTER TABLE fundmapping add column aqbudgetid integer|);
2910     # these can speed processing up
2911     $dbh->do(q|CREATE INDEX fundmaporder ON fundmapping (ordernumber)|);
2912     $dbh->do(q|CREATE INDEX fundmapid ON fundmapping (bookfundid)|);
2913
2914     $dbh->do("DROP TABLE IF EXISTS `aqbudgetperiods` ");
2915
2916     $dbh->do(qq|
2917                     CREATE TABLE `aqbudgetperiods` (
2918                     `budget_period_id` int(11) NOT NULL auto_increment,
2919                     `budget_period_startdate` date NOT NULL,
2920                     `budget_period_enddate` date NOT NULL,
2921                     `budget_period_active` tinyint(1) default '0',
2922                     `budget_period_description` mediumtext,
2923                     `budget_period_locked` tinyint(1) default NULL,
2924                     `sort1_authcat` varchar(10) default NULL,
2925                     `sort2_authcat` varchar(10) default NULL,
2926                     PRIMARY KEY  (`budget_period_id`)
2927                     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 |);
2928
2929    $dbh->do(<<ADDPERIODS);
2930 INSERT INTO aqbudgetperiods (budget_period_startdate,budget_period_enddate,budget_period_active,budget_period_description,budget_period_locked)
2931 SELECT DISTINCT startdate, enddate, NOW() BETWEEN startdate and enddate, concat(startdate," ",enddate),NOT NOW() BETWEEN startdate AND enddate from aqbudget
2932 ADDPERIODS
2933 # SORRY , NO AQBUDGET/AQBOOKFUND -> AQBUDGETS IMPORT JUST YET,
2934 # BUT A NEW CLEAN AQBUDGETS TABLE CREATE FOR NOW..
2935 # DROP TABLE IF EXISTS `aqbudget`;
2936 #CREATE TABLE `aqbudget` (
2937 #  `bookfundid` varchar(10) NOT NULL default ',
2938 #    `startdate` date NOT NULL default 0,
2939 #         `enddate` date default NULL,
2940 #           `budgetamount` decimal(13,2) default NULL,
2941 #                 `aqbudgetid` tinyint(4) NOT NULL auto_increment,
2942 #                   `branchcode` varchar(10) default NULL,
2943     DropAllForeignKeys('aqbudget');
2944   #$dbh->do("drop table aqbudget;");
2945
2946
2947     my $maxbudgetid = $dbh->selectcol_arrayref(<<IDsBUDGET);
2948 SELECT MAX(aqbudgetid) from aqbudget
2949 IDsBUDGET
2950
2951 $$maxbudgetid[0] = 0 if !$$maxbudgetid[0];
2952
2953     $dbh->do(<<BUDGETAUTOINCREMENT);
2954 ALTER TABLE aqbudget AUTO_INCREMENT=$$maxbudgetid[0]
2955 BUDGETAUTOINCREMENT
2956
2957     $dbh->do(<<BUDGETNAME);
2958 ALTER TABLE aqbudget RENAME `aqbudgets`
2959 BUDGETNAME
2960
2961     $dbh->do(<<BUDGETS);
2962 ALTER TABLE `aqbudgets`
2963    CHANGE  COLUMN aqbudgetid `budget_id` int(11) NOT NULL AUTO_INCREMENT,
2964    CHANGE  COLUMN branchcode `budget_branchcode` varchar(10) default NULL,
2965    CHANGE  COLUMN budgetamount `budget_amount` decimal(28,6) NOT NULL default '0.00',
2966    CHANGE  COLUMN bookfundid   `budget_code` varchar(30) default NULL,
2967    ADD     COLUMN `budget_parent_id` int(11) default NULL,
2968    ADD     COLUMN `budget_name` varchar(80) default NULL,
2969    ADD     COLUMN `budget_encumb` decimal(28,6) default '0.00',
2970    ADD     COLUMN `budget_expend` decimal(28,6) default '0.00',
2971    ADD     COLUMN `budget_notes` mediumtext,
2972    ADD     COLUMN `budget_description` mediumtext,
2973    ADD     COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
2974    ADD     COLUMN `budget_amount_sublevel`  decimal(28,6) AFTER `budget_amount`,
2975    ADD     COLUMN `budget_period_id` int(11) default NULL,
2976    ADD     COLUMN `sort1_authcat` varchar(80) default NULL,
2977    ADD     COLUMN `sort2_authcat` varchar(80) default NULL,
2978    ADD     COLUMN `budget_owner_id` int(11) default NULL,
2979    ADD     COLUMN `budget_permission` int(1) default '0';
2980 BUDGETS
2981
2982     $dbh->do(<<BUDGETCONSTRAINTS);
2983 ALTER TABLE `aqbudgets`
2984    ADD CONSTRAINT `aqbudgets_ifbk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON DELETE CASCADE ON UPDATE CASCADE
2985 BUDGETCONSTRAINTS
2986 #    $dbh->do(<<BUDGETPKDROP);
2987 #ALTER TABLE `aqbudgets`
2988 #   DROP PRIMARY KEY
2989 #BUDGETPKDROP
2990 #    $dbh->do(<<BUDGETPKADD);
2991 #ALTER TABLE `aqbudgets`
2992 #   ADD PRIMARY KEY budget_id
2993 #BUDGETPKADD
2994
2995
2996         my $query_period= $dbh->prepare(qq|SELECT budget_period_id from aqbudgetperiods where budget_period_startdate=? and budget_period_enddate=?|);
2997         my $query_bookfund= $dbh->prepare(qq|SELECT * from aqbookfund where bookfundid=?|);
2998         my $selectbudgets=$dbh->prepare(qq|SELECT * from aqbudgets|);
2999         my $updatebudgets=$dbh->prepare(qq|UPDATE aqbudgets SET budget_period_id= ? , budget_name=?, budget_branchcode=? where budget_id=?|);
3000         $selectbudgets->execute;
3001         while (my $databudget=$selectbudgets->fetchrow_hashref){
3002                 $query_period->execute ($$databudget{startdate},$$databudget{enddate});
3003                 my ($budgetperiodid)=$query_period->fetchrow;
3004                 $query_bookfund->execute ($$databudget{budget_code});
3005                 my $databf=$query_bookfund->fetchrow_hashref;
3006                 my $branchcode=$$databudget{budget_branchcode}||$$databf{branchcode};
3007                 $updatebudgets->execute($budgetperiodid,$$databf{bookfundname},$branchcode,$$databudget{budget_id});
3008         }
3009     $dbh->do(<<BUDGETDROPDATES);
3010 ALTER TABLE `aqbudgets`
3011    DROP startdate,
3012    DROP enddate
3013 BUDGETDROPDATES
3014
3015
3016     $dbh->do("DROP TABLE IF EXISTS `aqbudgets_planning` ");
3017     $dbh->do("CREATE TABLE  `aqbudgets_planning` (
3018                     `plan_id` int(11) NOT NULL auto_increment,
3019                     `budget_id` int(11) NOT NULL,
3020                     `budget_period_id` int(11) NOT NULL,
3021                     `estimated_amount` decimal(28,6) default NULL,
3022                     `authcat` varchar(30) NOT NULL,
3023                     `authvalue` varchar(30) NOT NULL,
3024                                         `display` tinyint(1) DEFAULT 1,
3025                         PRIMARY KEY  (`plan_id`),
3026                         CONSTRAINT `aqbudgets_planning_ifbk_1` FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON DELETE CASCADE ON UPDATE CASCADE
3027                         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
3028
3029     $dbh->do("ALTER TABLE `aqorders`
3030                     ADD COLUMN `budget_id` tinyint(4) NOT NULL,
3031                     ADD COLUMN `budgetgroup_id` int(11) NOT NULL,
3032                     ADD COLUMN  `sort1_authcat` varchar(10) default NULL,
3033                     ADD COLUMN  `sort2_authcat` varchar(10) default NULL" );
3034                 # We need to map the orders to the budgets
3035                 # For Historic reasons this is more complex than it should be on occasions
3036                 my $budg_arr = $dbh->selectall_arrayref(
3037                     q|SELECT aqbudgets.budget_id, aqbudgets.budget_code, aqbudgetperiods.budget_period_startdate,
3038                     aqbudgetperiods.budget_period_enddate
3039                     FROM aqbudgets JOIN aqbudgetperiods ON aqbudgets.budget_period_id = aqbudgetperiods.budget_period_id
3040                     ORDER BY budget_code, budget_period_startdate|, { Slice => {} });
3041                 # We arbitarily order on start date, this means if you have overlapping periods the order will be
3042                 # linked to the latest matching budget YMMV
3043                 my $b_sth = $dbh->prepare(
3044                     'UPDATE fundmapping set aqbudgetid = ? where bookfundid =? AND budgetdate >= ? AND budgetdate <= ?');
3045                 for my $b ( @{$budg_arr}) {
3046                     $b_sth->execute($b->{budget_id}, $b->{budget_code}, $b->{budget_period_startdate}, $b->{budget_period_enddate});
3047                 }
3048                 # move the budgetids to aqorders
3049                 $dbh->do(q|UPDATE aqorders, fundmapping SET aqorders.budget_id = fundmapping.aqbudgetid
3050                     WHERE aqorders.ordernumber = fundmapping.ordernumber AND fundmapping.aqbudgetid IS NOT NULL|);
3051                 # NB fundmapping is left as an accontants trail also if you have budgetids that werent set
3052                 # you can decide what to do with them
3053
3054      $dbh->do(
3055          q|UPDATE aqorders, aqbudgets SET aqorders.budgetgroup_id = aqbudgets.budget_period_id
3056          WHERE aqorders.budget_id = aqbudgets.budget_id|);
3057                 # cannot do until aqorderbreakdown removed
3058 #    $dbh->do("DROP TABLE aqbookfund ");
3059 #    $dbh->do("ALTER TABLE aqorders  ADD FOREIGN KEY (`budget_id`) REFERENCES `aqbudgets` (`budget_id`) ON UPDATE CASCADE  " ); ????
3060     $dbh->do("SET FOREIGN_KEY_CHECKS=1 ");
3061
3062     print "Upgrade to $DBversion done (Adding new aqbudgetperiods, aqbudgets and aqbudget_planning tables  )\n";
3063     SetVersion ($DBversion);
3064 }
3065
3066
3067
3068 $DBversion = '3.01.00.078';
3069 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3070     $dbh->do("ALTER TABLE aqbudgetperiods ADD COLUMN budget_period_total decimal(28,6)");
3071     print "Upgrade to $DBversion done (adds 'budget_period_total' column to aqbudgetperiods table)\n";
3072     SetVersion($DBversion);
3073 }
3074
3075
3076 $DBversion = '3.01.00.079';
3077 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3078     $dbh->do("ALTER TABLE currency ADD COLUMN active  tinyint(1)");
3079
3080     print "Upgrade to $DBversion done (adds 'active' column to currencies table)\n";
3081     SetVersion($DBversion);
3082 }
3083
3084 $DBversion = '3.01.00.080';
3085 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3086     $dbh->do(<<BUDG_PERM );
3087 INSERT INTO permissions (module_bit, code, description) VALUES
3088             (11, 'vendors_manage', 'Manage vendors'),
3089             (11, 'contracts_manage', 'Manage contracts'),
3090             (11, 'period_manage', 'Manage periods'),
3091             (11, 'budget_manage', 'Manage budgets'),
3092             (11, 'budget_modify', "Modify budget (can't create lines but can modify existing ones)"),
3093             (11, 'planning_manage', 'Manage budget plannings'),
3094             (11, 'order_manage', 'Manage orders & basket'),
3095             (11, 'group_manage', 'Manage orders & basketgroups'),
3096             (11, 'order_receive', 'Manage orders & basket'),
3097             (11, 'budget_add_del', "Add and delete budgets (but can't modify budgets)");
3098 BUDG_PERM
3099
3100     print "Upgrade to $DBversion done (adds permissions for the acquisitions module)\n";
3101     SetVersion($DBversion);
3102 }
3103
3104
3105 $DBversion = '3.01.00.081';
3106 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3107     $dbh->do("ALTER TABLE aqbooksellers ADD COLUMN `gstrate` decimal(6,4) default NULL");
3108     if (my $gist=C4::Context->preference("gist")){
3109                 my $sql=$dbh->prepare("UPDATE aqbooksellers set `gstrate`=? ");
3110         $sql->execute($gist) ;
3111         }
3112     print "Upgrade to $DBversion done (added per-supplier gstrate setting)\n";
3113     SetVersion($DBversion);
3114 }
3115
3116 $DBversion = "3.01.00.082";
3117 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3118     if (C4::Context->preference("opaclanguages") eq "fr") {
3119         $dbh->do(qq#INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AcqCreateItem','ordering',"Définit quand l'exemplaire est créé : à la commande, à la livraison, au catalogage",'ordering|receiving|cataloguing','Choice')#);
3120     } else {
3121         $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AcqCreateItem','ordering','Define when the item is created : when ordering, when receiving, or in cataloguing module','ordering|receiving|cataloguing','Choice')");
3122     }
3123     print "Upgrade to $DBversion done (adding ReservesNeedReturns systempref, in circulation)\n";
3124     SetVersion ($DBversion);
3125 }
3126
3127 $DBversion = "3.01.00.083";
3128 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3129     $dbh->do(qq|
3130  CREATE TABLE `aqorders_items` (
3131   `ordernumber` int(11) NOT NULL,
3132   `itemnumber` int(11) NOT NULL,
3133   `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
3134   PRIMARY KEY  (`itemnumber`),
3135   KEY `ordernumber` (`ordernumber`)
3136 ) ENGINE=InnoDB DEFAULT CHARSET=utf8   |
3137     );
3138
3139     $dbh->do(qq| DROP TABLE aqorderbreakdown |);
3140     $dbh->do('DROP TABLE aqbookfund');
3141     print "Upgrade to $DBversion done (New aqorders_items table for acqui)\n";
3142     SetVersion ($DBversion);
3143 }
3144
3145 $DBversion = "3.01.00.084";
3146 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3147     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('CurrencyFormat','US','US|FR','Determines the display format of currencies. eg: ''36000'' is displayed as ''360 000,00''  in ''FR'' or 360,000.00''  in ''US''.','Choice')  #);
3148
3149     print "Upgrade to $DBversion done (CurrencyFormat syspref added)\n";
3150     SetVersion ($DBversion);
3151 }
3152
3153 $DBversion = "3.01.00.085";
3154 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3155     $dbh->do("ALTER table aqorders drop column title");
3156     $dbh->do("ALTER TABLE `aqorders` CHANGE `budget_id` `budget_id` INT( 11 ) NOT NULL");
3157     print "Upgrade to $DBversion done update budget_id size that should not be a tinyint\n";
3158     SetVersion ($DBversion);
3159 }
3160
3161 $DBversion = "3.01.00.086";
3162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3163     $dbh->do(<<SUGGESTIONS);
3164 ALTER table suggestions
3165     ADD budgetid INT(11),
3166     ADD branchcode VARCHAR(10) default NULL,
3167     ADD acceptedby INT(11) default NULL,
3168     ADD accepteddate date default NULL,
3169     ADD suggesteddate date default NULL,
3170     ADD manageddate date default NULL,
3171     ADD rejectedby INT(11) default NULL,
3172     ADD rejecteddate date default NULL,
3173     ADD collectiontitle text default NULL,
3174     ADD itemtype VARCHAR(30) default NULL
3175     ;
3176 SUGGESTIONS
3177     print "Upgrade to $DBversion done (Suggestions)\n";
3178     SetVersion ($DBversion);
3179 }
3180
3181 $DBversion = "3.01.00.087";
3182 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3183     $dbh->do("ALTER table aqbudgets drop column budget_amount_sublevel;");
3184     print "Upgrade to $DBversion done (Drop column budget_amount_sublevel from aqbudgets)\n";
3185     SetVersion ($DBversion);
3186 }
3187
3188 $DBversion = "3.01.00.088";
3189 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3190     $dbh->do(  qq# INSERT INTO `systempreferences` VALUES ('intranetbookbag','1','','If ON, enables display of Cart feature in the intranet','YesNo')  #);
3191
3192     print "Upgrade to $DBversion done (intranetbookbag syspref added)\n";
3193     SetVersion ($DBversion);
3194 }
3195
3196 $DBversion = "3.01.00.090";
3197 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3198 $dbh->do("
3199        INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3200                 (16, 'execute_reports', 'Execute SQL reports'),
3201                 (16, 'create_reports', 'Create SQL Reports')
3202         ");
3203
3204     print "Upgrade to $DBversion done (granular permissions for guided reports added)\n";
3205     SetVersion ($DBversion);
3206 }
3207
3208 $DBversion = "3.01.00.091";
3209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3210 $dbh->do("
3211         UPDATE `systempreferences` SET `options` = 'holdings|serialcollection|subscriptions'
3212         WHERE `systempreferences`.`variable` = 'opacSerialDefaultTab' LIMIT 1
3213         ");
3214
3215     print "Upgrade to $DBversion done (opac-detail default tag updated)\n";
3216     SetVersion ($DBversion);
3217 }
3218
3219 $DBversion = "3.01.00.092";
3220 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3221     if (C4::Context->preference("opaclanguages") =~ /fr/) {
3222         $dbh->do(qq{
3223 INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('RoutingListAddReserves','1','Si activé, des reservations sont automatiquement créées pour chaque lecteur de la liste de circulation d''un numéro de périodique','','YesNo');
3224         });
3225         }else{
3226         $dbh->do(qq{
3227 INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('RoutingListAddReserves','1','If ON the patrons on routing lists are automatically added to holds on the issue.','','YesNo');
3228         });
3229         }
3230     print "Upgrade to $DBversion done (Added RoutingListAddReserves syspref)\n";
3231     SetVersion ($DBversion);
3232 }
3233
3234 $DBversion = "3.01.00.093";
3235 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3236         $dbh->do(qq{
3237         ALTER TABLE biblioitems ADD INDEX issn_idx (issn);
3238         });
3239     print "Upgrade to $DBversion done (added index to ISSN)\n";
3240     SetVersion ($DBversion);
3241 }
3242
3243 $DBversion = "3.01.00.094";
3244 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3245         $dbh->do(qq{
3246         ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10) default NULL, ADD deliverycomment VARCHAR(255) default NULL;
3247         });
3248
3249     print "Upgrade to $DBversion done (adding deliveryplace deliverycomment to basketgroups)\n";
3250     SetVersion ($DBversion);
3251 }
3252
3253 $DBversion = "3.01.00.095";
3254 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3255         $dbh->do(qq{
3256         ALTER TABLE items ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number";
3257         });
3258         $dbh->do(qq{
3259         ALTER TABLE items ADD UNIQUE INDEX itemsstocknumberidx (stocknumber);
3260         });
3261         $dbh->do(qq{
3262         ALTER TABLE deleteditems ADD stocknumber VARCHAR(32) DEFAULT NULL COMMENT "stores the inventory number of deleted items";
3263         });
3264         $dbh->do(qq{
3265         ALTER TABLE deleteditems ADD UNIQUE INDEX deleteditemsstocknumberidx (stocknumber);
3266         });
3267         if (C4::Context->preference('marcflavour') eq 'UNIMARC'){
3268                 $dbh->do(qq{
3269         INSERT IGNORE INTO marc_subfield_structure (frameworkcode,tagfield, tagsubfield, tab, repeatable, mandatory,kohafield)
3270         SELECT DISTINCT (frameworkcode),995,"j",10,0,0,"items.stocknumber" from biblio_framework ;
3271                 });
3272                 #Previously, copynumber was used as stocknumber
3273                 $dbh->do(qq{
3274         UPDATE items set stocknumber=copynumber;
3275                 });
3276                 $dbh->do(qq{
3277         UPDATE items set copynumber=NULL;
3278                 });
3279         }
3280     print "Upgrade to $DBversion done (stocknumber field added)\n";
3281     SetVersion ($DBversion);
3282 }
3283
3284 $DBversion = "3.01.00.096";
3285 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3286     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPdfTemplate','','Uploads a PDF template to use for printing baskets','NULL','Upload')");
3287     $dbh->do("UPDATE systempreferences SET variable='OrderPdfFormat' WHERE variable='pdfformat'");
3288     print "Upgrade to $DBversion done (PDF orders system preferences added and updated)\n";
3289     SetVersion ($DBversion);
3290 }
3291
3292 $DBversion = "3.01.00.097";
3293 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3294         $dbh->do(qq{
3295         ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10) NOT NULL AFTER deliverycomment;
3296         });
3297
3298     print "Upgrade to $DBversion done (Adding billingplace to aqbasketgroups)\n";
3299     SetVersion ($DBversion);
3300 }
3301
3302 $DBversion = "3.01.00.098";
3303 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3304         $dbh->do(qq{
3305         ALTER TABLE auth_subfield_structure MODIFY frameworkcode VARCHAR(10) NULL;
3306         });
3307
3308     print "Upgrade to $DBversion done (changing frameworkcode length in auth_subfield_structure)\n";
3309     SetVersion ($DBversion);
3310 }
3311
3312 $DBversion = "3.01.00.099";
3313 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3314         $dbh->do(qq{
3315                 INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3316                 (9, 'edit_catalogue', 'Edit catalogue'),
3317                 (9, 'fast_cataloging', 'Fast cataloging')
3318         });
3319
3320     print "Upgrade to $DBversion done (granular permissions for cataloging added)\n";
3321     SetVersion ($DBversion);
3322 }
3323
3324 $DBversion = "3.01.00.100";
3325 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3326         $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('casAuthentication', '0', '', 'Enable or disable CAS authentication', 'YesNo'), ('casLogout', '1', '', 'Does a logout from Koha should also log out of CAS ?', 'YesNo'), ('casServerUrl', 'https://localhost:8443/cas', '', 'URL of the cas server', 'Free')");
3327         print "Upgrade to $DBversion done (added CAS authentication system preferences)\n";
3328     SetVersion ($DBversion);
3329 }
3330
3331 $DBversion = "3.01.00.101";
3332 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3333         $dbh->do(
3334         "INSERT INTO systempreferences
3335            (variable, value, options, explanation, type)
3336          VALUES (
3337             'OverdueNoticeBcc', '', '',
3338             'Email address to Bcc outgoing notices sent by email',
3339             'free')
3340          ");
3341         print "Upgrade to $DBversion done (added OverdueNoticeBcc system preferences)\n";
3342     SetVersion ($DBversion);
3343 }
3344 $DBversion = "3.01.00.102";
3345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3346     $dbh->do(
3347     "UPDATE permissions set description = 'Edit catalog (Modify bibliographic/holdings data)' where module_bit = 9 and code = 'edit_catalogue'"
3348     );
3349         print "Upgrade to $DBversion done (fixed spelling error in edit_catalogue permission)\n";
3350     SetVersion ($DBversion);
3351 }
3352
3353 $DBversion = "3.01.00.103";
3354 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3355         $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES (13, 'moderate_tags', 'Moderate patron tags')");
3356         print "Upgrade to $DBversion done (adding patron permissions for tags tool)\n";
3357     SetVersion ($DBversion);
3358 }
3359
3360 $DBversion = "3.01.00.104";
3361 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3362
3363     my ($maninv_count, $borrnotes_count);
3364     eval { $maninv_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='MANUAL_INV'"); };
3365     if ($maninv_count == 0) {
3366         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('MANUAL_INV','Copier Fees','.25')");
3367     }
3368     eval { $borrnotes_count = $dbh->do("SELECT 1 FROM authorised_values WHERE category='BOR_NOTES'"); };
3369     if ($borrnotes_count == 0) {
3370         $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('BOR_NOTES','ADDR','Address Notes')");
3371     }
3372
3373     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','CART','Book Cart')");
3374     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('LOC','PROC','Processing Center')");
3375
3376         print "Upgrade to $DBversion done ( add defaults to authorized values for MANUAL_INV and BOR_NOTES and add new default LOC authorized values for shelf to cart processing )\n";
3377         SetVersion ($DBversion);
3378 }
3379
3380
3381 $DBversion = "3.01.00.105";
3382 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3383     $dbh->do("
3384       CREATE TABLE `collections` (
3385         `colId` int(11) NOT NULL auto_increment,
3386         `colTitle` varchar(100) NOT NULL default '',
3387         `colDesc` text NOT NULL,
3388         `colBranchcode` varchar(4) default NULL COMMENT 'branchcode for branch where item should be held.',
3389         PRIMARY KEY  (`colId`)
3390       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3391     ");
3392
3393     $dbh->do("
3394       CREATE TABLE `collections_tracking` (
3395         `ctId` int(11) NOT NULL auto_increment,
3396         `colId` int(11) NOT NULL default '0' COMMENT 'collections.colId',
3397         `itemnumber` int(11) NOT NULL default '0' COMMENT 'items.itemnumber',
3398         PRIMARY KEY  (`ctId`)
3399       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3400     ");
3401     $dbh->do("
3402         INSERT INTO permissions (module_bit, code, description)
3403         VALUES ( 13, 'rotating_collections', 'Manage Rotating collections')" );
3404         print "Upgrade to $DBversion done (added collection and collection_tracking tables for rotating collections functionality)\n";
3405     SetVersion ($DBversion);
3406 }
3407 $DBversion = "3.01.00.106";
3408 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3409         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ( 'OpacAddMastheadLibraryPulldown', '0', '', 'Adds a pulldown menu to select the library to search on the opac masthead.', 'YesNo' )");
3410         print "Upgrade to $DBversion done (added OpacAddMastheadLibraryPulldown system preferences)\n";
3411     SetVersion ($DBversion);
3412 }
3413
3414 $DBversion = '3.01.00.107';
3415 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3416     my $upgrade_script = C4::Context->config("intranetdir") . "/installer/data/mysql/patroncards_upgrade.pl";
3417     system("perl $upgrade_script");
3418     print "Upgrade to $DBversion done (Migrated labels and patroncards tables and data to new schema.)\n";
3419     SetVersion ($DBversion);
3420 }
3421
3422 $DBversion = '3.01.00.108';
3423 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3424         $dbh->do(qq{
3425     ALTER TABLE `export_format` ADD `csv_separator` VARCHAR( 2 ) NOT NULL AFTER `marcfields` ,
3426     ADD `field_separator` VARCHAR( 2 ) NOT NULL AFTER `csv_separator` ,
3427     ADD `subfield_separator` VARCHAR( 2 ) NOT NULL AFTER `field_separator`
3428     });
3429         print "Upgrade to $DBversion done (added separators for csv export)\n";
3430     SetVersion ($DBversion);
3431 }
3432
3433 $DBversion = "3.01.00.109";
3434 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3435         $dbh->do(qq{
3436         ALTER TABLE `export_format` ADD `encoding` VARCHAR(255) NOT NULL AFTER `subfield_separator`
3437         });
3438         print "Upgrade to $DBversion done (added encoding for csv export)\n";
3439     SetVersion ($DBversion);
3440 }
3441
3442 $DBversion = '3.01.00.110';
3443 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3444     $dbh->do('ALTER TABLE `categories` ADD COLUMN `enrolmentperioddate` DATE NULL DEFAULT NULL AFTER `enrolmentperiod`');
3445     print "Upgrade to $DBversion done (Add enrolment period date support)\n";
3446     SetVersion ($DBversion);
3447 }
3448
3449 $DBversion = '3.01.00.111';
3450 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3451     print "Upgrade to $DBversion done (mark DBrev for 3.2-alpha release)\n";
3452     SetVersion ($DBversion);
3453 }
3454
3455 $DBversion = '3.01.00.112';
3456 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3457         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('SpineLabelShowPrintOnBibDetails', '0', '', 'If turned on, a \"Print Label\" link will appear for each item on the bib details page in the staff interface.', 'YesNo');");
3458         print "Upgrade to $DBversion done ( added Show Spine Label Printer on Bib Items Details preferences )\n";
3459     SetVersion ($DBversion);
3460 }
3461
3462 $DBversion = '3.01.00.113';
3463 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3464     my $value = C4::Context->preference("XSLTResultsDisplay");
3465     $dbh->do(
3466         "INSERT INTO systempreferences (variable,value,type)
3467          VALUES('OPACXSLTResultsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3468     $value = C4::Context->preference("XSLTDetailsDisplay");
3469     $dbh->do(
3470         "INSERT INTO systempreferences (variable,value,type)
3471          VALUES('OPACXSLTDetailsDisplay',?,'YesNo')", {}, $value ? 1 : 0);
3472     print "Upgrade to $DBversion done (added two new syspref: OPACXSLTResultsDisplay and OPACXSLTDetailDisplay). You may have to go in Admin > System preference to tweak XSLT related syspref both in OPAC and Search tabs.\n";
3473     SetVersion ($DBversion);
3474 }
3475
3476 $DBversion = '3.01.00.114';
3477 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3478     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type)VALUES('AutoSelfCheckAllowed', '0', 'For corporate and special libraries which want web-based self-check available from any PC without the need for a manual staff login. Most libraries will want to leave this turned off. If on, requires self-check ID and password to be entered in AutoSelfCheckID and AutoSelfCheckPass sysprefs.', '', 'YesNo')");
3479     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AutoSelfCheckID','','Staff ID with circulation rights to be used for automatic web-based self-check. Only applies if AutoSelfCheckAllowed syspref is turned on.','','free')");
3480     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AutoSelfCheckPass','','Password to be used for automatic web-based self-check. Only applies if AutoSelfCheckAllowed syspref is turned on.','','free')");
3481         print "Upgrade to $DBversion done ( Added AutoSelfCheckAllowed, AutoSelfCheckID, and AutoShelfCheckPass system preference )\n";
3482     SetVersion ($DBversion);
3483 }
3484
3485 $DBversion = '3.01.00.115';
3486 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3487     $dbh->do('UPDATE aqorders SET quantityreceived = 0 WHERE quantityreceived IS NULL');
3488     $dbh->do('ALTER TABLE aqorders MODIFY COLUMN quantityreceived smallint(6) NOT NULL DEFAULT 0');
3489         print "Upgrade to $DBversion done ( Default aqorders.quantityreceived to 0 )\n";
3490     SetVersion ($DBversion);
3491 }
3492
3493 $DBversion = '3.01.00.116';
3494 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3495         if (C4::Context->preference('OrderPdfFormat') eq 'pdfformat::example'){
3496                 $dbh->do("UPDATE `systempreferences` set value='pdfformat::layout2pages' WHERE variable='OrderPdfFormat'");
3497         }
3498         print "Upgrade to $DBversion done (corrected default OrderPdfFormat value if still set wrong )\n";
3499     SetVersion ($DBversion);
3500 }
3501
3502 $DBversion = '3.01.00.117';
3503 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3504     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'por' WHERE rfc4646_subtag='pt' ");
3505     print "Upgrade to $DBversion done (corrected ISO 639-2 language code for Portuguese)\n";
3506     SetVersion ($DBversion);
3507 }
3508
3509 $DBversion = '3.01.00.118';
3510 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3511     my ($count) = $dbh->selectrow_array("SELECT count(*) FROM information_schema.columns
3512                                          WHERE table_name = 'aqbudgets_planning'
3513                                          AND column_name = 'display'");
3514     if ($count < 1) {
3515         $dbh->do("ALTER TABLE aqbudgets_planning ADD COLUMN display tinyint(1) DEFAULT 1");
3516     }
3517     print "Upgrade to $DBversion done (bug 4203: add display column to aqbudgets_planning if missing)\n";
3518     SetVersion ($DBversion);
3519 }
3520
3521 $DBversion = '3.01.00.119';
3522 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3523     eval{require Locale::Currency::Format};
3524     if (!$@) {
3525         print "Upgrade to $DBversion done (Locale::Currency::Format installed.)\n";
3526         SetVersion ($DBversion);
3527     }
3528     else {
3529         print "Upgrade to $DBversion done.\n";
3530         print "NOTICE: The Locale::Currency::Format package is not installed on your system or not found in \@INC.\nThis dependency is required in order to include fine information in overdue notices.\nPlease ask your system administrator to install this package.\n";
3531         SetVersion ($DBversion);
3532     }
3533 }
3534
3535 $DBversion = '3.01.00.120';
3536 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3537     $dbh->do(q{
3538 INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('soundon','0','Enable circulation sounds during checkin and checkout in the staff interface.  Not supported by all web browsers yet.','','YesNo');
3539 });
3540     print "Upgrade to $DBversion done (bug 1080: add soundon system preference for circulation sounds)\n";
3541     SetVersion ($DBversion);
3542 }
3543
3544 $DBversion = '3.01.00.121';
3545 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3546     $dbh->do("ALTER TABLE `reserves` ADD `expirationdate` DATE DEFAULT NULL");
3547     $dbh->do("ALTER TABLE `reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3548     $dbh->do("ALTER TABLE `old_reserves` ADD `expirationdate` DATE DEFAULT NULL");
3549     $dbh->do("ALTER TABLE `old_reserves` ADD `lowestPriority` tinyint(1) NOT NULL");
3550     print "Upgrade to $DBversion done ( Added Additional Fields to Reserves tables )\n";
3551     SetVersion ($DBversion);
3552 }
3553
3554 $DBversion = '3.01.00.122';
3555 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3556     $dbh->do(q{
3557       INSERT INTO systempreferences (variable,value,explanation,options,type)
3558       VALUES ('OAI-PMH:ConfFile', '', 'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','','File');
3559 });
3560     print "Upgrade to $DBversion done. — Add a new system preference OAI-PMF:ConfFile\n";
3561     SetVersion ($DBversion);
3562 }
3563
3564 $DBversion = "3.01.00.123";
3565 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3566     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3567         (6, 'place_holds', 'Place holds for patrons')");
3568     $dbh->do("INSERT INTO `permissions` (`module_bit`, `code`, `description`) VALUES
3569         (6, 'modify_holds_priority', 'Modify holds priority')");
3570     $dbh->do("UPDATE `userflags` SET `flagdesc` = 'Place and modify holds for patrons' WHERE `flag` = 'reserveforothers'");
3571     print "Upgrade to $DBversion done (Add granular permission for holds modification and update description of reserveforothers permission)\n";
3572     SetVersion ($DBversion);
3573 }
3574
3575 $DBversion = '3.01.00.124';
3576 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3577     $dbh->do("
3578         INSERT INTO `letter` (module, code, name, title, content)         VALUES('reserves', 'HOLDPLACED', 'Hold Placed on Item', 'Hold Placed on Item','A hold has been placed on the following item : <<title>> (<<biblionumber>>) by the user <<firstname>> <<surname>> (<<cardnumber>>).');
3579     ");
3580     print "Upgrade to $DBversion done (bug 3242: add HOLDPLACED letter template, which is used when emailLibrarianWhenHoldIsPlaced is enabled)\n";
3581     SetVersion ($DBversion);
3582 }
3583
3584 $DBversion = '3.01.00.125';
3585 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3586     $dbh->do("
3587         INSERT INTO `systempreferences` ( `variable` , `value` , `options` , `explanation` , `type` ) VALUES ( 'PrintNoticesMaxLines', '0', '', 'If greater than 0, sets the maximum number of lines an overdue notice will print. If the number of items is greater than this number, the notice will end with a warning asking the borrower to check their online account for a full list of overdue items.', 'Integer' );
3588     ");
3589     $dbh->do("
3590         INSERT INTO message_transport_types (message_transport_type) values ('print');
3591     ");
3592     print "Upgrade to $DBversion done (bug 3482: Printable hold and overdue notices)\n";
3593     SetVersion ($DBversion);
3594 }
3595
3596 $DBversion = "3.01.00.126";
3597 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3598         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ILS-DI','0','Enable ILS-DI services. See http://your.opac.name/cgi-bin/koha/ilsdi.pl for online documentation.','','YesNo')");
3599         $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ILS-DI:AuthorizedIPs','127.0.0.1','A comma separated list of IP addresses authorized to access the web services.','','free')");
3600
3601     print "Upgrade to $DBversion done (Adding ILS-DI updates and ILS-DI:AuthorizedIPs)\n";
3602     SetVersion ($DBversion);
3603 }
3604
3605 $DBversion = '3.01.00.127';
3606 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3607     $dbh->do("ALTER TABLE messages CHANGE branchcode branchcode varchar(10);");
3608     print "Upgrade to $DBversion done (bug 4190: messages in patron account did not work with branchcodes > 4)\n";
3609     SetVersion ($DBversion);
3610 }
3611
3612 $DBversion = '3.01.00.128';
3613 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3614     $dbh->do('CREATE INDEX budget_id ON aqorders (budget_id );');
3615     print "Upgrade to $DBversion done (bug 4331: index orders by budget_id)\n";
3616     SetVersion ($DBversion);
3617 }
3618
3619 $DBversion = "3.01.00.129";
3620 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3621         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchdel' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchdel' LIMIT 1 ;");
3622         $dbh->do("UPDATE `permissions` SET `code` = 'items_batchmod' WHERE `permissions`.`module_bit` =13 AND `permissions`.`code` = 'batchmod' LIMIT 1 ;");
3623         print "Upgrade to $DBversion done (Change permissions names for item batch modification / deletion)\n";
3624
3625     SetVersion ($DBversion);
3626 }
3627
3628 $DBversion = "3.01.00.130";
3629 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3630     sanitize_zero_date('reserves', 'expirationdate');
3631     print "Upgrade to $DBversion done (change reserves.expirationdate values of 0000-00-00 to NULL (bug 1532)\n";
3632     SetVersion ($DBversion);
3633 }
3634
3635 $DBversion = "3.01.00.131";
3636 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3637         $dbh->do(q{
3638 INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('print'),('feed');
3639     });
3640     print "Upgrade to $DBversion done (adding print and feed message transport types)\n";
3641     SetVersion ($DBversion);
3642 }
3643
3644 $DBversion = "3.01.00.132";
3645 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3646         $dbh->do(q{
3647     ALTER TABLE language_descriptions ADD INDEX subtag_type_lang (subtag, type, lang);
3648     });
3649     print "Upgrade to $DBversion done (Adding index to language_descriptions table)\n";
3650     SetVersion ($DBversion);
3651 }
3652
3653 $DBversion = '3.01.00.133';
3654 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3655     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OverduesBlockCirc','noblock','When checking out an item should overdues block checkout, generate a confirmation dialogue, or allow checkout','noblock|confirmation|block','Choice')");
3656     print "Upgrade to $DBversion done (bug 4405: added OverduesBlockCirc syspref to control whether circulation is blocked if a borrower has overdues)\n";
3657     SetVersion ($DBversion);
3658 }
3659
3660 $DBversion = '3.01.00.134';
3661 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3662     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('DisplayMultiPlaceHold','1','Display the ability to place multiple holds or not','','YesNo')");
3663     print "Upgrade to $DBversion done (adding syspref DisplayMultiPlaceHold to control whether multiple holds can be placed from the search results page)\n";
3664     SetVersion ($DBversion);
3665 }
3666
3667 $DBversion = '3.01.00.135';
3668 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3669     $dbh->do("
3670         INSERT INTO `letter` (module, code, name, title, content) VALUES
3671 ('reserves', 'HOLD_PRINT', 'Hold Available for Pickup (print notice)', 'Hold Available for Pickup (print notice)', '<<branches.branchname>>\r\n<<branches.branchaddress1>>\r\n<<branches.branchaddress2>>\r\n\r\n\r\nChange Service Requested\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<<borrowers.firstname>> <<borrowers.surname>>\r\n<<borrowers.address>>\r\n<<borrowers.city>> <<borrowers.zipcode>>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<<borrowers.firstname>> <<borrowers.surname>> <<borrowers.cardnumber>>\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\n')
3672 ");
3673     print "Upgrade to $DBversion done (bug 4377: added HOLD_PRINT message template)\n";
3674     SetVersion ($DBversion);
3675 }
3676
3677 $DBversion = '3.01.00.136';
3678 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3679     $dbh->do(qq{
3680 INSERT INTO permissions (module_bit, code, description) VALUES
3681    ( 9, 'edit_items', 'Edit Items');});
3682     print "Upgrade to $DBversion done (Adding a new permission to edit items)\n";
3683     SetVersion ($DBversion);
3684 }
3685
3686 $DBversion = "3.01.00.137";
3687 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3688         $dbh->do("
3689           INSERT INTO permissions (module_bit, code, description) VALUES
3690           (15, 'check_expiration', 'Check the expiration of a serial'),
3691           (15, 'claim_serials', 'Claim missing serials'),
3692           (15, 'create_subscription', 'Create a new subscription'),
3693           (15, 'delete_subscription', 'Delete an existing subscription'),
3694           (15, 'edit_subscription', 'Edit an existing subscription'),
3695           (15, 'receive_serials', 'Serials receiving'),
3696           (15, 'renew_subscription', 'Renew a subscription'),
3697           (15, 'routing', 'Routing');
3698                  ");
3699     print "Upgrade to $DBversion done (adding granular permissions for serials)\n";
3700     SetVersion ($DBversion);
3701 }
3702
3703 $DBversion = "3.01.00.138";
3704 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3705     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GranularPermissions'");
3706     print "Upgrade to $DBversion done (bug 4896: removing GranularPermissions syspref; use of granular permissions is now the default)\n";
3707     SetVersion ($DBversion);
3708 }
3709
3710 $DBversion = '3.01.00.139';
3711 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3712     $dbh->do("ALTER TABLE message_attributes CHANGE message_name message_name varchar(40);");
3713     print "Upgrade to $DBversion done (bug 3682: change message_name from varchar(20) to varchar(40))\n";
3714     SetVersion ($DBversion);
3715 }
3716
3717 $DBversion = '3.01.00.140';
3718 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3719     $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'TagsModeration' AND value is NULL");
3720     print "Upgrade to $DBversion done (bug 4312 TagsModeration changed from NULL to 0)\n";
3721     SetVersion ($DBversion);
3722 }
3723
3724 $DBversion = '3.01.00.141';
3725 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3726     $dbh->do(qq{DELETE FROM message_attributes WHERE message_attribute_id=3;});
3727     $dbh->do(qq{DELETE FROM letter WHERE code='EVENT' AND title='Upcoming Library Event';});
3728     print "Upgrade to $DBversion done Remove upcoming events messaging option (bug 2434)\n";
3729     SetVersion ($DBversion);
3730 }
3731
3732 $DBversion = '3.01.00.142';
3733 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3734     $dbh->do(qq{DELETE FROM message_transports WHERE message_attribute_id=3;});
3735     print "Upgrade to $DBversion done (Remove upcoming events messaging option part 2 (bug 2434))\n";
3736     SetVersion ($DBversion);
3737 }
3738
3739 $DBversion = '3.01.00.143';
3740 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3741     $dbh->do(qq{CREATE INDEX auth_value_idx ON authorised_values (authorised_value)});
3742     $dbh->do(qq{CREATE INDEX auth_val_cat_idx ON borrower_attribute_types (authorised_value_category)});
3743     print "Upgrade to $DBversion done (Create index on authorised_values and borrower_attribute_types (bug 4139))\n";
3744     SetVersion ($DBversion);
3745 }
3746
3747 $DBversion = '3.01.00.144';
3748 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3749     $dbh->do(qq{UPDATE systempreferences SET value='normal' where value='default' and variable='IntranetBiblioDefaultView'});
3750     print "Upgrade to $DBversion done (Update the 'default' to 'normal' for the IntranetBiblioDefaultView syspref (bug 5007))\n";
3751     SetVersion ($DBversion);
3752 }
3753
3754 $DBversion = "3.01.00.145";
3755 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3756     $dbh->do("ALTER TABLE borrowers ADD KEY `guarantorid` (guarantorid);");
3757     print "Upgrade to $DBversion done (Add index on guarantorid)\n";
3758     SetVersion ($DBversion);
3759 }
3760
3761 $DBversion = '3.01.00.999';
3762 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3763     print "Upgrade to $DBversion done (3.2.0 release candidate)\n";
3764     SetVersion ($DBversion);
3765 }
3766
3767 $DBversion = "3.02.00.000";
3768 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3769     my $value = $dbh->selectrow_array("SELECT value FROM systempreferences WHERE variable = 'HomeOrHoldingBranch'");
3770     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('HomeOrHoldingBranchReturn','$value','Used by Circulation to determine which branch of an item to check checking-in items','holdingbranch|homebranch','Choice');");
3771     print "Upgrade to $DBversion done (Add HomeOrHoldingBranchReturn system preference)\n";
3772     SetVersion ($DBversion);
3773 }
3774
3775 $DBversion = "3.02.00.001";
3776 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3777     $dbh->do(q{DELETE FROM systempreferences WHERE variable IN (
3778                 'holdCancelLength',
3779                 'PINESISBN',
3780                 'sortbynonfiling',
3781                 'TemplateEncoding',
3782                 'OPACSubscriptionDisplay',
3783                 'OPACDisplayExtendedSubInfo',
3784                 'OAI-PMH:Set',
3785                 'OAI-PMH:Subset',
3786                 'libraryAddress',
3787                 'kohaspsuggest',
3788                 'OrderPdfTemplate',
3789                 'marc',
3790                 'acquisitions',
3791                 'MIME')
3792                }
3793     );
3794     print "Upgrade to $DBversion done (bug 3756: remove disused system preferences)\n";
3795     SetVersion ($DBversion);
3796 }
3797
3798 $DBversion = "3.02.00.002";
3799 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3800     $dbh->do(q{DELETE FROM systempreferences WHERE variable = 'OpacPrivacy'});
3801     print "Upgrade to $DBversion done (bug 3881: remove unused OpacPrivacy system preference)\n";
3802     SetVersion ($DBversion);
3803 }
3804
3805 $DBversion = "3.02.00.003";
3806 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3807     $dbh->do(q{UPDATE systempreferences SET variable = 'ILS-DI:AuthorizedIPs' WHERE variable = 'ILS-DI:Authorized_IPs'});
3808     print "Upgrade to $DBversion done (correct ILS-DI:AuthorizedIPs)\n";
3809     SetVersion ($DBversion);
3810 }
3811
3812 $DBversion = "3.02.00.004";
3813 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3814     print "Upgrade to $DBversion done (3.2.0 general release)\n";
3815     SetVersion ($DBversion);
3816 }
3817 # This is the point where 3.2.x and master diverged, we can use $original_version to make sure we don't
3818
3819 # apply updates that have already been done
3820
3821 $DBversion = "3.03.00.001";
3822 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.005")) {
3823     $dbh->do("DELETE FROM subscriptionroutinglist WHERE borrowernumber IS NULL;");
3824     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `borrowernumber` int(11) NOT NULL;");
3825     $dbh->do("DELETE FROM subscriptionroutinglist WHERE subscriptionid IS NULL;");
3826     $dbh->do("ALTER TABLE subscriptionroutinglist MODIFY COLUMN `subscriptionid` int(11) NOT NULL;");
3827     $dbh->do("CREATE TEMPORARY TABLE del_subscriptionroutinglist
3828               SELECT s1.routingid FROM subscriptionroutinglist s1
3829               WHERE EXISTS (SELECT * FROM subscriptionroutinglist s2
3830                             WHERE s2.borrowernumber = s1.borrowernumber
3831                             AND   s2.subscriptionid = s1.subscriptionid
3832                             AND   s2.routingid < s1.routingid);");
3833     $dbh->do("DELETE FROM subscriptionroutinglist
3834               WHERE routingid IN (SELECT routingid FROM del_subscriptionroutinglist);");
3835     $dbh->do("ALTER TABLE subscriptionroutinglist ADD UNIQUE (subscriptionid, borrowernumber);");
3836     $dbh->do("ALTER TABLE subscriptionroutinglist
3837                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_1` FOREIGN KEY (`borrowernumber`)
3838                 REFERENCES `borrowers` (`borrowernumber`)
3839                 ON DELETE CASCADE ON UPDATE CASCADE");
3840     $dbh->do("ALTER TABLE subscriptionroutinglist
3841                 ADD CONSTRAINT `subscriptionroutinglist_ibfk_2` FOREIGN KEY (`subscriptionid`)
3842                 REFERENCES `subscription` (`subscriptionid`)
3843                 ON DELETE CASCADE ON UPDATE CASCADE");
3844     print "Upgrade to $DBversion done (Make subscriptionroutinglist more strict)\n";
3845     SetVersion ($DBversion);
3846 }
3847
3848 $DBversion = '3.03.00.002';
3849 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.006")) {
3850     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='arm' WHERE rfc4646_subtag='hy';");
3851     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='eng' WHERE rfc4646_subtag='en';");
3852     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'fi','fin');");
3853     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='fre' WHERE rfc4646_subtag='fr';");
3854     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'lo','lao');");
3855     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it';");
3856     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'sr','srp');");
3857     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'tet','tet');");
3858     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ur','urd');");
3859
3860     print "Upgrade to $DBversion done (Correct language mappings)\n";
3861     SetVersion ($DBversion);
3862 }
3863
3864 $DBversion = '3.03.00.003';
3865 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.00.007")) {
3866     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTablesortForCirc','0','If on, use the JQuery tablesort function on the list of current borrower checkouts on the circulation page. Note that the use of this function may slow down circ for patrons with may checkouts.','','YesNo');");
3867     print "Upgrade to $DBversion done (Add UseTablesortForCirc syspref)\n";
3868     SetVersion ($DBversion);
3869 }
3870
3871 $DBversion = '3.03.00.004';
3872 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.001")) {
3873     my $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ACCEPTED');
3874     $dbh->do(q/
3875 INSERT INTO `letter`
3876 (module, code, name, title, content)
3877 VALUES
3878 ('suggestions','ACCEPTED','Suggestion accepted', 'Purchase suggestion accepted','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nThe library has reviewed your suggestion today. The item will be ordered as soon as possible. You will be notified by mail when the order is completed, and again when the item arrives at the library.\n\nIf you have any questions, please email us at <<branches.branchemail>>.\n\nThank you,\n\n<<branches.branchname>>')
3879 /) unless $count > 0;
3880     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'AVAILABLE');
3881     $dbh->do(q/
3882 INSERT INTO `letter`
3883 (module, code, name, title, content)
3884 VALUES
3885 ('suggestions','AVAILABLE','Suggestion available', 'Suggested purchase available','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nWe are pleased to inform you that the item you requested is now part of the collection.\n\nIf you have any questions, please email us at <<branches.branchemail>>.\n\nThank you,\n\n<<branches.branchname>>')
3886 /) unless $count > 0;
3887     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'ORDERED');
3888     $dbh->do(q/
3889 INSERT INTO `letter`
3890 (module, code, name, title, content)
3891 VALUES
3892 ('suggestions','ORDERED','Suggestion ordered', 'Suggested item ordered','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nWe are pleased to inform you that the item you requested has now been ordered. It should arrive soon, at which time it will be processed for addition into the collection.\n\nYou will be notified again when the book is available.\n\nIf you have any questions, please email us at <<branches.branchemail>>\n\nThank you,\n\n<<branches.branchname>>')
3893 /) unless $count > 0;
3894     $count = $dbh->selectrow_array('SELECT COUNT(*) FROM letter WHERE module = ? AND code = ?', {}, 'suggestions', 'REJECTED');
3895     $dbh->do(q/
3896 INSERT INTO `letter`
3897 (module, code, name, title, content)
3898 VALUES
3899 ('suggestions','REJECTED','Suggestion rejected', 'Purchase suggestion declined','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nYou have suggested that the library acquire <<suggestions.title>> by <<suggestions.author>>.\n\nThe library has reviewed your request today, and has decided not to accept the suggestion at this time.\n\nThe reason given is: <<suggestions.reason>>\n\nIf you have any questions, please email us at <<branches.branchemail>>.\n\nThank you,\n\n<<branches.branchname>>')
3900 /) unless $count > 0;
3901     print "Upgrade to $DBversion done (bug 5127: add default templates for suggestion status change notifications)\n";
3902     SetVersion ($DBversion);
3903 };
3904
3905 $DBversion = '3.03.00.005';
3906 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3907     $dbh->do("update `systempreferences` set options='whitespace|T-prefix|cuecat|libsuite8' where variable='itemBarcodeInputFilter'");
3908     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice libsuite8)\n";
3909 }
3910
3911 $DBversion = '3.03.00.006';
3912 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.002")) {
3913     $dbh->do("ALTER TABLE deletedborrowers ADD `privacy` int(11) AFTER smsalertnumber;");
3914     $dbh->do("ALTER TABLE deletedborrowers CHANGE `cardnumber` `cardnumber` varchar(16);");
3915     print "Upgrade to $DBversion done (Fix differences between borrowers and deletedborrowers)\n";
3916     SetVersion ($DBversion);
3917 }
3918
3919 $DBversion = '3.03.00.007';
3920 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3921     $dbh->do("ALTER table suggestions ADD quantity SMALLINT(6) default NULL,
3922                 ADD currency VARCHAR(3) default NULL,
3923                 ADD price DECIMAL(28,6) default NULL,
3924                 ADD total DECIMAL(28,6) default NULL;
3925                 ");
3926     print "Upgrade to $DBversion done (Added acq related columns to suggestions)\n";
3927     SetVersion ($DBversion);
3928 }
3929
3930 $DBversion = '3.03.00.008';
3931 if (C4::Context->preference('Version') < TransformToNum($DBversion)){
3932     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACNoResultsFound','','Display this HTML when no results are found for a search in the OPAC','70|10','Textarea')");
3933     print "Upgrade to $DBversion done (adding syspref OPACNoResultsFound to control what displays when no results are found for a search in the OPAC.)\n";
3934     SetVersion ($DBversion);
3935 }
3936
3937 $DBversion = '3.03.00.009';
3938 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.01.003")) {
3939     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetUserCSS','','Add CSS to be included in the Intranet',NULL,'free')");
3940     print "Upgrade to $DBversion done (Add IntranetUserCSS syspref)\n";
3941     SetVersion ($DBversion);
3942 }
3943
3944 $DBversion = "3.03.00.010";
3945 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.02.001")) {
3946     $dbh->do("UPDATE `marc_subfield_structure` SET liblibrarian = 'Distance from earth' WHERE liblibrarian = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3947     $dbh->do("UPDATE `marc_subfield_structure` SET libopac = 'Distance from earth' WHERE libopac = 'Distrance from earth' AND tagfield = '034' AND tagsubfield = 'r';");
3948     print "Upgrade to $DBversion done (Fix misspelled 034r subfield in MARC21 Frameworks)\n";
3949     SetVersion ($DBversion);
3950 }
3951
3952 $DBversion = "3.03.00.011";
3953 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3954     $dbh->do("UPDATE aqbooksellers SET gstrate=NULL WHERE gstrate=0.0");
3955     print "Upgrade to $DBversion done (Bug 5186: allow GST rate to be set to 0)\n";
3956     SetVersion ($DBversion);
3957 }
3958
3959 $DBversion = "3.03.00.012";
3960 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3961    $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('maxItemsInSearchResults',20,'Specify the maximum number of items to display for each result on a page of results',NULL,'free')");
3962    print "Upgrade to $DBversion done (Bug 2142: maxItemsInSearchResults syspref resurrected)\n";
3963    SetVersion ($DBversion);
3964 }
3965
3966 $DBversion = "3.03.00.013";
3967 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3968     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacPublic','1','If set to OFF and user is not logged in, all  OPAC pages require authentication, and OPAC searchbar is removed)','','YesNo')");
3969     print "Upgrade to $DBversion done (added 'OpacPublic' syspref)\n";
3970    SetVersion ($DBversion);
3971 }
3972
3973 $DBversion = "3.03.00.014";
3974 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
3975     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('ShelfBrowserUsesLocation','1','Use the item location when finding items for the shelf browser.','1','YesNo')");
3976     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('ShelfBrowserUsesHomeBranch','1','Use the item home branch when finding items for the shelf browser.','1','YesNo')");
3977     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('ShelfBrowserUsesCcode','0','Use the item collection code when finding items for the shelf browser.','1','YesNo')");
3978     print "Upgrade to $DBversion done (Add flexible shelf browser constraints)\n";
3979     SetVersion ($DBversion);
3980 }
3981
3982 $DBversion = "3.03.00.015";
3983 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
3984     if ( C4::Context->preference("marcflavour") eq "MARC21" ) {
3985         my $sth = $dbh->prepare(
3986 "INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`,
3987                              `tab`, `authorised_value`, `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`)
3988                              VALUES ( ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, '', 6, '', '', '', 0, -5, '', '', '', NULL)"
3989         );
3990         $sth->execute('648');
3991         $sth->execute('654');
3992         $sth->execute('655');
3993         $sth->execute('656');
3994         $sth->execute('657');
3995         $sth->execute('658');
3996         $sth->execute('662');
3997         $sth->finish;
3998         print
3999 "Upgrade to $DBversion done (Bug 5619: Add subfield 9 to marc21 648,654,655,656,657,658,662)\n";
4000     }
4001     SetVersion($DBversion);
4002 }
4003
4004 $DBversion = '3.03.00.016';
4005 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4006     # reimplement OpacPrivacy system preference
4007     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacPrivacy', '0', 'if ON, allows patrons to define their privacy rules (reading history)',NULL,'YesNo')");
4008     $dbh->do("ALTER TABLE `borrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4009     $dbh->do("ALTER TABLE `deletedborrowers` ADD `privacy` INTEGER NOT NULL DEFAULT 1;");
4010     print "Upgrade to $DBversion done (OpacPrivacy reimplementation)\n";
4011     SetVersion($DBversion);
4012 };
4013
4014 $DBversion = '3.03.00.017';
4015 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.001")) {
4016     $dbh->do("ALTER TABLE  `currency` CHANGE `rate` `rate` FLOAT( 15, 5 ) NULL DEFAULT NULL;");
4017     print "Upgrade to $DBversion done (Enable currency rates >= 100)\n";
4018     SetVersion ($DBversion);
4019 }
4020
4021 $DBversion = '3.03.00.018';
4022 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.002")) {
4023     $dbh->do( q|update language_descriptions set description = 'Nederlands' where lang = 'nl' and subtag = 'nl'|);
4024     $dbh->do( q|update language_descriptions set description = 'Dansk' where lang = 'da' and subtag = 'da'|);
4025     print "Upgrade to $DBversion done (Correct language descriptions)\n";
4026     SetVersion ($DBversion);
4027 }
4028
4029 $DBversion = '3.03.00.019';
4030 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.03.003")) {
4031     # Fix bokmål
4032     $dbh->do("UPDATE language_subtag_registry SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb';");
4033     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nb','nob');");
4034     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokm&#229;l' WHERE subtag = 'nb' AND lang = 'nb';");
4035     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokm&#229;l' WHERE subtag = 'nb' AND lang = 'en';");
4036     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokm&#229;l' WHERE subtag = 'nb' AND lang = 'fr';");
4037     # Add nynorsk
4038     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'nn', 'language', 'Norwegian nynorsk','2011-02-14' )");
4039     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'nn','nno')");
4040     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nb', 'Norsk nynorsk')");
4041     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'nn', 'Norsk nynorsk')");
4042     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'en', 'Norwegian nynorsk')");
4043     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'nn', 'language', 'fr', 'Norvégien nynorsk')");
4044     print "Upgrade to $DBversion done (Correct language descriptions for Norwegian)\n";
4045     SetVersion ($DBversion);
4046 }
4047
4048 $DBversion = '3.03.00.020';
4049 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4050     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowFineOverride','0','If on, staff will be able to issue books to patrons with fines greater than noissuescharge.','0','YesNo')");
4051     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllFinesNeedOverride','1','If on, staff will be asked to override every fine, even if it is below noissuescharge.','0','YesNo')");
4052     print "Upgrade to $DBversion done (Bug 5811: Add sysprefs controlling overriding fines)\n";
4053     SetVersion($DBversion);
4054 };
4055
4056 $DBversion = '3.03.00.021';
4057 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.001")) {
4058     $dbh->do("ALTER TABLE items MODIFY enumchron TEXT");
4059     $dbh->do("ALTER TABLE deleteditems MODIFY enumchron TEXT");
4060     print "Upgrade to $DBversion done (bug 5642: longer serial enumeration)\n";
4061     SetVersion ($DBversion);
4062 }
4063
4064 $DBversion = '3.03.00.022';
4065 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4066     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AuthoritiesLog','0','If ON, log edit/create/delete actions on authorities.','','YesNo');");
4067     print "Upgrade to $DBversion done (Add AuthoritiesLog syspref)\n";
4068     SetVersion ($DBversion);
4069 }
4070
4071 # due to a mismatch in kohastructure.sql some koha will have missing columns in aqbasketgroup
4072 # this attempts to fix that
4073 $DBversion = '3.03.00.023';
4074 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.002")) {
4075     my $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'billingplace'");
4076     $sth->execute;
4077     $dbh->do("ALTER TABLE aqbasketgroups ADD billingplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4078     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliveryplace'");
4079     $sth->execute;
4080     $dbh->do("ALTER TABLE aqbasketgroups ADD deliveryplace VARCHAR(10)") if ! $sth->fetchrow_hashref;
4081     $sth = $dbh->prepare("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'aqbasketgroups' AND COLUMN_NAME = 'deliverycomment'");
4082     $sth->execute;
4083     $dbh->do("ALTER TABLE aqbasketgroups ADD deliverycomment VARCHAR(255)") if ! $sth->fetchrow_hashref;
4084     print "Upgrade to $DBversion done (Reconcile aqbasketgroups)\n";
4085     SetVersion ($DBversion);
4086 }
4087
4088 $DBversion = '3.03.00.024';
4089 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4090     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('TraceCompleteSubfields','0','Force subject tracings to only match complete subfields.','0','YesNo')");
4091     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('UseAuthoritiesForTracings','1','Use authority record numbers for subject tracings instead of heading strings.','0','YesNo')");
4092     print "Upgrade to $DBversion done (Add syspref to force whole-subfield matching on subject tracings)\n";
4093     SetVersion($DBversion);
4094 };
4095
4096 $DBversion = "3.03.00.025";
4097 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4098     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OPACAllowUserToChooseBranch', 1, 'Allow the user to choose the branch they want to pickup their hold from','1','YesNo')");
4099     print "Upgrade to $DBversion done (Add syspref to control if user can choose pickup branch for holds)\n";
4100     SetVersion ($DBversion);
4101 }
4102
4103 $DBversion = '3.03.00.026';
4104 if (C4::Context->preference("Version") < TransformToNum($DBversion) && $original_version < TransformToNum("3.02.05.003")) {
4105     $dbh->do("UPDATE `message_attributes` SET message_name='Item Due' WHERE message_attribute_id=1 AND message_name LIKE 'Item DUE'");
4106         print "Upgrade to $DBversion done ( fix capitalization in message type )\n";
4107     SetVersion ($DBversion);
4108 }
4109
4110 $DBversion = '3.03.00.027';
4111 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4112     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('displayFacetCount', '0', NULL, NULL, 'YesNo')");
4113     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('maxRecordsForFacets', '20', NULL, NULL, 'Integer')");
4114     print "Upgrade to $DBversion done (Preferences for facet count)\n";
4115     SetVersion ($DBversion);
4116 }
4117
4118 $DBversion = "3.03.00.028";
4119 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4120     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('FacetLabelTruncationLength', 20, 'Truncate facets length to','','free')");
4121     print "Upgrade to $DBversion done (Add FacetLabelTruncationLength syspref to control facets displayed length)\n";
4122     SetVersion ($DBversion);
4123 }
4124
4125 $DBversion = "3.03.00.029";
4126 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4127     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowPurchaseSuggestionBranchChoice', 0, 'Allow user to choose branch when making a purchase suggestion','1','YesNo')");
4128     print "Upgrade to $DBversion done (Add syspref to control if user can choose branch when making purchase suggestion)\n";
4129     SetVersion ($DBversion);
4130 }
4131
4132 $DBversion = "3.03.00.030";
4133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4134     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacFavicon','','Enter a complete URL to an image to replace the default Koha favicon on the OPAC','','free')");
4135     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('IntranetFavicon','','Enter a complete URL to an image to replace the default Koha favicon on the Staff client','','free')");
4136     print "Upgrade to $DBversion done (Add sysprefs to control custom favicons)\n";
4137     SetVersion ($DBversion);
4138 }
4139
4140 $DBversion = "3.03.00.031";
4141 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4142     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('FineNotifyAtCheckin',0,'If ON notify librarians of overdue fines on the items they are checking in.',NULL,'YesNo');");
4143     print "Upgrade to $DBversion done (Add syspref FineNotifyAtCheckin)\n";
4144     SetVersion ($DBversion);
4145 }
4146
4147 $DBversion = '3.03.00.032';
4148 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4149     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('TraceSubjectSubdivisions', 1, 'Create searches on all subdivisions for subject tracings.','1','YesNo')");
4150     print "Upgrade to $DBversion done ( include subdivisions when generating subject tracing searches )\n";
4151 }
4152
4153
4154 $DBversion = '3.03.00.033';
4155 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4156     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('StaffAuthorisedValueImages', '1', '', NULL, 'YesNo')");
4157     print "Upgrade to $DBversion done (System pref StaffAuthorisedValueImages)\n";
4158     SetVersion ($DBversion);
4159 }
4160
4161 $DBversion = '3.03.00.034';
4162 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4163     $dbh->do("ALTER TABLE `categories` ADD `hidelostitems` tinyint(1) NOT NULL default '0' AFTER `reservefee`");
4164     print "Upgrade to $DBversion done (Add hidelostitems preference to borrower categories)\n";
4165     SetVersion ($DBversion);
4166 }
4167
4168 $DBversion = '3.03.00.035';
4169 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4170     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedate date default NULL AFTER issuelength");
4171     $dbh->do("ALTER TABLE `issuingrules` ADD hardduedatecompare tinyint NOT NULL default 0 AFTER hardduedate");
4172     my $duedate;
4173     if (C4::Context->preference("globalDueDate")) {
4174       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("globalDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4175       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = 0");
4176     } elsif (C4::Context->preference("ceilingDueDate")) {
4177       $duedate = eval { output_pref( { dt => dt_from_string( C4::Context->preference("ceilingDueDate") ), dateonly => 1, dateformat => 'iso' } ); };
4178       $dbh->do("UPDATE `issuingrules` SET hardduedate = '$duedate', hardduedatecompare = -1");
4179     }
4180     $dbh->do("DELETE FROM `systempreferences` WHERE variable = 'globalDueDate' OR variable = 'ceilingDueDate'");
4181     print "Upgrade to $DBversion done (Move global and ceiling due dates to Circ Rules level)\n";
4182     SetVersion ($DBversion);
4183 }
4184
4185 $DBversion = '3.03.00.036';
4186 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4187     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('COinSinOPACResults', 1, 'If ON, use COinS in OPAC search results page.  NOTE: this can slow down search response time significantly','','YesNo')");
4188     print "Upgrade to $DBversion done ( Make COinS optional in OPAC search results )\n";
4189     SetVersion ($DBversion);
4190 }
4191
4192 $DBversion = '3.03.00.037';
4193 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4194     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACDisplay856uAsImage','OFF','Display the URI in the 856u field as an image, the corresponding OPACXSLT option must be on','OFF|Details|Results|Both','Choice')");
4195     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('Display856uAsImage','OFF','Display the URI in the 856u field as an image, the corresponding Staff Client XSLT option must be on','OFF|Details|Results|Both','Choice')");
4196     print "Upgrade to $DBversion done (Add 'Display856uAsImage' and 'OPACDisplay856uAsImage' syspref)\n";
4197     SetVersion ($DBversion);
4198 }
4199
4200 $DBversion = '3.03.00.038';
4201 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4202     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('SelfCheckTimeout',120,'Define the number of seconds before the Web-based Self Checkout times out a patron','','Integer')");
4203     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowSelfCheckReturns',0,'If enabled, patrons may return items through the Web-based Self Checkout','','YesNo')");
4204     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('SelfCheckHelpMessage','','Enter HTML to include under the basic Web-based Self Checkout instructions on the Help page','70|10','Textarea')");
4205     print "Upgrade to $DBversion done ( Add Self-checkout by Login system preferences )\n";
4206 }
4207
4208 $DBversion = "3.03.00.039";
4209 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4210     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ShowReviewer',1,'If ON, name of reviewer will be shown above comments in OPAC',NULL,'YesNo');");
4211     print "Upgrade to $DBversion done (Add syspref ShowReviewer)\n";
4212 }
4213
4214 $DBversion = "3.03.00.040";
4215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4216     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseControlNumber',0,'If ON, record control number (w subfields) and control number (001) are used for linking of bibliographic records.','','YesNo');");
4217     print "Upgrade to $DBversion done (Add syspref UseControlNumber)\n";
4218 }
4219
4220 $DBversion = "3.03.00.041";
4221 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4222     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AlternateHoldingsField','','The MARC field/subfield that contains alternate holdings information for bibs taht do not have items attached (e.g. 852abchi for libraries converting from MARC Magician).',NULL,'free')");
4223     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('AlternateHoldingsSeparator','','The string to use to separate subfields in alternate holdings displays.',NULL,'free')");
4224     print "Upgrade to $DBversion done (Add sysprefs to control alternate holdings information display)\n";
4225     SetVersion ($DBversion);
4226 }
4227
4228 $DBversion = '3.03.00.042';
4229 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4230     stocknumber_checker();
4231     print "Upgrade to $DBversion done (5860 Index itemstocknumber)\n";
4232     SetVersion ($DBversion);
4233 }
4234
4235 sub stocknumber_checker { #code reused later on
4236   my @row;
4237   #drop the obsolete itemSStocknumber idx if it exists
4238   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemsstocknumberidx'");
4239   $dbh->do("ALTER TABLE `items` DROP INDEX `itemsstocknumberidx`;") if @row;
4240
4241   #check itemstocknumber idx; remove it if it is unique
4242   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx' AND non_unique=0");
4243   $dbh->do("ALTER TABLE `items` DROP INDEX `itemstocknumberidx`;") if @row;
4244
4245   #add itemstocknumber index non-unique IF it still not exists
4246   @row = $dbh->selectrow_array("SHOW INDEXES FROM items WHERE key_name='itemstocknumberidx'");
4247   $dbh->do("ALTER TABLE items ADD INDEX itemstocknumberidx (stocknumber);") unless @row;
4248 }
4249
4250 $DBversion = "3.03.00.043";
4251 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4252
4253     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','0','No','No')");
4254     $dbh->do("INSERT INTO authorised_values (category,authorised_value,lib,lib_opac) VALUES ('YES_NO','1','Yes','Yes')");
4255
4256         print "Upgrade to $DBversion done ( add generic boolean YES_NO authorised_values pair )\n";
4257         SetVersion ($DBversion);
4258 }
4259
4260 $DBversion = '3.03.00.044';
4261 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4262     $dbh->do("ALTER TABLE `aqbasketgroups` ADD `freedeliveryplace` TEXT NULL AFTER `deliveryplace`;");
4263     print "Upgrade to $DBversion done (adding freedeliveryplace to basketgroups)\n";
4264 }
4265
4266 $DBversion = '3.03.00.045';
4267 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4268     #Remove obsolete columns from aqbooksellers if needed
4269     my $a = $dbh->selectall_hashref('SHOW columns from aqbooksellers','Field');
4270     my $sqldrop="ALTER TABLE aqbooksellers DROP COLUMN ";
4271     foreach(qw/deliverydays followupdays followupscancel invoicedisc nocalc specialty/) {
4272       $dbh->do($sqldrop.$_) if exists $a->{$_};
4273     }
4274     #Remove obsolete column from aqbudgets if needed
4275     #The correct column is budget_notes
4276     $a = $dbh->selectall_hashref('SHOW columns from aqbudgets','Field');
4277     if(exists $a->{budget_description}) {
4278       $dbh->do("ALTER TABLE aqbudgets DROP COLUMN budget_description");
4279     }
4280     print "Upgrade to $DBversion done (Remove obsolete columns from aqbooksellers and aqbudgets if needed)\n";
4281     SetVersion ($DBversion);
4282 }
4283
4284 $DBversion = "3.03.00.046";
4285 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4286     $dbh->do("ALTER TABLE overduerules ALTER delay1 SET DEFAULT NULL, ALTER delay2 SET DEFAULT NULL, ALTER delay3 SET DEFAULT NULL");
4287     print "Upgrade to $DBversion done (Setting NULL default value for delayn columns in table overduerules)\n";
4288     SetVersion($DBversion);
4289 }
4290
4291 $DBversion = '3.03.00.047';
4292 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4293     $dbh->do("ALTER TABLE borrowers ADD `state` mediumtext AFTER city;");
4294     $dbh->do("ALTER TABLE borrowers ADD `B_state` mediumtext AFTER B_city;");
4295     $dbh->do("ALTER TABLE borrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4296     $dbh->do("ALTER TABLE deletedborrowers ADD `state` mediumtext AFTER city;");
4297     $dbh->do("ALTER TABLE deletedborrowers ADD `B_state` mediumtext AFTER B_city;");
4298     $dbh->do("ALTER TABLE deletedborrowers ADD `altcontactstate` mediumtext AFTER altcontactaddress3;");
4299     print "Upgrade to $DBversion done (Add state field to patron's addresses)\n";
4300 }
4301
4302 $DBversion = '3.03.00.048';
4303 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4304     $dbh->do("ALTER TABLE branches ADD `branchstate` mediumtext AFTER `branchcity`;");
4305     print "Upgrade to $DBversion done (Add state to branch address)\n";
4306     SetVersion ($DBversion);
4307 }
4308
4309 $DBversion = '3.03.00.049';
4310 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4311     $dbh->do("ALTER TABLE `accountlines` ADD `note` text NULL default NULL");
4312     $dbh->do("ALTER TABLE `accountlines` ADD `manager_id` int( 11 ) NULL ");
4313     print "Upgrade to $DBversion done (adding note and manager_id fields in accountlines table)\n";
4314     SetVersion($DBversion);
4315 }
4316
4317 $DBversion = "3.03.00.050";
4318 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4319     $dbh->do("
4320         INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacHiddenItems','','This syspref allows to define custom rules for hiding specific items at opac. See docs/opac/OpacHiddenItems.txt for more informations.','','Textarea');
4321         ");
4322     print "Upgrade to $DBversion done (Adding OpacHiddenItems syspref)\n";
4323     SetVersion($DBversion);
4324 }
4325
4326 $DBversion = "3.03.00.051";
4327 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4328     print "Upgrade to $DBversion done (Remove spaces and dashes from message_attribute names)\n";
4329     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Due' WHERE message_name='Item Due'");
4330     $dbh->do("UPDATE message_attributes SET message_name = 'Advance_Notice' WHERE message_name='Advance Notice'");
4331     $dbh->do("UPDATE message_attributes SET message_name = 'Hold_Filled' WHERE message_name='Hold Filled'");
4332     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Check_in' WHERE message_name='Item Check-in'");
4333     $dbh->do("UPDATE message_attributes SET message_name = 'Item_Checkout' WHERE message_name='Item Checkout'");
4334     SetVersion ($DBversion);
4335 }
4336
4337 $DBversion = "3.03.00.052";
4338 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4339     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('WaitingNotifyAtCheckin',0,'If ON, notify librarians of waiting holds for the patron whose items they are checking in.',NULL,'YesNo');");
4340     print "Upgrade to $DBversion done (Add syspref WaitingNotifyAtCheckin)\n";
4341     SetVersion ($DBversion);
4342 }
4343
4344 $DBversion = "3.04.00.000";
4345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4346     print "Upgrade to $DBversion done Koha 3.4.0 release \n";
4347     SetVersion ($DBversion);
4348 }
4349
4350 $DBversion = "3.05.00.001";
4351 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4352     $dbh->do(qq{
4353     INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('numSearchRSSResults',50,'Specify the maximum number of results to display on a RSS page of results',NULL,'Integer');
4354     });
4355     print "Upgrade to $DBversion done (Adds New System preference numSearchRSSResults)\n";
4356     SetVersion($DBversion);
4357 }
4358
4359 $DBversion = '3.05.00.002';
4360 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4361     #follow up fix 5860: some installs already past 3.3.0.42
4362     stocknumber_checker();
4363     print "Upgrade to $DBversion done (Fix for stocknumber index)\n";
4364     SetVersion ($DBversion);
4365 }
4366
4367 $DBversion = "3.05.00.003";
4368 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4369     $dbh->do(qq{
4370     INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacRenewalBranch','checkoutbranch','Choose how the branch for an OPAC renewal is recorded in statistics','itemhomebranch|patronhomebranch|checkoutbranch|null','Choice');
4371     });
4372     print "Upgrade to $DBversion done (Adds New System preference OpacRenewalBranch)\n";
4373     SetVersion($DBversion);
4374 }
4375
4376 $DBversion = "3.05.00.004";
4377 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4378     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('ShowReviewerPhoto',1,'If ON, photo of reviewer will be shown beside comments in OPAC',NULL,'YesNo');");
4379     print "Upgrade to $DBversion done (Add syspref ShowReviewerPhoto)\n";
4380     SetVersion($DBversion);
4381 }
4382
4383 $DBversion = "3.05.00.005";
4384 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4385     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('BasketConfirmations', '1', 'When closing or reopening a basket,', 'always ask for confirmation.|do not ask for confirmation.', 'Choice');");
4386     print "Upgrade to $DBversion done (Adds pref BasketConfirmations)\n";
4387     SetVersion($DBversion);
4388 }
4389
4390 $DBversion = "3.05.00.006";
4391 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4392     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('MARCAuthorityControlField008', '|| aca||aabn           | a|a     d', NULL, NULL, 'Textarea')");
4393     print "Upgrade to $DBversion done (Add syspref MARCAuthorityControlField008)\n";
4394     SetVersion ($DBversion);
4395 }
4396
4397 $DBversion = "3.05.00.007";
4398 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4399     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpenLibraryCovers',0,'If ON Openlibrary book covers will be show',NULL,'YesNo');");
4400     print "Upgrade to $DBversion done (Add syspref OpenLibraryCovers)\n";
4401     SetVersion($DBversion);
4402 }
4403
4404 $DBversion = "3.05.00.008";
4405 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4406     $dbh->do("ALTER TABLE `cities` ADD `city_state` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_name`;");
4407     $dbh->do("ALTER TABLE `cities` ADD `city_country` VARCHAR( 100 ) NULL DEFAULT NULL AFTER  `city_zipcode`;");
4408     print "Add state and country to cities table corresponding to new columns in borrowers\n";
4409     SetVersion($DBversion);
4410 }
4411
4412 $DBversion = "3.05.00.009";
4413 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4414     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4415               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE borrowernumber IS NULL");
4416     $dbh->do("DELETE FROM issues WHERE borrowernumber IS NULL");
4417
4418     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4419               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE itemnumber IS NULL");
4420     $dbh->do("DELETE FROM issues WHERE itemnumber IS NULL");
4421
4422     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4423               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4424     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowernumber = issues.borrowernumber)");
4425
4426     $dbh->do("INSERT INTO old_issues (borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate)
4427               SELECT borrowernumber, itemnumber, date_due, branchcode, issuingbranch, returndate, lastreneweddate, `return`, renewals, timestamp, issuedate FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4428     $dbh->do("DELETE FROM issues WHERE NOT EXISTS (SELECT * FROM items WHERE itemnumber = issues.itemnumber)");
4429
4430     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_1`");
4431     $dbh->do("ALTER TABLE issues DROP FOREIGN KEY `issues_ibfk_2`");
4432     $dbh->do("ALTER TABLE issues ALTER COLUMN borrowernumber DROP DEFAULT");
4433     $dbh->do("ALTER TABLE issues ALTER COLUMN itemnumber DROP DEFAULT");
4434     $dbh->do("ALTER TABLE issues MODIFY COLUMN borrowernumber int(11) NOT NULL");
4435     $dbh->do("ALTER TABLE issues MODIFY COLUMN itemnumber int(11) NOT NULL");
4436     $dbh->do("ALTER TABLE issues DROP KEY `issuesitemidx`");
4437     $dbh->do("ALTER TABLE issues ADD PRIMARY KEY (`itemnumber`)");
4438     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4439     $dbh->do("ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_2` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE RESTRICT ON UPDATE CASCADE");
4440
4441     print "Upgrade to $DBversion done (issues referential integrity)\n";
4442     SetVersion ($DBversion);
4443 }
4444
4445 $DBversion = "3.05.00.010";
4446 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4447     $dbh->do("CREATE INDEX priorityfoundidx ON reserves (priority,found)");
4448     print "Create an index on reserves to speed up holds awaiting pickup report bug 5866\n";
4449     SetVersion($DBversion);
4450 }
4451
4452
4453 $DBversion = "3.05.00.011";
4454 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4455     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACResultsSidebar','','Define HTML to be included on the search results page, underneath the facets sidebar','70|10','Textarea')");
4456     print "Upgrade to $DBversion done (add OPACResultsSidebar syspref (enh 6165))\n";
4457     SetVersion($DBversion);
4458 }
4459
4460 $DBversion = "3.05.00.012";
4461 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4462     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('RecordLocalUseOnReturn',0,'If ON, statistically record returns of unissued items as local use, instead of return',NULL,'YesNo')");
4463     print "Upgrade to $DBversion done (add RecordLocalUseOnReturn syspref (enh 6403))\n";
4464     SetVersion($DBversion);
4465 }
4466
4467 $DBversion = "3.05.00.013";
4468 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4469     $dbh->do(qq|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OpacKohaUrl','0',"Show 'Powered by Koha' text on OPAC footer.",NULL,NULL)|);
4470     print "Upgrade to $DBversion done (Add syspref 'OpacKohaUrl')\n";
4471     SetVersion($DBversion);
4472 }
4473
4474 $DBversion = "3.05.00.014";
4475 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4476     $dbh->do("ALTER TABLE `borrowers` MODIFY `userid` VARCHAR(75)");
4477     print "Modified userid column length into 75 in borrowers\n";
4478     SetVersion($DBversion);
4479 }
4480
4481 $DBversion = "3.05.00.015";
4482 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4483     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectEnabled',0,'Enable Novelist Select content.  Requires Novelist Profile and Password',NULL,'YesNo')");
4484     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectProfile',NULL,'Novelist Select user Password',NULL,'free')");
4485     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectPassword',NULL,'Enable Novelist user Profile',NULL,'free')");
4486     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('NovelistSelectView','tab','Where to display Novelist Select content','tab|above|below|right','Choice')");
4487     print "Upgrade to $DBversion done (Add support for EBSCO's NoveList Select (enh 6902))\n";
4488     SetVersion($DBversion);
4489 }
4490
4491 $DBversion = '3.05.00.016';
4492 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4493     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('EasyAnalyticalRecords','0','If on, display in the catalogue screens tools to easily setup analytical record relationships','','YesNo');");
4494     print "Upgrade to $DBversion done (Add EasyAnalyticalRecords syspref)\n";
4495     SetVersion ($DBversion);
4496 }
4497
4498 $DBversion = '3.05.00.017';
4499 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4500     if (C4::Context->preference("marcflavour") eq 'MARC21' ||
4501         C4::Context->preference("marcflavour") eq 'NORMARC'){
4502         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('773', '0', 'Host Biblionumber', 'Host Biblionumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4503         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('773', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4504         print "Upgrade to $DBversion done (Add 773 subfield 9 and 0 to default framework)\n";
4505         SetVersion ($DBversion);
4506     } elsif (C4::Context->preference("marcflavour") eq 'UNIMARC'){
4507         $dbh->do("INSERT INTO `marc_subfield_structure` (`tagfield`, `tagsubfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `kohafield`, `tab`, `authorised_value` , `authtypecode`, `value_builder`, `isurl`, `hidden`, `frameworkcode`, `seealso`, `link`, `defaultvalue`) VALUES ('461', '9', 'Host Itemnumber', 'Host Itemnumber', 0, 0, NULL, 7, NULL, NULL, '', NULL, -6, '', '', '', NULL)");
4508         print "Upgrade to $DBversion done (Add 461 subfield 9 to default framework)\n";
4509         SetVersion ($DBversion);
4510     }
4511 }
4512
4513 $DBversion = "3.05.00.018";
4514 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4515     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OpacNavBottom','','Links after OpacNav links','70|10','Textarea')");
4516     print "Upgrade to $DBversion done (add OpacNavBottom syspref (enh 6825): if appropriate, you can split OpacNav into OpacNav and OpacNavBottom)\n";
4517     SetVersion($DBversion);
4518 }
4519
4520 $DBversion = "3.05.00.019";
4521 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4522     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4523     $dbh->do("UPDATE itemtypes SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4524     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book.png' WHERE imageurl = 'vokal/BOOK.png'");
4525     $dbh->do("UPDATE authorised_values SET imageurl = 'vokal/Book-32px.png' WHERE imageurl = 'vokal/BOOK-32px.png'");
4526     print "Upgrade to $DBversion done (remove duplicate VOKAL Book icons, bug 6862)\n";
4527     SetVersion($DBversion);
4528 }
4529
4530 $DBversion = "3.05.00.020";
4531 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4532     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('AcqViewBaskets','user','user|branch|all','Define which baskets a user is allowed to view: his own only, any within his branch or all','Choice')");
4533     print "Upgrade to $DBversion done (Add syspref AcqViewBaskets)\n";
4534     SetVersion($DBversion);
4535 }
4536
4537 $DBversion = "3.05.00.021";
4538 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4539     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN display_checkout TINYINT(1) NOT NULL DEFAULT '0';");
4540     print "Upgrade to $DBversion done (Added a display_checkout field in borrower_attribute_types table)\n";
4541     SetVersion($DBversion);
4542 }
4543
4544 $DBversion = "3.05.00.022";
4545 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4546     $dbh->do("CREATE TABLE need_merge_authorities (id int NOT NULL auto_increment PRIMARY KEY, authid bigint NOT NULL, done tinyint DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8");
4547     print "Upgrade to $DBversion done (6094: Fixing ModAuthority problems, add a need_merge_authorities table)\n";
4548     SetVersion($DBversion);
4549 }
4550
4551 $DBversion = "3.05.00.023";
4552 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4553     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowRecentComments',0,'If ON a link to recent comments will appear in the OPAC masthead',NULL,'YesNo');");
4554     print "Upgrade to $DBversion done (Add syspref OpacShowRecentComments. When the preference is turned on a link to recent comments will appear in the OPAC masthead. )\n";
4555     SetVersion($DBversion);
4556 }
4557
4558 $DBversion = "3.06.00.000";
4559 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4560     print "Upgrade to $DBversion done Koha 3.6.0 release \n";
4561     SetVersion ($DBversion);
4562 }
4563
4564 $DBversion = "3.07.00.001";
4565 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4566     my $borrowers = $dbh->selectcol_arrayref( "SELECT borrowernumber from borrowers where debarred =1;", { Columns => [1] } );
4567     $dbh->do("ALTER TABLE borrowers MODIFY debarred DATE DEFAULT NULL;");
4568     $dbh->do( "UPDATE borrowers set debarred='9999-12-31' where borrowernumber IN (" . join( ",", @$borrowers ) . ");" ) if ($borrowers and scalar(@$borrowers)>0);
4569     $dbh->do("ALTER TABLE borrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4570     $dbh->do("ALTER TABLE deletedborrowers MODIFY debarred DATE DEFAULT NULL;");
4571     $dbh->do("ALTER TABLE deletedborrowers ADD COLUMN debarredcomment VARCHAR(255) DEFAULT NULL AFTER debarred;");
4572     print "Upgrade done (Change borrowers.debarred into Date )\n";
4573     SetVersion($DBversion);
4574 }
4575
4576 $DBversion = "3.07.00.002";
4577 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4578     sanitize_zero_date('borrowers', 'debarred');
4579     print "Setting NULL to debarred where 0000-00-00 is stored (bug 7272)\n";
4580     SetVersion($DBversion);
4581 }
4582
4583 $DBversion = "3.07.00.003";
4584 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4585     $dbh->do(" UPDATE `message_attributes` SET message_name='Item_Due' WHERE message_name='Item_DUE'");
4586     print "Updating message_name in message_attributes\n";
4587     SetVersion($DBversion);
4588 }
4589
4590 $DBversion = "3.07.00.004";
4591 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4592     $dbh->do("ALTER TABLE  `suggestions` ADD  `patronreason` TEXT NULL AFTER  `reason`");
4593     print "Upgrade to $DBversion done (Add column to suggestions table to store patrons' reasons for submitting a suggestion. )\n";
4594     SetVersion($DBversion);
4595 }
4596
4597 $DBversion = "3.07.00.005";
4598 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4599     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('BorrowerUnwantedField','','Name the fields you don''t need to store for a patron''s account',NULL,'free')");
4600     print "Upgrade to $DBversion done (BorrowerUnwantedField syspref)\n";
4601     SetVersion ($DBversion);
4602 }
4603
4604 $DBversion = "3.07.00.006";
4605 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4606     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('CircAutoPrintQuickSlip', '1', 'Choose what should happen when an empty barcode field is submitted in circulation: Display a print quick slip window or Clear the screen.',NULL,'YesNo');");
4607     print "Upgrade to $DBversion done (Add syspref CircAutoPrintQuickSlip to control what should happen when an empty barcode field is submitted in circulation: Display a print quick slip window (default value, 3.6 behaviour) or clear the screen (previous 3.6 behaviour). )\n";
4608     SetVersion($DBversion);
4609 }
4610
4611 $DBversion = "3.07.00.007";
4612 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4613     $dbh->do("ALTER TABLE items MODIFY materials text;");
4614     print "Upgrade to $DBversion done alter items.material from varchar(10) to text \n";
4615     SetVersion($DBversion);
4616 }
4617
4618 $DBversion = '3.07.00.008';
4619 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4620     if (C4::Context->preference("marcflavour") eq 'MARC21') {
4621         if (C4::Context->preference("opaclanguages") eq "de") {
4622             $dbh->do("INSERT INTO `marc_tag_structure` (`tagfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `authorised_value`, `frameworkcode`) VALUES ('545', 'Fußnote zu biografischen oder historischen Daten', 'Fußnote zu biografischen oder historischen Daten', 1, 0, NULL, '');");
4623         } else {
4624             $dbh->do("INSERT INTO `marc_tag_structure` (`tagfield`, `liblibrarian`, `libopac`, `repeatable`, `mandatory`, `authorised_value`, `frameworkcode`) VALUES ('545', 'BIOGRAPHICAL OR HISTORICAL DATA', 'BIOGRAPHICAL OR HISTORICAL DATA', 1, 0, NULL, '');");
4625         }
4626     }
4627     print "Upgrade to $DBversion done (add MARC21 field 545 to framework)\n";
4628     SetVersion ($DBversion);
4629 }
4630
4631 $DBversion = "3.07.00.009";
4632 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4633     $dbh->do("ALTER TABLE `aqorders` ADD COLUMN `claims_count` INT(11)  DEFAULT 0, ADD COLUMN `claimed_date` DATE  DEFAULT NULL AFTER `claims_count`");
4634     print "Upgrade to $DBversion done (Add claims_count and claimed_date fields in aqorders table)\n";
4635     SetVersion($DBversion);
4636 }
4637
4638 $DBversion = "3.07.00.010";
4639 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4640     $dbh->do(
4641         q|CREATE TABLE `biblioimages` (
4642           `imagenumber` int(11) NOT NULL AUTO_INCREMENT,
4643           `biblionumber` int(11) NOT NULL,
4644           `mimetype` varchar(15) NOT NULL,
4645           `imagefile` mediumblob NOT NULL,
4646           `thumbnail` mediumblob NOT NULL,
4647           PRIMARY KEY (`imagenumber`),
4648           CONSTRAINT `bibliocoverimage_fk1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
4649           ) ENGINE=InnoDB DEFAULT CHARSET=utf8|
4650     );
4651     $dbh->do(
4652         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACLocalCoverImages','0','Display local cover images on OPAC search and details pages.','1','YesNo')|
4653         );
4654     $dbh->do(
4655         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('LocalCoverImages','0','Display local cover images on intranet search and details pages.','1','YesNo')|
4656         );
4657     $dbh->do(
4658         q|INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowMultipleCovers','0','Allow multiple cover images to be attached to each bibliographic record.','1','YesNo')|
4659     );
4660     $dbh->do(
4661         q|INSERT INTO permissions (module_bit, code, description) VALUES (13, 'upload_local_cover_images', 'Upload local cover images')|
4662     );
4663     print "Upgrade to $DBversion done (Added support for local cover images)\n";
4664     SetVersion($DBversion);
4665 }
4666
4667 $DBversion = "3.07.00.011";
4668 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4669     $dbh->do(<<ENDOFRENEWAL);
4670     INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('BorrowerRenewalPeriodBase', 'now', 'Set whether the borrower renewal date should be counted from the dateexpiry or from the current date ','dateexpiry|now','Choice');
4671 ENDOFRENEWAL
4672     print "Upgrade to $DBversion done (Added a system preference to allow renewal of Patron account either from todays date or from existing expiry date in the patrons account.)\n";
4673     SetVersion($DBversion);
4674 }
4675
4676 $DBversion = "3.07.00.012";
4677 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4678     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowItemsOnHoldCheckout',0,'Do not generate RESERVE_WAITING and RESERVED warning when checking out items reserved to someone else. This allows self checkouts for those items.','','YesNo')");
4679     print "Upgrade to $DBversion add 'AllowItemsOnHoldCheckout' syspref \n";
4680     SetVersion ($DBversion);
4681 }
4682
4683 $DBversion = "3.07.00.013";
4684 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4685     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacExportOptions','bibtex|dc|marcxml|marc8|utf8|marcstd|mods|ris','Define available export options on OPAC detail page.','','free');");
4686     print "Upgrade to $DBversion done (Bug 7345: Add system preference OpacExportOptions.)\n";
4687     SetVersion ($DBversion);
4688 }
4689
4690 $DBversion = "3.07.00.014";
4691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4692     print "RELTERMS category available for English-, French-, and Spanish-language relator terms. They are not loaded during upgrade but can be easily inserted using the provided marc21_relatorterms.sql SQL script (MARC21 only, and currently available for en, es, and fr only).\n";
4693     SetVersion($DBversion);
4694 }
4695
4696 $DBversion = "3.07.00.015";
4697 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4698     my $sth = $dbh->prepare(q|
4699         SELECT COUNT(*) FROM marc_subfield_structure where kohafield="biblioitems.editionstatement"
4700         |);
4701     $sth->execute;
4702     my $already_exists = $sth->fetchrow;
4703     if ( not $already_exists ) {
4704         my $field = C4::Context->preference("marcflavour") eq "UNIMARC" ? "205" : "250";
4705         my $subfield = "a";
4706         my $sth = $dbh->prepare( q|
4707             UPDATE marc_subfield_structure SET kohafield = "biblioitems.editionstatement"
4708             WHERE tagfield = ? AND tagsubfield = ?
4709         |);
4710         $sth->execute( $field, $subfield );
4711         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement.)\n";
4712     } else {
4713         print "Upgrade to $DBversion done (Added a mapping for biblioitems.editionstatement (already exists, nothing to do).)\n";
4714     }
4715     SetVersion($DBversion);
4716 }
4717
4718 $DBversion = "3.07.00.016";
4719 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4720     $dbh->do("ALTER TABLE items ADD KEY `itemcallnumber` (itemcallnumber)");
4721     print "Upgrade to $DBversion done (Added index on items.itemcallnumber)\n";
4722     SetVersion($DBversion);
4723 }
4724
4725 $DBversion = "3.07.00.017";
4726 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4727     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('TransferWhenCancelAllWaitingHolds','0','Transfer items when cancelling all waiting holds',NULL,'YesNo')");
4728     print "Upgrade to $DBversion done (Add sysprefs to control transfer when cancel all waiting holds)\n";
4729     SetVersion ($DBversion);
4730 }
4731
4732 $DBversion = "3.07.00.018";
4733 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4734     $dbh->do("CREATE TABLE pending_offline_operations ( operationid int(11) NOT NULL AUTO_INCREMENT, userid varchar(30) NOT NULL, branchcode varchar(10) NOT NULL, timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, action varchar(10) NOT NULL, barcode varchar(20) NOT NULL, cardnumber varchar(16) DEFAULT NULL, PRIMARY KEY (operationid) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
4735     print "Upgrade to $DBversion done ( adding offline operations table )\n";
4736     SetVersion($DBversion);
4737 }
4738
4739 $DBversion = "3.07.00.019";
4740 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4741     $dbh->do(" UPDATE `systempreferences` SET  `value` =  'none', `options` =  'none|full|first|surname|firstandinitial|username', `explanation` =  'Choose how a commenter''s identity is presented alongside comments in the OPAC', `type` =  'Choice' WHERE  `systempreferences`.`variable` =  'ShowReviewer' AND `systempreferences`.`variable` = 0");
4742     $dbh->do(" UPDATE `systempreferences` SET  `value` =  'full', `options` =  'none|full|first|surname|firstandinitial|username', `explanation` =  'Choose how a commenter''s identity is presented alongside comments in the OPAC', `type` =  'Choice' WHERE  `systempreferences`.`variable` =  'ShowReviewer' AND `systempreferences`.`variable` = 1");
4743     print "Upgrade to $DBversion done ( Adding additional options for the display of commenter's identity in the OPAC: Full name, first name, last name, first name and last name first initial, username, or no information)\n";
4744     SetVersion($DBversion);
4745 }
4746
4747 $DBversion = "3.07.00.020";
4748 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4749     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACpatronimages',0,'Enable patron images in the OPAC',NULL,'YesNo');");
4750     print "Upgrade to $DBversion done (Bug 3516: Add the option to show patron images in the OPAC.)\n";
4751     SetVersion($DBversion);
4752 }
4753
4754 $DBversion = "3.07.00.021";
4755 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4756     $dbh->do(
4757     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerModule','Default','Chooses which linker module to use (see documentation).','Default|FirstMatchLastMatch','Choice');"
4758     );
4759     $dbh->do(
4760     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerOptions','','A pipe-separated list of options for the linker.','','free');"
4761     );
4762     $dbh->do(
4763     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerRelink',1,'If ON the authority linker will relink headings that have previously been linked every time it runs.',NULL,'YesNo');"
4764     );
4765     $dbh->do(
4766     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('LinkerKeepStale',0,'If ON the authority linker will keep existing authority links for headings where it is unable to find a match.',NULL,'YesNo');"
4767     );
4768     $dbh->do(
4769     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AutoCreateAuthorities',0,'Automatically create authorities that do not exist when cataloging records.',NULL,'YesNo');"
4770     );
4771     $dbh->do(
4772     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('CatalogModuleRelink',0,'If OFF the linker will never replace the authids that are set in the cataloging module.',NULL,'YesNo');"
4773     );
4774     print "Upgrade to $DBversion done (Enhancement 7284, improved authority matching, see http://wiki.koha-community.org/wiki/Bug7284_authority_matching_improvement wiki page for configuration update needed)\n";
4775     SetVersion($DBversion);
4776 }
4777
4778 $DBversion = "3.07.00.022";
4779 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4780     $dbh->do("DELETE FROM reviews WHERE biblionumber NOT IN (SELECT biblionumber from biblio)");
4781     $dbh->do("UPDATE reviews SET borrowernumber = NULL WHERE borrowernumber NOT IN (SELECT borrowernumber FROM borrowers)");
4782     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_2 FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE");
4783     $dbh->do("ALTER TABLE reviews ADD CONSTRAINT reviews_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber ) ON UPDATE CASCADE ON DELETE SET NULL");
4784     print "Upgrade to $DBversion done (Bug 7493 - Add constraint linking OPAC comment biblionumber to biblio, OPAC comment borrowernumber to borrowers.)\n";
4785     SetVersion($DBversion);
4786 }
4787
4788 $DBversion = "3.07.00.023";
4789 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4790     $dbh->do("ALTER TABLE `message_transports` DROP FOREIGN KEY `message_transports_ibfk_3`");
4791     $dbh->do("ALTER TABLE `letter` DROP PRIMARY KEY");
4792     $dbh->do("ALTER TABLE `letter` ADD `branchcode` varchar(10) default NULL AFTER `code`");
4793     $dbh->do("ALTER TABLE `letter` ADD PRIMARY KEY  (`module`,`code`, `branchcode`)");
4794     $dbh->do("ALTER TABLE `message_transports` ADD `branchcode` varchar(10) NOT NULL default ''");
4795     $dbh->do("ALTER TABLE `message_transports` ADD CONSTRAINT `message_transports_ibfk_3` FOREIGN KEY (`letter_module`, `letter_code`, `branchcode`) REFERENCES `letter` (`module`, `code`, `branchcode`) ON DELETE CASCADE ON UPDATE CASCADE");
4796     $dbh->do("ALTER TABLE `letter` ADD `is_html` tinyint(1) default 0 AFTER `name`");
4797
4798     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4799               VALUES ('circulation','ISSUESLIP','Issue Slip','Issue Slip', '<h3><<branches.branchname>></h3>
4800 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4801 (<<borrowers.cardnumber>>) <br />
4802
4803 <<today>><br />
4804
4805 <h4>Checked Out</h4>
4806 <checkedout>
4807 <p>
4808 <<biblio.title>> <br />
4809 Barcode: <<items.barcode>><br />
4810 Date due: <<issues.date_due>><br />
4811 </p>
4812 </checkedout>
4813
4814 <h4>Overdues</h4>
4815 <overdue>
4816 <p>
4817 <<biblio.title>> <br />
4818 Barcode: <<items.barcode>><br />
4819 Date due: <<issues.date_due>><br />
4820 </p>
4821 </overdue>
4822
4823 <hr>
4824
4825 <h4 style=\"text-align: center; font-style:italic;\">News</h4>
4826 <news>
4827 <div class=\"newsitem\">
4828 <h5 style=\"margin-bottom: 1px; margin-top: 1px\"><b><<opac_news.title>></b></h5>
4829 <p style=\"margin-bottom: 1px; margin-top: 1px\"><<opac_news.new>></p>
4830 <p class=\"newsfooter\" style=\"font-size: 8pt; font-style:italic; margin-bottom: 1px; margin-top: 1px\">Posted on <<opac_news.timestamp>></p>
4831 <hr />
4832 </div>
4833 </news>', 1)");
4834     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4835               VALUES ('circulation','ISSUEQSLIP','Issue Quick Slip','Issue Quick Slip', '<h3><<branches.branchname>></h3>
4836 Checked out to <<borrowers.title>> <<borrowers.firstname>> <<borrowers.initials>> <<borrowers.surname>> <br />
4837 (<<borrowers.cardnumber>>) <br />
4838
4839 <<today>><br />
4840
4841 <h4>Checked Out Today</h4>
4842 <checkedout>
4843 <p>
4844 <<biblio.title>> <br />
4845 Barcode: <<items.barcode>><br />
4846 Date due: <<issues.date_due>><br />
4847 </p>
4848 </checkedout>', 1)");
4849     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4850               VALUES ('circulation','RESERVESLIP','Reserve Slip','Reserve Slip', '<h5>Date: <<today>></h5>
4851
4852 <h3> Transfer to/Hold in <<branches.branchname>></h3>
4853
4854 <h3><<borrowers.surname>>, <<borrowers.firstname>></h3>
4855
4856 <ul>
4857     <li><<borrowers.cardnumber>></li>
4858     <li><<borrowers.phone>></li>
4859     <li> <<borrowers.address>><br />
4860          <<borrowers.address2>><br />
4861          <<borrowers.city >>  <<borrowers.zipcode>>
4862     </li>
4863     <li><<borrowers.email>></li>
4864 </ul>
4865 <br />
4866 <h3>ITEM ON HOLD</h3>
4867 <h4><<biblio.title>></h4>
4868 <h5><<biblio.author>></h5>
4869 <ul>
4870    <li><<items.barcode>></li>
4871    <li><<items.itemcallnumber>></li>
4872    <li><<reserves.waitingdate>></li>
4873 </ul>
4874 <p>Notes:
4875 <pre><<reserves.reservenotes>></pre>
4876 </p>', 1)");
4877     $dbh->do("INSERT INTO `letter` (module, code, name, title, content, is_html)
4878               VALUES ('circulation','TRANSFERSLIP','Transfer Slip','Transfer Slip', '<h5>Date: <<today>></h5>
4879 <h3>Transfer to <<branches.branchname>></h3>
4880
4881 <h3>ITEM</h3>
4882 <h4><<biblio.title>></h4>
4883 <h5><<biblio.author>></h5>
4884 <ul>
4885    <li><<items.barcode>></li>
4886    <li><<items.itemcallnumber>></li>
4887 </ul>', 1)");
4888
4889     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NoticeCSS','','Notices CSS url.',NULL,'free')");
4890     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('SlipCSS','','Slips CSS url.',NULL,'free')");
4891
4892     $dbh->do("UPDATE `letter` SET content = replace(content, '<<title>>', '<<biblio.title>>') WHERE code = 'HOLDPLACED'");
4893
4894     print "Upgrade to $DBversion done (Add branchcode and is_html to letter table; Default ISSUESLIP, RESERVESLIP and TRANSFERSLIP letters; Add NoticeCSS and SlipCSS sysprefs)\n";
4895     SetVersion($DBversion);
4896 }
4897
4898 $DBversion = "3.07.00.024";
4899 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4900     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ExpireReservesMaxPickUpDelayCharge', '0', NULL , 'If ExpireReservesMaxPickUpDelay is enabled, and this field has a non-zero value, than a borrower whose waiting hold has expired will be charged this amount.',  'free')");
4901     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ExpireReservesMaxPickUpDelay', '0', '', 'Enabling this allows holds to expire automatically if they have not been picked by within the time period specified in ReservesMaxPickUpDelay', 'YesNo')");
4902     print "Upgrade to $DBversion done (Added system preference ExpireReservesMaxPickUpDelay, system preference ExpireReservesMaxPickUpDelayCharge, add reseves.charge_if_expired)\n";
4903 }
4904
4905 $DBversion = "3.07.00.025";
4906 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4907     if (TableExists('bibliocoverimage')) {
4908         $dbh->do( q|DROP TABLE bibliocoverimage;| );
4909         $dbh->do(
4910             q|CREATE TABLE biblioimages (
4911               imagenumber int(11) NOT NULL AUTO_INCREMENT,
4912               biblionumber int(11) NOT NULL,
4913               mimetype varchar(15) NOT NULL,
4914               imagefile mediumblob NOT NULL,
4915               thumbnail mediumblob NOT NULL,
4916               PRIMARY KEY (imagenumber),
4917               CONSTRAINT bibliocoverimage_fk1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
4918               ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
4919         );
4920     }
4921     print "Upgrade to $DBversion done (Correct table name for local cover images if needed. )\n";
4922     SetVersion($DBversion);
4923 }
4924
4925 $DBversion = "3.07.00.026";
4926 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
4927     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('CalendarFirstDayOfWeek','Sunday','Select the first day of week to use in the calendar.','Sunday|Monday','Choice');");
4928     print "Upgrade to $DBversion done (Add syspref CalendarFirstDayOfWeek used to select the first day of week to use in the calendar. )\n";
4929     SetVersion($DBversion);
4930 }
4931
4932 $DBversion = "3.07.00.027";
4933 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4934     $dbh->do(q{INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RoutingListNote','','Define a note to be shown on all routing lists','70|10','Textarea');});
4935     print "Upgrade to $DBversion done (Added system preference RoutingListNote for adding a general note to all routing lists.)\n";
4936     SetVersion($DBversion);
4937 }
4938
4939 $DBversion = "3.07.00.028";
4940 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4941     $dbh->do(qq{
4942     INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('AllowPKIAuth','None','Use the field from a client-side SSL certificate to look a user in the Koha database','None|Common Name|emailAddress','Choice');
4943     });
4944     print "Upgrade to $DBversion done (Bug 6296 New System preference AllowPKIAuth)\n";
4945 }
4946
4947 $DBversion = "3.07.00.029";
4948 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
4949     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_descriptions`;});
4950     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_mappings`;});
4951     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets_biblios`;});
4952     $dbh->do(q{DROP TABLE IF EXISTS `oai_sets`;});
4953
4954     $dbh->do(q{
4955         CREATE TABLE `oai_sets` (
4956           `id` int(11) NOT NULL auto_increment,
4957           `spec` varchar(80) NOT NULL UNIQUE,
4958           `name` varchar(80) NOT NULL,
4959           PRIMARY KEY (`id`)
4960         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4961     });
4962
4963     $dbh->do(q{
4964         CREATE TABLE `oai_sets_descriptions` (
4965           `set_id` int(11) NOT NULL,
4966           `description` varchar(255) NOT NULL,
4967           CONSTRAINT `oai_sets_descriptions_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4968         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4969     });
4970
4971     $dbh->do(q{
4972         CREATE TABLE `oai_sets_mappings` (
4973           `set_id` int(11) NOT NULL,
4974           `marcfield` char(3) NOT NULL,
4975           `marcsubfield` char(1) NOT NULL,
4976           `marcvalue` varchar(80) NOT NULL,
4977           CONSTRAINT `oai_sets_mappings_ibfk_1` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4978         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4979     });
4980
4981     $dbh->do(q{
4982         CREATE TABLE `oai_sets_biblios` (
4983           `biblionumber` int(11) NOT NULL,
4984           `set_id` int(11) NOT NULL,
4985           PRIMARY KEY (`biblionumber`, `set_id`),
4986           CONSTRAINT `oai_sets_biblios_ibfk_1` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
4987           CONSTRAINT `oai_sets_biblios_ibfk_2` FOREIGN KEY (`set_id`) REFERENCES `oai_sets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
4988         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4989     });
4990
4991     $dbh->do(q{
4992         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OAI-PMH:AutoUpdateSets','0','Automatically update OAI sets when a bibliographic record is created or updated','','YesNo');
4993     });
4994
4995     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
4996     SetVersion($DBversion);
4997 }
4998
4999 $DBversion = "3.07.00.030";
5000 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5001     $dbh->do("ALTER TABLE default_circ_rules ADD
5002             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5003     $dbh->do("ALTER TABLE branch_item_rules ADD
5004             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5005     $dbh->do("ALTER TABLE default_branch_circ_rules ADD
5006             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5007     $dbh->do("ALTER TABLE default_branch_item_rules ADD
5008             COLUMN `returnbranch` varchar(15) default NULL AFTER `holdallowed`");
5009     # set the default rule to the current value of HomeOrHoldingBranchReturn (default to 'homebranch' if need be)
5010     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') || 'homebranch';
5011     $dbh->do("UPDATE default_circ_rules SET returnbranch = '$homeorholdingbranchreturn'");
5012     print "Upgrade to $DBversion done (Atomic update for OAI-PMH sets management)\n";
5013     SetVersion($DBversion);
5014 }
5015
5016 $DBversion = "3.07.00.031";
5017 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5018     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UseICU', '1', 'Tell Koha if ICU indexing is in use for Zebra or not.','1','YesNo')");
5019     print "Upgrade to $DBversion done (Add syspref to tell Koha if ICU indexing is in use for Zebra or not.)\n";
5020     SetVersion ($DBversion);
5021 }
5022
5023 $DBversion = "3.07.00.032";
5024 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5025     $dbh->do("ALTER TABLE virtualshelves MODIFY COLUMN owner int"); #should have been int already (fk to borrowers)
5026     $dbh->do("UPDATE virtualshelves vi LEFT JOIN borrowers bo ON bo.borrowernumber=vi.owner SET vi.owner=NULL where bo.borrowernumber IS NULL"); #before adding the constraint on borrowernumber, we need to get rid of deleted owners
5027     $dbh->do("DELETE FROM virtualshelves WHERE owner IS NULL and category=1"); #delete private lists without owner (cascades to shelfcontents)
5028     $dbh->do("ALTER TABLE virtualshelves ADD COLUMN allow_add tinyint(1) DEFAULT 0, ADD COLUMN allow_delete_own tinyint(1) DEFAULT 1, ADD COLUMN allow_delete_other tinyint(1) DEFAULT 0, ADD CONSTRAINT `virtualshelves_ibfk_1` FOREIGN KEY (`owner`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL");
5029     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=1");
5030     $dbh->do("UPDATE virtualshelves SET allow_add=0, allow_delete_own=1, allow_delete_other=0 WHERE category=2");
5031     $dbh->do("UPDATE virtualshelves SET allow_add=1, allow_delete_own=1, allow_delete_other=1 WHERE category=3");
5032     $dbh->do("UPDATE virtualshelves SET category=2 WHERE category=3");
5033
5034     $dbh->do("ALTER TABLE virtualshelfcontents ADD COLUMN borrowernumber int, ADD CONSTRAINT `shelfcontents_ibfk_3` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL");
5035     $dbh->do("UPDATE virtualshelfcontents co LEFT JOIN virtualshelves sh USING (shelfnumber) SET co.borrowernumber=sh.owner");
5036
5037     $dbh->do("CREATE TABLE virtualshelfshares
5038     (id int AUTO_INCREMENT PRIMARY KEY, shelfnumber int NOT NULL,
5039     borrowernumber int, invitekey varchar(10), sharedate datetime,
5040     CONSTRAINT `virtualshelfshares_ibfk_1` FOREIGN KEY (`shelfnumber`) REFERENCES `virtualshelves` (`shelfnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
5041         CONSTRAINT `virtualshelfshares_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE SET NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5042
5043     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowPublicListCreation',1,'If set, allows opac users to create public lists',NULL,'YesNo');");
5044     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAllowSharingPrivateLists',0,'If set, allows opac users to share private lists with other patrons',NULL,'YesNo');");
5045
5046     print "Upgrade to $DBversion done (BZ7310: Improving list permissions)\n";
5047     SetVersion($DBversion);
5048 }
5049
5050 $DBversion = "3.07.00.033";
5051 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5052     $dbh->do("ALTER TABLE branches ADD opac_info text;");
5053     print "Upgrade to $DBversion done add opac_info to branches \n";
5054     SetVersion($DBversion);
5055 }
5056
5057 $DBversion = "3.07.00.034";
5058 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5059     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN category_code VARCHAR(10) NULL DEFAULT NULL AFTER `display_checkout`");
5060     $dbh->do("ALTER TABLE borrower_attribute_types ADD COLUMN class VARCHAR(255)  NOT NULL DEFAULT '' AFTER `category_code`");
5061     $dbh->do("ALTER TABLE borrower_attribute_types ADD CONSTRAINT category_code_fk FOREIGN KEY (category_code) REFERENCES categories(categorycode)");
5062     print "Upgrade to $DBversion done (New fields category_code and class in borrower_attribute_types table)\n";
5063     SetVersion($DBversion);
5064 }
5065
5066 $DBversion = "3.07.00.035";
5067 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5068     $dbh->do("ALTER TABLE issues CHANGE date_due date_due datetime");
5069     $dbh->do("UPDATE issues SET date_due = CONCAT(SUBSTR(date_due,1,11),'23:59:00')");
5070     $dbh->do("ALTER TABLE issues CHANGE returndate returndate datetime");
5071     $dbh->do("ALTER TABLE issues CHANGE lastreneweddate lastreneweddate datetime");
5072     $dbh->do("ALTER TABLE issues CHANGE issuedate issuedate datetime");
5073     $dbh->do("ALTER TABLE old_issues CHANGE date_due date_due datetime");
5074     $dbh->do("ALTER TABLE old_issues CHANGE returndate returndate datetime");
5075     $dbh->do("ALTER TABLE old_issues CHANGE lastreneweddate lastreneweddate datetime");
5076     $dbh->do("ALTER TABLE old_issues CHANGE issuedate issuedate datetime");
5077     $dbh->do("UPDATE accountlines SET description = CONCAT(description,' 23:59') WHERE accounttype='F' OR accounttype='FU'"); #BUG-8253
5078     print "Upgrade to $DBversion done (Setting up issues and accountlines tables for hourly loans)\n";
5079     SetVersion($DBversion);
5080 }
5081
5082 $DBversion = "3.07.00.036";
5083 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5084     $dbh->do(qq{
5085        ALTER TABLE z3950servers ADD timeout INT( 11 ) NOT NULL DEFAULT '0' AFTER syntax;
5086     });
5087     print "Upgrade to $DBversion done (New timeout field in z3950servers)\n";
5088 }
5089
5090 $DBversion = "3.07.00.037";
5091 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5092     $dbh->do("
5093        ALTER TABLE  `marc_subfield_structure` ADD  `maxlength` INT( 4 ) NOT NULL DEFAULT  '9999';
5094        ");
5095        $dbh->do("
5096        UPDATE `marc_subfield_structure` SET maxlength=24 WHERE tagfield='000';
5097        ");
5098        $dbh->do("
5099        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='MARC21','40','9999') WHERE tagfield='008';
5100        ");
5101        $dbh->do("
5102        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='NORMARC','40','9999') WHERE tagfield='008';
5103        ");
5104        $dbh->do("
5105        UPDATE marc_subfield_structure SET maxlength = IF ((SELECT value FROM systempreferences WHERE variable = 'marcflavour')='UNIMARC','36','9999') WHERE tagfield='100';
5106        ");
5107     print "Upgrade to $DBversion done (Add new field maxlength to marc_subfield_structure)\n";
5108     SetVersion($DBversion);
5109 }
5110
5111 $DBversion = "3.07.00.038";
5112 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5113     $dbh->do(qq{
5114         INSERT INTO systempreferences(variable,value,explanation,options,type)
5115         VALUES('UniqueItemFields', 'barcode', 'Space-separated list of fields that should be unique (used in acquisition module for item creation). Fields must be valid SQL column names of items table', '', 'Free')
5116     });
5117     print "Upgrade to $DBversion done (Added system preference 'UniqueItemFields')\n";
5118     SetVersion($DBversion);
5119 }
5120
5121 $DBversion = "3.07.00.039";
5122 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5123     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Babeltheque_url_js','','Url for Babeltheque javascript (e.g. http://www.babeltheque.com/bw_XX.js','','Free')} );
5124     $dbh->do( qq{CREATE TABLE IF NOT EXISTS social_data
5125       ( isbn VARCHAR(30),
5126         num_critics INT,
5127         num_critics_pro INT,
5128         num_quotations INT,
5129         num_videos INT,
5130         score_avg DECIMAL(5,2),
5131         num_scores INT,
5132         PRIMARY KEY  (isbn)
5133       ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5134     } );
5135     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('Babeltheque_url_update', '', 'Url for Babeltheque update (E.G. http://www.babeltheque.com/.../file.csv.bz2)', '', 'Free')} );
5136     print "Upgrade to $DBversion done (added syspref and table for babeltheque (Babeltheque_url_js, babeltheque))\n";
5137     SetVersion($DBversion);
5138 }
5139
5140 $DBversion = "3.07.00.040";
5141 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5142     $dbh->do( qq{INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('SocialNetworks','0','Enable/Disable social networks links in opac detail','','YesNo')} );
5143     print "Upgrade to $DBversion done (added syspref SocialNetworks, to display facebook/ggl+ and other buttons)\n";
5144     SetVersion($DBversion);
5145 }
5146
5147
5148
5149 $DBversion = "3.07.00.041";
5150 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5151     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('SubscriptionDuplicateDroppedInput','','','List of fields which must not be rewritten when a subscription is duplicated (Separated by pipe |)','Free')");
5152     print "Upgrade to $DBversion done (Add system preference SubscriptionDuplicateDroppedInput)\n";
5153     SetVersion($DBversion);
5154 }
5155
5156 $DBversion = "3.07.00.042";
5157 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5158     $dbh->do("ALTER TABLE reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5159     $dbh->do("ALTER TABLE old_reserves ADD suspend BOOLEAN NOT NULL DEFAULT 0");
5160
5161     $dbh->do("ALTER TABLE reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5162     $dbh->do("ALTER TABLE old_reserves ADD suspend_until DATETIME NULL DEFAULT NULL");
5163
5164     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AutoResumeSuspendedHolds',  '1', NULL ,  'Allow suspended holds to be automatically resumed by a set date.',  'YesNo')");
5165
5166     print "Upgrade to $DBversion done (Add suspend fields to reserves table, add syspref AutoResumeSuspendedHolds)\n";
5167     SetVersion ($DBversion);
5168 }
5169
5170 $DBversion = "3.07.00.043";
5171 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5172     my $countXSLTDetailsDisplay = 0;
5173     my $valueXSLTDetailsDisplay = "";
5174     my $valueXSLTResultsDisplay = "";
5175     my $valueOPACXSLTDetailsDisplay = "";
5176     my $valueOPACXSLTResultsDisplay = "";
5177     #the line below test if database comes from a BibLibre's branch
5178     $countXSLTDetailsDisplay = $dbh->do('SELECT 1 FROM systempreferences WHERE variable="IntranetXSLTDetailsDisplay"');
5179     if ($countXSLTDetailsDisplay > 0)
5180     {
5181         #the two lines below will only be used to update the databases from the BibLibre's branch. They will not affect the others
5182         $dbh->do(q|UPDATE systempreferences SET variable="XSLTDetailsDisplay" WHERE variable="IntranetXSLTDetailsDisplay"|);
5183         $dbh->do(q|UPDATE systempreferences SET variable="XSLTResultsDisplay" WHERE variable="IntranetXSLTResultsDisplay"|);
5184     }
5185     else
5186     {
5187         $valueXSLTDetailsDisplay = "default" if (C4::Context->preference("XSLTDetailsDisplay"));
5188         $valueXSLTResultsDisplay = "default" if (C4::Context->preference("XSLTResultsDisplay"));
5189         $valueOPACXSLTDetailsDisplay = "default" if (C4::Context->preference("OPACXSLTDetailsDisplay"));
5190         $valueOPACXSLTResultsDisplay = "default" if (C4::Context->preference("OPACXSLTResultsDisplay"));
5191         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTDetailsDisplay\" WHERE variable='XSLTDetailsDisplay'");
5192         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueXSLTResultsDisplay\" WHERE variable='XSLTResultsDisplay'");
5193         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTDetailsDisplay\" WHERE variable='OPACXSLTDetailsDisplay'");
5194         $dbh->do("UPDATE systempreferences SET type='Free', value=\"$valueOPACXSLTResultsDisplay\" WHERE variable='OPACXSLTResultsDisplay'");
5195     }
5196     print "Upgrade to $DBversion done (XSLT systempreference takes a path to file rather than YesNo)\n";
5197     SetVersion($DBversion);
5198 }
5199
5200 $DBversion = "3.07.00.044";
5201 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5202     $dbh->do("ALTER TABLE aqbooksellers ADD deliverytime INT DEFAULT NULL");
5203     print "Upgrade to $DBversion done (Add deliverytime field in aqbooksellers table)";
5204     SetVersion($DBversion);
5205 }
5206
5207 $DBversion = "3.07.00.045";
5208 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5209     $dbh->do("ALTER TABLE import_batches MODIFY COLUMN batch_type ENUM('batch','z3950','webservice') NOT NULL default 'batch'");
5210     print "Upgrade to $DBversion done (Add 'webservice' to batch_type enum)\n";
5211     SetVersion ($DBversion);
5212 }
5213
5214 $DBversion = "3.07.00.046";
5215 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5216     $dbh->do("ALTER TABLE issuingrules ADD COLUMN lengthunit varchar(10) DEFAULT 'days' AFTER issuelength");
5217     print "Upgrade to $DBversion done (Setting up issues tables for hourly loans (lengthunit fix))\n";
5218     SetVersion($DBversion);
5219 }
5220
5221 $DBversion = "3.07.00.047";
5222 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5223     $dbh->do("CREATE INDEX items_location ON items(location)");
5224     $dbh->do("CREATE INDEX items_ccode ON items(ccode)");
5225     print "Upgrade to $DBversion done (items_location and items_ccode indexes added for ShelfBrowser)\n";
5226     SetVersion($DBversion);
5227 }
5228
5229 $DBversion = "3.07.00.048";
5230 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5231     $dbh->do(
5232         q | CREATE TABLE ratings (
5233   borrowernumber int(11) NOT NULL,
5234   biblionumber int(11) NOT NULL,
5235   rating_value tinyint(1) NOT NULL,
5236   timestamp timestamp NOT NULL default CURRENT_TIMESTAMP,
5237   PRIMARY KEY  (borrowernumber,biblionumber),
5238   CONSTRAINT ratings_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
5239   CONSTRAINT ratings_ibfk_2 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
5240 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
5241     );
5242
5243     $dbh->do(
5244 q /INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacStarRatings','disable',NULL,'disable|all|details','Choice') /
5245     );
5246
5247     print
5248 "Upgrade to $DBversion done (Add 'ratings' table and 'OpacStarRatings' syspref)\n";
5249     SetVersion($DBversion);
5250 }
5251
5252 $DBversion = "3.07.00.049";
5253 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5254     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacBrowseResults','1','Disable/enable browsing and paging search results from the OPAC detail page.',NULL,'YesNo')");
5255     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5256     SetVersion($DBversion);
5257 }
5258
5259 $DBversion = "3.08.00.000";
5260 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5261     print "Upgrade to $DBversion done\n";
5262     SetVersion($DBversion);
5263 }
5264
5265 $DBversion = "3.09.00.001";
5266 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5267     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 1 ) NULL DEFAULT NULL");
5268     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table to allow NULL category_code)\n";
5269     SetVersion($DBversion);
5270 }
5271
5272 $DBversion = "3.09.00.002";
5273 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5274     $dbh->do("ALTER TABLE saved_sql
5275         ADD (
5276             cache_expiry INT NOT NULL DEFAULT 300,
5277             public BOOLEAN NOT NULL DEFAULT FALSE
5278         );
5279     ");
5280     print "Upgrade to $DBversion done (Added cache_expiry and public fields in
5281 saved_reports table.)\n";
5282     SetVersion($DBversion);
5283 }
5284
5285 $DBversion = "3.09.00.003";
5286 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5287     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SvcMaxReportRows','10','Maximum number of rows to return via the report web service.',NULL,'Integer');");
5288     print "Upgrade to $DBversion done (Added SvcMaxReportRows syspref)\n";
5289     SetVersion($DBversion);
5290 }
5291
5292 $DBversion = "3.09.00.004";
5293 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5294     $dbh->do("INSERT IGNORE INTO permissions (module_bit, code, description) VALUES('13', 'edit_patrons', 'Perform batch modifivation of patrons')");
5295     print "Upgrade to $DBversion done (Adds permissions flag for access to the patron modifications tool)\n";
5296     SetVersion($DBversion);
5297 }
5298
5299 $DBversion = "3.09.00.005";
5300 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5301     unless (TableExists('quotes')) {
5302         $dbh->do( qq{
5303             CREATE TABLE `quotes` (
5304               `id` int(11) NOT NULL AUTO_INCREMENT,
5305               `source` text DEFAULT NULL,
5306               `text` mediumtext NOT NULL,
5307               `timestamp` datetime NOT NULL,
5308               PRIMARY KEY (`id`)
5309             ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5310         });
5311     }
5312     $dbh->do( qq{
5313         INSERT IGNORE INTO permissions VALUES (13, "edit_quotes","Edit quotes for quote-of-the-day feature");
5314     });
5315     $dbh->do( qq{
5316         INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('QuoteOfTheDay',0,'Enable or disable display of Quote of the Day on the OPAC home page',NULL,'YesNo');
5317     });
5318     print "Upgrade to $DBversion done (Adding Quote of the Day Option.)\n";
5319     SetVersion($DBversion);
5320 }
5321
5322 $DBversion = "3.09.00.006";
5323 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5324     $dbh->do("UPDATE systempreferences SET
5325                 variable = 'OPACShowHoldQueueDetails',
5326                 value = CASE value WHEN '1' THEN 'priority' ELSE 'none' END,
5327                 options = 'none|priority|holds|holds_priority',
5328                 explanation = 'Show holds details in OPAC',
5329                 type = 'Choice'
5330               WHERE variable = 'OPACDisplayRequestPriority'");
5331     print "Upgrade to $DBversion done (Changed system preference OPACDisplayRequestPriority -> OPACShowHoldQueueDetails)\n";
5332     SetVersion($DBversion);
5333 }
5334
5335 $DBversion = "3.09.00.007";
5336 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5337     unless(C4::Context->preference('ReservesControlBranch')){
5338         $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type) VALUES ('ReservesControlBranch','PatronLibrary','ItemHomeLibrary|PatronLibrary','Branch checked for members reservations rights.','Choice')");
5339     }
5340     print "Upgrade to $DBversion done (Insert ReservesControlBranch systempreference into systempreferences table )\n";
5341     SetVersion($DBversion);
5342 }
5343
5344 $DBversion = "3.09.00.008";
5345 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5346     $dbh->do("ALTER TABLE sessions ADD PRIMARY KEY (id);");
5347     $dbh->do("ALTER TABLE sessions DROP INDEX `id`;");
5348     print "Upgrade to $DBversion done (redefine the field id as PRIMARY KEY of sessions)\n";
5349     SetVersion($DBversion);
5350 }
5351
5352 $DBversion = "3.09.00.009";
5353 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5354     $dbh->do("ALTER TABLE branches ADD PRIMARY KEY (branchcode);");
5355     $dbh->do("ALTER TABLE branches DROP INDEX branchcode;");
5356     print "Upgrade to $DBversion done (redefine the field branchcode as PRIMARY KEY of branches)\n";
5357     SetVersion ($DBversion);
5358 }
5359
5360 $DBversion = "3.09.00.010";
5361 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5362     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('IssueLostItem', 'alert', 'alert|confirm|nothing', 'Defines what should be done when an attempt is made to issue an item that has been marked as lost.', 'Choice')");
5363     print "Upgrade to $DBversion done (Add system preference issuelostitem ))\n";
5364     SetVersion($DBversion);
5365 }
5366
5367 $DBversion = "3.09.00.011";
5368 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5369     $dbh->do("ALTER TABLE `biblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5370     $dbh->do("CREATE INDEX `ean` ON biblioitems (`ean`) ");
5371     $dbh->do("ALTER TABLE `deletedbiblioitems` ADD `ean` VARCHAR( 13 ) NULL AFTER issn");
5372     if (C4::Context->preference("marcflavour") eq 'UNIMARC') {
5373          $dbh->do("UPDATE marc_subfield_structure SET kohafield='biblioitems.ean' WHERE tagfield='073' and tagsubfield='a'");
5374     }
5375     print "Upgrade to $DBversion done (Adding ean in biblioitems and deletedbiblioitems)\n";
5376     print "If you have records with ean, please run misc/batchRebuildBiblioTables.pl to populate bibliotems.ean\n" if (C4::Context->preference("marcflavour") eq 'UNIMARC');
5377     SetVersion($DBversion);
5378 }
5379
5380 $DBversion = "3.09.00.012";
5381 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5382     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsIntranet', '1', NULL , 'Allow holds to be suspended from the intranet.', 'YesNo')");
5383     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('SuspendHoldsOpac', '1', NULL , 'Allow holds to be suspended from the OPAC.', 'YesNo')");
5384     print "Upgrade to $DBversion done (Add system preference OpacBrowseResults ))\n";
5385     SetVersion($DBversion);
5386 }
5387
5388 $DBversion ="3.09.00.013";
5389 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5390     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('DefaultLanguageField008','','Fill in the default language for field 008 Range 35-37 (e.g. eng, nor, ger, see www.loc.gov/marc/languages/language_code.html)','','Free');");
5391     print "Upgrade to $DBversion done (Add system preference DefaultLanguageField008))\n";
5392     SetVersion($DBversion);
5393 }
5394
5395 $DBversion ="3.09.00.014";
5396 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5397     # add phone message transport type
5398     $dbh->do("INSERT INTO message_transport_types (message_transport_type) VALUES ('phone')");
5399
5400     # adds HOLD_PHONE and PREDUE_PHONE letters (as placeholders)
5401     $dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES
5402               ('reserves', 'HOLD_PHONE', 'Item Available for Pick-up (phone notice)', 'Item Available for Pick-up (phone notice)', 'Your item is available for pickup'),
5403               ('circulation', 'PREDUE_PHONE', 'Advance Notice of Item Due (phone notice)', 'Advance Notice of Item Due (phone notice)', 'Your item is due soon'),
5404               ('circulation', 'OVERDUE_PHONE', 'Overdue Notice (phone notice)', 'Overdue Notice (phone notice)', 'Your item is overdue')
5405               ");
5406
5407     # add phone notifications to patron message preferences options
5408     $dbh->do("INSERT INTO message_transports
5409              (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES
5410              (4, 'phone', 0, 'reserves', 'HOLD_PHONE'),
5411              (2, 'phone', 0, 'circulation', 'PREDUE_PHONE')
5412              ");
5413
5414     # add TalkingTechItivaPhoneNotification syspref
5415     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('TalkingTechItivaPhoneNotification',0,'If ON, enables Talking Tech I-tiva phone notifications',NULL,'YesNo');");
5416
5417     print "Upgrade done (Support for Talking Tech i-tiva phone notification system)\n";
5418     SetVersion($DBversion);
5419 }
5420
5421 $DBversion = "3.09.00.015";
5422 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5423     $dbh->do(qq{
5424         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('StatisticsFields','location|itype|ccode','Define Fields (from the items table) used for statistics members','location|itype|ccode','free')
5425     });
5426     print "Upgrade to $DBversion done (Add System preference StatisticsFields)\n";
5427     SetVersion($DBversion);
5428 }
5429
5430 $DBversion = "3.09.00.016";
5431 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5432     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('OPACShowBarcode','0','Show items barcode in holding tab','','YesNo')");
5433     print "Upgrade to $DBversion done (Add syspref OPACShowBarcode)\n";
5434     SetVersion ($DBversion);
5435 }
5436
5437 $DBversion = "3.09.00.017";
5438 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5439     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OpacNavRight', '', '70|10', 'Show the following HTML in the right hand column of the main page under the main login form', 'Textarea');");
5440     print "Upgrade to $DBversion done (Add customizable OpacNavRight region to the OPAC main page)\n";
5441     SetVersion ($DBversion);
5442 }
5443
5444 $DBversion = "3.09.00.018";
5445 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5446     $dbh->do("DROP TABLE IF EXISTS aqbudgetborrowers");
5447     $dbh->do("
5448         CREATE TABLE aqbudgetborrowers (
5449           budget_id int(11) NOT NULL,
5450           borrowernumber int(11) NOT NULL,
5451           PRIMARY KEY (budget_id, borrowernumber),
5452           CONSTRAINT aqbudgetborrowers_ibfk_1 FOREIGN KEY (budget_id)
5453             REFERENCES aqbudgets (budget_id)
5454             ON DELETE CASCADE ON UPDATE CASCADE,
5455           CONSTRAINT aqbudgetborrowers_ibfk_2 FOREIGN KEY (borrowernumber)
5456             REFERENCES borrowers (borrowernumber)
5457             ON DELETE CASCADE ON UPDATE CASCADE
5458         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5459     ");
5460     $dbh->do("
5461         INSERT INTO permissions (module_bit, code, description)
5462         VALUES (11, 'budget_manage_all', 'Manage all budgets')
5463     ");
5464     print "Upgrade to $DBversion done (Add aqbudgetborrowers table)\n";
5465     SetVersion($DBversion);
5466 }
5467
5468 $DBversion = "3.09.00.019";
5469 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5470     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACShowUnusedAuthorities','1','','Show authorities that are not being used in the OPAC.','YesNo')");
5471     print "Upgrade to $DBversion done (Add OPACShowUnusedAuthorities system preference)\n";
5472     SetVersion ($DBversion);
5473 }
5474
5475 $DBversion = "3.09.00.020";
5476 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5477     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('EnableBorrowerFiles','0','If enabled, allows librarians to upload and attach arbitrary files to a borrower record.','YesNo')");
5478     $dbh->do("
5479 CREATE TABLE IF NOT EXISTS borrower_files (
5480   file_id int(11) NOT NULL AUTO_INCREMENT,
5481   borrowernumber int(11) NOT NULL,
5482   file_name varchar(255) NOT NULL,
5483   file_type varchar(255) NOT NULL,
5484   file_description varchar(255) DEFAULT NULL,
5485   file_content longblob NOT NULL,
5486   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
5487   PRIMARY KEY (file_id),
5488   KEY borrowernumber (borrowernumber)
5489 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
5490     ");
5491     $dbh->do("ALTER TABLE borrower_files ADD CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE");
5492
5493     print "Upgrade to $DBversion done (Added borrow_files table, EnableBorrowerFiles syspref)\n";
5494     SetVersion($DBversion);
5495 }
5496
5497 $DBversion = "3.09.00.021";
5498 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5499     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UpdateTotalIssuesOnCirc','0','Whether to update the totalissues field in the biblio on each circ.',NULL,'YesNo');");
5500     print "Upgrade to $DBversion done (Add syspref UpdateTotalIssuesOnCirc)\n";
5501     SetVersion($DBversion);
5502 }
5503
5504 $DBversion = "3.09.00.022";
5505 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5506     $dbh->do("ALTER TABLE search_history MODIFY COLUMN query_cgi text NOT NULL");
5507     print "Upgrade to $DBversion done (Change search_history.query_cgi type to text. bug 5981)\n";
5508     SetVersion($DBversion);
5509 }
5510
5511 $DBversion = "3.09.00.023";
5512 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5513     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
5514     print "Upgrade to $DBversion done (Add system preference SearchEngine )\n";
5515     SetVersion($DBversion);
5516 }
5517
5518 $DBversion ="3.09.00.024";
5519 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5520     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('IntranetSlipPrinterJS','','Use this JavaScript for printing slips. Define at least function printThenClose(). For use e.g. with Firefox PlugIn jsPrintSetup, see http://jsprintsetup.mozdev.org/','','Free')");
5521     print "Upgrade to $DBversion done (Add system preference IntranetSlipPrinterJS))\n";
5522     SetVersion($DBversion);
5523 }
5524
5525 $DBversion = "3.09.00.025";
5526 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5527     $dbh->do('START TRANSACTION');
5528     $dbh->do('CREATE TABLE tmp_reserves AS SELECT * FROM old_reserves LIMIT 0');
5529     $dbh->do('ALTER TABLE tmp_reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5530     $dbh->do("
5531         INSERT INTO tmp_reserves (
5532           borrowernumber, reservedate, biblionumber,
5533           constrainttype, branchcode, notificationdate,
5534           reminderdate, cancellationdate, reservenotes,
5535           priority, found, timestamp, itemnumber,
5536           waitingdate, expirationdate, lowestPriority,
5537           suspend, suspend_until
5538         ) SELECT
5539           borrowernumber, reservedate, biblionumber,
5540           constrainttype, branchcode, notificationdate,
5541           reminderdate, cancellationdate, reservenotes,
5542           priority, found, timestamp, itemnumber,
5543           waitingdate, expirationdate, lowestPriority,
5544           suspend, suspend_until
5545         FROM old_reserves ORDER BY reservedate
5546     ");
5547     $dbh->do('SET @ai = ( SELECT MAX( reserve_id ) FROM tmp_reserves )');
5548     $dbh->do('TRUNCATE old_reserves');
5549     $dbh->do('ALTER TABLE old_reserves ADD reserve_id INT( 11 ) NOT NULL PRIMARY KEY FIRST');
5550     $dbh->do('INSERT INTO old_reserves SELECT * FROM tmp_reserves WHERE reserve_id <= @ai');
5551     $dbh->do("
5552         INSERT INTO tmp_reserves (
5553           borrowernumber, reservedate, biblionumber,
5554           constrainttype, branchcode, notificationdate,
5555           reminderdate, cancellationdate, reservenotes,
5556           priority, found, timestamp, itemnumber,
5557           waitingdate, expirationdate, lowestPriority,
5558           suspend, suspend_until
5559         ) SELECT
5560           borrowernumber, reservedate, biblionumber,
5561           constrainttype, branchcode, notificationdate,
5562           reminderdate, cancellationdate, reservenotes,
5563           priority, found, timestamp, itemnumber,
5564           waitingdate, expirationdate, lowestPriority,
5565           suspend, suspend_until
5566         FROM reserves ORDER BY reservedate
5567     ");
5568     $dbh->do('TRUNCATE reserves');
5569     $dbh->do('ALTER TABLE reserves ADD reserve_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
5570     $dbh->do('INSERT INTO reserves SELECT * FROM tmp_reserves WHERE reserve_id > COALESCE(@ai, 0)');
5571     $dbh->do('DROP TABLE tmp_reserves');
5572     $dbh->do('COMMIT');
5573
5574     my $sth = $dbh->prepare("
5575         SELECT COUNT( * ) AS count
5576         FROM information_schema.COLUMNS
5577         WHERE COLUMN_NAME =  'reserve_id'
5578         AND (
5579           TABLE_NAME LIKE  'reserves'
5580           OR
5581           TABLE_NAME LIKE  'old_reserves'
5582         )
5583     ");
5584     $sth->execute();
5585     my $row = $sth->fetchrow_hashref();
5586     die("Failed to add reserve_id to reserves tables, please refresh the page to try again.") unless ( $row->{'count'} );
5587
5588     print "Upgrade to $DBversion done (add reserve_id to reserves & old_reserves tables)\n";
5589     SetVersion($DBversion);
5590 }
5591
5592 $DBversion = "3.09.00.026";
5593 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5594     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
5595         ( 3, 'parameters_remaining_permissions', 'Remaining system parameters permissions'),
5596         ( 3, 'manage_circ_rules', 'manage circulation rules')");
5597     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5598         SELECT borrowernumber, 3, 'parameters_remaining_permissions'
5599         FROM borrowers WHERE flags & (1 << 3)");
5600     # Give new subpermissions to all users that have 'parameters' permission flag (bit 3) set
5601     # see userflags table
5602     $dbh->do("INSERT INTO user_permissions (borrowernumber, module_bit, code)
5603         SELECT borrowernumber, 3, 'manage_circ_rules'
5604         FROM borrowers WHERE flags & (1 << 3)");
5605     print "Upgrade to $DBversion done (Added parameters subpermissions)\n";
5606     SetVersion($DBversion);
5607 }
5608
5609 $DBversion = '3.09.00.027';
5610 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5611     $dbh->do("ALTER TABLE issuingrules ADD overduefinescap decimal(28,6) DEFAULT NULL");
5612     my $maxfine = C4::Context->preference('MaxFine');
5613     if ($maxfine && $maxfine < 900) { # an arbitrary value that tells us it's not "some huge value"
5614       $dbh->do("UPDATE issuingrules SET overduefinescap=?",undef,$maxfine);
5615       $dbh->do("UPDATE systempreferences SET value = NULL WHERE variable = 'MaxFine'");
5616     }
5617     $dbh->do("UPDATE systempreferences SET explanation = 'Maximum fine a patron can have for all late returns at one moment. Single item caps are specified in the circulation rules matrix.' WHERE variable = 'MaxFine'");
5618     print "Upgrade to $DBversion done (Bug 7420 add overduefinescap to circulation matrix)\n";
5619     SetVersion ($DBversion);
5620 }
5621
5622 $DBversion = "3.09.00.028";
5623 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5624     unless ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
5625         my %referencetypes = (  '00' => 'PERSO_NAME',
5626                                 '10' => 'CORPO_NAME',
5627                                 '11' => 'MEETI_NAME',
5628                                 '30' => 'UNIF_TITLE',
5629                                 '48' => 'CHRON_TERM',
5630                                 '50' => 'TOPIC_TERM',
5631                                 '51' => 'GEOGR_NAME',
5632                                 '55' => 'GENRE/FORM'
5633                 );
5634         my $query = q{SELECT DISTINCT authtypecode, tagfield
5635                     FROM auth_subfield_structure
5636                     WHERE (tagfield BETWEEN '400' AND '455' OR
5637                     tagfield BETWEEN '500' and '555') AND tagsubfield='a' AND
5638                     frameworkcode = '' AND ROW(authtypecode, tagfield) NOT IN
5639                     (SELECT authtypecode, tagfield FROM auth_subfield_structure
5640                     WHERE tagsubfield ='9' )};
5641         $sth = $dbh->prepare($query);
5642         $sth->execute;
5643         my $sth2 = $dbh->prepare(q{INSERT INTO auth_subfield_structure
5644                 (authtypecode, tagfield, tagsubfield, liblibrarian, libopac,
5645                  repeatable, mandatory, tab, authorised_value, value_builder,
5646                  seealso, isurl, hidden, linkid, kohafield, frameworkcode)
5647                 VALUES (?, ?, '9', '9 (RLIN)', '9 (RLIN)', 0, 0, ?, NULL, NULL,
5648                     NULL, 0, 1, '', '', '')});
5649         my $sth3 = $dbh->prepare(q{UPDATE auth_subfield_structure SET
5650                                     frameworkcode = ? WHERE authtypecode = ? AND
5651                                     tagfield = ? AND tagsubfield = 'a'});
5652         while (my $row = $sth->fetchrow_arrayref()) {
5653             my ($authtypecode, $field) = @$row;
5654             $sth2->execute($authtypecode, $field, substr($field, 0, 1));
5655             my $authtypemarker = substr $field, 1, 2;
5656             if ($authtypemarker && $referencetypes{$authtypemarker}) {
5657                 $sth3->execute($referencetypes{$authtypemarker}, $authtypecode, $field);
5658             }
5659         }
5660     }
5661
5662     print "Upgrade to $DBversion done (Add thesaurus links for MARC21/NORMARC)\n";
5663     SetVersion($DBversion);
5664 }
5665
5666 $DBversion = "3.09.00.029"; # FIXME
5667 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5668     $dbh->do("UPDATE systempreferences SET options=concat(options,'|EAN13') WHERE variable='itemBarcodeInputFilter' AND options NOT LIKE '%EAN13%'");
5669     print "Upgrade to $DBversion done (Add itemBarcodeInputFilter choice EAN13)\n";
5670
5671     $dbh->do("UPDATE systempreferences SET options = concat(options,'|EAN13'), explanation = concat(explanation,'; EAN13 - incremental') WHERE variable = 'autoBarcode' AND options NOT LIKE '%EAN13%'");
5672     print "Upgrade to $DBversion done ( Added EAN13 barcode autogeneration sequence )\n";
5673     SetVersion($DBversion);
5674 }
5675
5676 $DBversion ="3.09.00.030";
5677 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5678     my $query = "SELECT value FROM systempreferences WHERE variable='opacstylesheet'";
5679     my $remote= $dbh->selectrow_arrayref($query);
5680     $dbh->do("DELETE from systempreferences WHERE variable='opacstylesheet'");
5681     if($remote && $remote->[0]) {
5682         $query="UPDATE systempreferences SET value=? WHERE variable='opaclayoutstylesheet'";
5683         $dbh->do($query,undef,$remote->[0]);
5684         print "NOTE: The URL of your remote opac css file has been moved to preference opaclayoutstylesheet.\n";
5685     }
5686     print "Upgrade to $DBversion done (BZ 8263: Make OPAC stylesheet preferences more consistent)\n";
5687     SetVersion($DBversion);
5688 }
5689
5690 $DBversion = "3.09.00.031";
5691 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5692     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonReviews'");
5693     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonSimilarItems'");
5694     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSAccessKeyID'");
5695     $dbh->do("DELETE FROM systempreferences WHERE variable='AWSPrivateKey'");
5696     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonReviews'");
5697     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonSimilarItems'");
5698     $dbh->do("DELETE FROM systempreferences WHERE variable='AmazonEnabled'");
5699     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACAmazonEnabled'");
5700     print "Upgrade to $DBversion done ('Remove preferences controlling broken Amazon features (Bug 8679')\n";
5701     SetVersion ($DBversion);
5702 }
5703
5704 $DBversion = "3.09.00.032";
5705 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5706     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'defaultSortField' AND value = 'callnumber'");
5707     $dbh->do("UPDATE systempreferences SET value = 'call_number' WHERE variable = 'OPACdefaultSortField' AND value = 'callnumber'");
5708     print "Upgrade to $DBversion done (Bug 8657 - Default sort by call number does not work. Correcting system preference value.)\n";
5709     SetVersion ($DBversion);
5710 }
5711
5712
5713 $DBversion = '3.09.00.033';
5714 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5715    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacSuppressionByIPRange','','Restrict the suppression to IP adresses outside of the IP range','','free');");
5716    print "Upgrade to $DBversion done (Add OpacSuppressionByIPRange syspref)\n";
5717    SetVersion ($DBversion);
5718 }
5719
5720 $DBversion ="3.09.00.034";
5721 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5722     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'PERSO_NAME' WHERE frameworkcode = 'PERSO_CODE'");
5723     $dbh->do("UPDATE auth_subfield_structure SET frameworkcode = 'CORPO_NAME' WHERE frameworkcode = 'ORGO_CODE'");
5724     print "Upgrade to $DBversion done (Bug 8207: correct typo in authority types)\n";
5725     SetVersion ($DBversion);
5726 }
5727
5728 $DBversion = "3.09.00.035";
5729 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5730     $dbh->do("
5731     INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('PrefillItem','0','When a new item is added, should it be prefilled with last created item values?','','YesNo');
5732     ");
5733     $dbh->do(
5734     "INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToUseWhenPrefill','','Define a list of subfields to use when prefilling items (separated by space)','','Free');
5735     ");
5736     print "Upgrade to $DBversion done (Adding PrefillItem and SubfieldsToUseWhenPrefill sysprefs)\n";
5737     SetVersion ($DBversion);
5738 }
5739
5740 $DBversion = "3.09.00.036";
5741 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5742     # biblioitems changes
5743     $dbh->do("ALTER TABLE biblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5744     $dbh->do("ALTER TABLE deletedbiblioitems ADD COLUMN agerestriction VARCHAR(255) DEFAULT NULL AFTER cn_sort");
5745     # preferences changes
5746     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AgeRestrictionMarker','','Markers for age restriction indication, e.g. FSK|PEGI|Age|. See: http://wiki.koha-community.org/wiki/Age_restriction',NULL,'free')");
5747     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AgeRestrictionOverride',0,'Allow staff to check out an item with age restriction.',NULL,'YesNo')");
5748
5749     print "Upgrade to $DBversion done (Add colum agerestriction to biblioitems and deletedbiblioitems, add system preferences AgeRestrictionMarker and AgeRestrictionOverride)\n";
5750    SetVersion ($DBversion);
5751 }
5752
5753 $DBversion = "3.09.00.037";
5754 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5755     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('UseTransportCostMatrix',0,'Use Transport Cost Matrix when filling holds','','YesNo')");
5756
5757  $dbh->do("CREATE TABLE `transport_cost` (
5758               `frombranch` varchar(10) NOT NULL,
5759               `tobranch` varchar(10) NOT NULL,
5760               `cost` decimal(6,2) NOT NULL,
5761               `disable_transfer` tinyint(1) NOT NULL DEFAULT 0,
5762               CHECK ( `frombranch` <> `tobranch` ), -- a dud check, mysql does not support that
5763               PRIMARY KEY (`frombranch`, `tobranch`),
5764               CONSTRAINT `transport_cost_ibfk_1` FOREIGN KEY (`frombranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
5765               CONSTRAINT `transport_cost_ibfk_2` FOREIGN KEY (`tobranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
5766           ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
5767
5768     print "Upgrade to $DBversion done (creating `transport_cost` table; adding UseTransportCostMatrix systempref, in circulation)\n";
5769     SetVersion($DBversion);
5770 }
5771
5772 $DBversion ="3.09.00.038";
5773 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5774     $dbh->do("ALTER TABLE borrower_attributes CHANGE  attribute  attribute VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
5775     print "Upgrade to $DBversion done (Increase the maximum size of a borrower attribute value)\n";
5776     SetVersion($DBversion);
5777 }
5778
5779 $DBversion ="3.09.00.039";
5780 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5781     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('DidYouMeanFromAuthorities','0','Suggest searches based on authority file.','YesNo');");
5782     print "Upgrade to $DBversion done (Add system preference DidYouMeanFromAuthorities)\n";
5783     SetVersion($DBversion);
5784 }
5785
5786 $DBversion = "3.09.00.040";
5787 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5788     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IncludeSeeFromInSearches','0','','Include see-from references in searches.','YesNo');");
5789     print "Upgrade to $DBversion done (Add IncludeSeeFromInSearches system preference)\n";
5790     SetVersion ($DBversion);
5791 }
5792
5793 $DBversion = "3.09.00.041";
5794 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5795     $dbh->do(qq{
5796         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportRemoveFields','','List of fields for non export in circulation.pl (separated by a space)','','');
5797     });
5798     print "Upgrade to $DBversion done (Add system preference ExportRemoveFields)\n";
5799     SetVersion($DBversion);
5800 }
5801
5802 $DBversion = "3.09.00.042";
5803 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5804     $dbh->do(qq{
5805         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ExportWithCsvProfile','','Set a profile name for CSV export','','');
5806     });
5807     print "Upgrade to $DBversion done (Adds New System preference ExportWithCsvProfile)\n";
5808     SetVersion($DBversion)
5809 }
5810
5811 $DBversion = "3.09.00.043";
5812 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5813     $dbh->do("
5814         ALTER TABLE aqorders
5815         ADD parent_ordernumber int(11) DEFAULT NULL
5816     ");
5817     $dbh->do("
5818         UPDATE aqorders
5819         SET parent_ordernumber = ordernumber;
5820     ");
5821     print "Upgrade to $DBversion done (Adding parent_ordernumber in aqorders)\n";
5822     SetVersion($DBversion);
5823 }
5824
5825 $DBversion = '3.09.00.044';
5826 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5827     $dbh->do("ALTER TABLE statistics ADD COLUMN ccode VARCHAR ( 10 ) NULL AFTER associatedborrower");
5828     $dbh->do("UPDATE statistics SET statistics.ccode = ( SELECT items.ccode FROM items WHERE statistics.itemnumber = items.itemnumber )");
5829     $dbh->do("UPDATE statistics SET statistics.ccode = (
5830               SELECT deleteditems.ccode FROM deleteditems
5831                   WHERE statistics.itemnumber = deleteditems.itemnumber
5832               ) WHERE statistics.ccode IS NULL");
5833     print "Upgrade done ( Added Collection Code to Statistics table. )\n";
5834     SetVersion ($DBversion);
5835 }
5836
5837 $DBversion = "3.09.00.045";
5838 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5839     $dbh->do("ALTER TABLE borrower_attribute_types MODIFY category_code VARCHAR( 10 ) NULL DEFAULT NULL");
5840     print "Upgrade to $DBversion done. (Bug 8002: Update patron attribute types table from varchar(1) to varchar(10) category_code)\nWarning to Koha System Administrators: If you use borrower attributes defined by borrower categories, you have to check your configuration. A bug may have removed your attribute links to borrower categories.\nPlease check, and fix it if necessary.";
5841     SetVersion($DBversion);
5842 }
5843
5844 $DBversion = "3.09.00.046";
5845 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5846     $dbh->do("ALTER TABLE `accountlines` ADD `accountlines_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;");
5847     print "Upgrade to $DBversion done (adding accountlines_id field in accountlines table)\n";
5848     SetVersion($DBversion);
5849 }
5850
5851 $DBversion = "3.09.00.047";
5852 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5853     # to preserve default behaviour as best as possible, set this new preference differently depending on whether IndependantBranches is set or not
5854     my $prefvalue = 'anywhere';
5855     if (C4::Context->preference("IndependantBranches")) { $prefvalue = 'homeorholdingbranch';}
5856     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowReturnToBranch', '$prefvalue', 'Where an item may be returned', 'anywhere|homebranch|holdingbranch|homeorholdingbranch', 'Choice');");
5857
5858     print "Upgrade to $DBversion done: adding AllowReturnToBranch syspref (bug 6151)";
5859     SetVersion($DBversion);
5860 }
5861
5862 $DBversion = "3.09.00.048";
5863 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5864     $dbh->do("ALTER TABLE authorised_values MODIFY lib varchar(200)");
5865     $dbh->do("ALTER TABLE authorised_values MODIFY lib_opac varchar(200)");
5866
5867     print "Upgrade to $DBversion done (Raise the length of Authorised Values descriptions)\n";
5868     SetVersion($DBversion);
5869 }
5870
5871 $DBversion ="3.09.00.049";
5872 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
5873     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACMobileUserCSS','','Include the following CSS for the mobile view on all pages in the OPAC:',NULL,'free');");
5874     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacMainUserBlockMobile','','Show the following HTML in its own column on the main page of the OPAC (mobile version):',NULL,'free');");
5875     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowLibrariesPulldownMobile','1','Show the libraries pulldown on the mobile version of the OPAC.',NULL,'YesNo');");
5876     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowFiltersPulldownMobile','1','Show the search filters pulldown on the mobile version of the OPAC.',NULL,'YesNo');");
5877     print "Upgrade to $DBversion done (Add OPACMobileUserCSS, OpacMainUserBlockMobile, OpacShowLibrariesPulldownMobile and OpacShowFiltersPulldownMobile sysprefs)\n";
5878     SetVersion($DBversion);
5879 }
5880
5881 $DBversion = "3.09.00.050";
5882 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5883     $dbh->do("ALTER TABLE authorised_values MODIFY category varchar(16) NOT NULL DEFAULT '';");
5884     $dbh->do("INSERT INTO authorised_values (category, authorised_value, lib) VALUES
5885               ('REPORT_GROUP', 'CIRC', 'Circulation'),
5886               ('REPORT_GROUP', 'CAT', 'Catalog'),
5887               ('REPORT_GROUP', 'PAT', 'Patrons'),
5888               ('REPORT_GROUP', 'ACQ', 'Acquisitions'),
5889               ('REPORT_GROUP', 'ACC', 'Accounts');");
5890
5891     $dbh->do("ALTER TABLE reports_dictionary ADD report_area varchar(6) DEFAULT NULL;");
5892     $dbh->do("UPDATE reports_dictionary SET report_area = CASE area
5893                   WHEN 1 THEN 'CIRC'
5894                   WHEN 2 THEN 'CAT'
5895                   WHEN 3 THEN 'PAT'
5896                   WHEN 4 THEN 'ACQ'
5897                   WHEN 5 THEN 'ACC'
5898                   END;");
5899     $dbh->do("ALTER TABLE reports_dictionary DROP area;");
5900     $dbh->do("ALTER TABLE reports_dictionary ADD KEY dictionary_area_idx (report_area);");
5901
5902     $dbh->do("ALTER TABLE saved_sql ADD report_area varchar(6) DEFAULT NULL;");
5903     $dbh->do("ALTER TABLE saved_sql ADD report_group varchar(80) DEFAULT NULL;");
5904     $dbh->do("ALTER TABLE saved_sql ADD report_subgroup varchar(80) DEFAULT NULL;");
5905     $dbh->do("ALTER TABLE saved_sql ADD KEY sql_area_group_idx (report_group, report_subgroup);");
5906
5907     print "Upgrade to $DBversion done saved_sql new fields report_group and report_area; authorised_values.category 16 char \n";
5908     SetVersion($DBversion);
5909 }
5910
5911 $DBversion = "3.09.00.051";
5912 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5913     $dbh->do("
5914         CREATE TABLE aqinvoices (
5915           invoiceid int(11) NOT NULL AUTO_INCREMENT,
5916           invoicenumber mediumtext NOT NULL,
5917           booksellerid int(11) NOT NULL,
5918           shipmentdate date default NULL,
5919           billingdate date default NULL,
5920           closedate date default NULL,
5921           shipmentcost decimal(28,6) default NULL,
5922           shipmentcost_budgetid int(11) default NULL,
5923           PRIMARY KEY (invoiceid),
5924           CONSTRAINT aqinvoices_fk_aqbooksellerid FOREIGN KEY (booksellerid) REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE,
5925           CONSTRAINT aqinvoices_fk_shipmentcost_budgetid FOREIGN KEY (shipmentcost_budgetid) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
5926         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5927     ");
5928
5929     # Fill this new table with existing invoices
5930     my $sth = $dbh->prepare("
5931         SELECT aqorders.booksellerinvoicenumber AS invoicenumber, aqbasket.booksellerid, aqorders.datereceived
5932         FROM aqorders
5933           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
5934         WHERE aqorders.booksellerinvoicenumber IS NOT NULL
5935           AND aqorders.booksellerinvoicenumber != ''
5936         GROUP BY aqorders.booksellerinvoicenumber
5937     ");
5938     $sth->execute;
5939     my $results = $sth->fetchall_arrayref({});
5940     $sth = $dbh->prepare("
5941         INSERT INTO aqinvoices (invoicenumber, booksellerid, shipmentdate) VALUES (?,?,?)
5942     ");
5943     foreach(@$results) {
5944         $sth->execute($_->{invoicenumber}, $_->{booksellerid}, $_->{datereceived});
5945     }
5946
5947     # Add the column in aqorders, fill it with correct value
5948     # and then drop booksellerinvoicenumber column
5949     $dbh->do("
5950         ALTER TABLE aqorders
5951         ADD COLUMN invoiceid int(11) default NULL AFTER booksellerinvoicenumber,
5952         ADD CONSTRAINT aqorders_ibfk_3 FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE SET NULL ON UPDATE CASCADE
5953     ");
5954
5955     $dbh->do("
5956         UPDATE aqorders, aqinvoices
5957         SET aqorders.invoiceid = aqinvoices.invoiceid
5958         WHERE aqorders.booksellerinvoicenumber = aqinvoices.invoicenumber
5959     ");
5960
5961     $dbh->do("
5962         ALTER TABLE aqorders
5963         DROP COLUMN booksellerinvoicenumber
5964     ");
5965
5966     print "Upgrade to $DBversion done (Add aqinvoices table) \n";
5967     SetVersion ($DBversion);
5968 }
5969
5970 $DBversion = "3.09.00.052";
5971 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5972     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('decreaseLoanHighHolds', NULL, '', 'Decreases the loan period for items with number of holds above the threshold specified in decreaseLoanHighHoldsValue', 'YesNo');");
5973     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('decreaseLoanHighHoldsValue', NULL, '', 'Specifies a threshold for the minimum number of holds needed to trigger a reduction in loan duration (used with decreaseLoanHighHolds)', 'Integer');");
5974     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('decreaseLoanHighHoldsDuration', NULL, '', 'Specifies a number of days that a loan is reduced to when used in conjunction with decreaseLoanHighHolds', 'Integer');");
5975     print "Upgrade to $DBversion done (Add systempreferences to decrease loan length on high demand items decreaseLoanHighHolds, decreaseLoanHighHoldsValue and decreaseLoanHighHoldsDuration) \n";
5976     SetVersion ($DBversion);
5977 }
5978
5979 $DBversion = "3.09.00.053";
5980 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
5981     $dbh->do(
5982     q|CREATE TABLE `import_auths` (
5983         import_record_id int(11) NOT NULL,
5984         matched_authid int(11) default NULL,
5985         control_number varchar(25) default NULL,
5986         authorized_heading varchar(128) default NULL,
5987         original_source varchar(25) default NULL,
5988         CONSTRAINT import_auths_ibfk_1 FOREIGN KEY (import_record_id)
5989         REFERENCES import_records (import_record_id) ON DELETE CASCADE ON UPDATE CASCADE,
5990         KEY matched_authid (matched_authid)
5991         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;|
5992     );
5993     $dbh->do("ALTER TABLE import_batches
5994                 CHANGE COLUMN num_biblios num_records int(11) NOT NULL default 0,
5995                 ADD COLUMN record_type enum('biblio', 'auth', 'holdings') NOT NULL default 'biblio'");
5996     $dbh->do("UPDATE import_batches SET record_type='auth' WHERE import_batch_id IN
5997                 (SELECT import_batch_id FROM import_records WHERE record_type='auth')");
5998
5999     print "Upgrade to $DBversion done (Added support for staging authorities)\n";
6000     SetVersion ($DBversion);
6001 }
6002
6003 $DBversion = "3.09.00.054";
6004 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6005     $dbh->do("ALTER TABLE aqorders CHANGE COLUMN gst gstrate DECIMAL(6,4)  DEFAULT NULL");
6006     print "Upgrade to $DBversion done (Change column name in aqorders gst --> gstrate)\n";
6007     SetVersion($DBversion);
6008 }
6009
6010 $DBversion = "3.09.00.055";
6011 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6012     $dbh->do("ALTER TABLE aqorders ADD discount float(6,4) DEFAULT NULL AFTER gstrate");
6013     print "Upgrade to $DBversion done (Add discount field in aqorders table)\n";
6014     SetVersion($DBversion);
6015 }
6016
6017 $DBversion ="3.09.00.056";
6018 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6019     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('AuthDisplayHierarchy','0','Display authority hierarchies','','YesNo')");
6020     print "Upgrade to $DBversion done (Add system preference AuthDisplayHierarchy)\n";
6021     SetVersion($DBversion);
6022 }
6023
6024 $DBversion = "3.09.00.057";
6025 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6026     $dbh->do("ALTER TABLE aqbasket ADD deliveryplace VARCHAR(10) default NULL AFTER basketgroupid;");
6027     $dbh->do("ALTER TABLE aqbasket ADD billingplace VARCHAR(10) default NULL AFTER deliveryplace;");
6028     print "Upgrade to $DBversion done (Bug 5356: Added billingplace, deliveryplace to the aqbasket table)\n";
6029     SetVersion($DBversion);
6030 }
6031
6032 $DBversion ="3.09.00.058";
6033 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6034     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('OPACdidyoumean',NULL,'Did you mean? configuration for the OPAC. Do not change, as this is controlled by /cgi-bin/koha/admin/didyoumean.pl.','Free');");
6035     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('INTRAdidyoumean',NULL,'Did you mean? configuration for the Intranet. Do not change, as this is controlled by /cgi-bin/koha/admin/didyoumean.pl.','Free');");
6036     print "Upgrade to $DBversion done (Add Did You Mean? configuration)\n";
6037     SetVersion($DBversion);
6038 }
6039
6040 $DBversion ="3.09.00.059";
6041 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6042     $dbh->do("INSERT INTO systempreferences (variable, value, options, explanation, type) VALUES ('BlockReturnOfWithdrawnItems', '1', '0', 'If enabled, items that are marked as withdrawn cannot be returned.', 'YesNo');");
6043     print "Upgrade to $DBversion done (Add system preference BlockReturnOfWithdrawnItems)\n";
6044     SetVersion($DBversion);
6045 }
6046
6047 $DBversion = "3.09.00.060";
6048 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6049     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HoldsToPullStartDate','2','Set the default start date for the Holds to pull list to this many days ago',NULL,'Integer')");
6050     print "Upgrade to $DBversion done (Added HoldsToPullStartDate syspref)\n";
6051     SetVersion($DBversion);
6052 }
6053
6054 $DBversion = "3.09.00.061";
6055 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6056     $dbh->do("UPDATE systempreferences set value=0 WHERE variable='OPACItemsResultsDisplay' AND value='statuses'");
6057     $dbh->do("UPDATE systempreferences set value=1 WHERE variable='OPACItemsResultsDisplay' AND value='itemdetails'");
6058     $dbh->do("UPDATE systempreferences SET explanation='If No, show only the status of items in result list. If Yes, show full location of items (branchlocation+callnumber) as in staff interface',options=NULL,type='YesNo' WHERE variable='OPACItemsResultsDisplay'");
6059     print "Upgrade to $DBversion done (Fixes Bug 5409, Set the syspref value to 1 if it is itemdetails and 0 if it is statuses, leaving it alone if it is already 1 or 0 and change the type of the syspref to YesNo.)\n";
6060     SetVersion ($DBversion);
6061 }
6062
6063 $DBversion = "3.09.00.062";
6064 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6065    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
6066    $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='QueryRemoveStopwords'");
6067    print "Upgrade to $DBversion done (Disable obsolete NoZebra and QueryRemoveStopwords sysprefs)\n";
6068    SetVersion ($DBversion);
6069 }
6070
6071 $DBversion = "3.09.00.063";
6072 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6073     my $gst_booksellers = $dbh->selectcol_arrayref("SELECT DISTINCT(gstrate) FROM aqbooksellers");
6074     my $gist_syspref = C4::Context->preference("gist");
6075     # remove the undef values and construct and array with the syspref and the supplier values
6076     my @gstrates = map { defined $_ ? $_ : () } @$gst_booksellers;
6077     push @gstrates, split ('\|', $gist_syspref);
6078     # we want to compare integer (or float)
6079     $_ = $_ + 0 for @gstrates;
6080     use List::MoreUtils qw/uniq/;
6081     # remove duplicate values
6082     @gstrates = uniq sort @gstrates;
6083     my $new_syspref_value = join '|', @gstrates;
6084     # update the syspref with the new values
6085     my $sth = $dbh->prepare("UPDATE systempreferences set value=? WHERE variable='gist'");
6086     $sth->execute( $new_syspref_value );
6087
6088     print "Upgrade to $DBversion done (Bug 8832, Set the syspref gist with the existing values)\n";
6089     SetVersion ($DBversion);
6090 }
6091
6092 $DBversion = "3.09.00.064";
6093 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6094    $dbh->do('ALTER TABLE items ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6095    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the items table)\n";
6096    SetVersion ($DBversion);
6097 }
6098
6099 $DBversion = "3.09.00.065";
6100 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6101    $dbh->do('ALTER TABLE deleteditems ADD coded_location_qualifier varchar(10) default NULL AFTER itemcallnumber');
6102    print "Upgrade to $DBversion done (Bug 6428: Added coded_location_qualifier to the deleteditems table)\n";
6103    SetVersion ($DBversion);
6104 }
6105
6106 $DBversion = "3.09.00.066";
6107 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6108    $dbh->do("DELETE FROM systempreferences WHERE variable='DidYouMeanFromAuthorities'");
6109    print "Upgrade to $DBversion done (Bug 9107: remove DidYouMeanFromAuthorities syspref)\n";
6110    SetVersion ($DBversion);
6111 }
6112
6113 $DBversion = "3.09.00.067";
6114 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6115    $dbh->do("ALTER TABLE statistics CHANGE COLUMN ccode ccode varchar(10) NULL");
6116    print "Upgrade to $DBversion done (Bug 9064: statistics.ccode potentially wrongly defined)\n";
6117    SetVersion ($DBversion);
6118 }
6119
6120 $DBversion = "3.10.00.00";
6121 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6122    print "Upgrade to $DBversion done (release tag)\n";
6123    SetVersion ($DBversion);
6124 }
6125
6126 $DBversion = "3.11.00.001";
6127 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6128     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('alphabet','A B C D E F G H I J K L M N O P Q R S T U V W X Y Z','Alphabet that can be expanded into browse links, e.g. on Home > Patrons',NULL,'free')");
6129     print "Upgrade to $DBversion done (Bug 2832 - Add alphabet syspref)\n";
6130 }
6131
6132 $DBversion = "3.11.00.002";
6133 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6134     $dbh->do(q{
6135         DELETE from aqorders_items where ordernumber NOT IN (SELECT ordernumber FROM aqorders);
6136     });
6137     $dbh->do(q{
6138         ALTER TABLE aqorders_items
6139         ADD CONSTRAINT aqorders_items_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber)
6140         ON DELETE CASCADE ON UPDATE CASCADE;
6141     });
6142     print "Upgrade to $DBversion done (Bug 9030: Add constraint on aqorders_items.ordernumber)\n";
6143     SetVersion ($DBversion);
6144 }
6145
6146 $DBversion = "3.11.00.003";
6147 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6148     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('RefundLostItemFeeOnReturn', '1', 'If enabled, the lost item fee charged to a borrower will be refunded when the lost item is returned.', NULL, 'YesNo')");
6149     print "Upgrade to $DBversion done (Bug 7189: Add system preference RefundLostItemFeeOnReturn)\n";
6150     SetVersion($DBversion);
6151 }
6152
6153 $DBversion = "3.11.00.004";
6154 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6155     $dbh->do(qq{
6156         ALTER TABLE subscription ADD COLUMN closed INT(1) NOT NULL DEFAULT 0 AFTER enddate;
6157     });
6158
6159     print "Upgrade to $DBversion done (Bug 8782: Add field subscription.closed)\n";
6160     SetVersion($DBversion);
6161 }
6162
6163 $DBversion = "3.11.00.005";
6164 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6165     $dbh->do(qq{CREATE TABLE borrower_attribute_types_branches(bat_code VARCHAR(10), b_branchcode VARCHAR(10),FOREIGN KEY (bat_code) REFERENCES borrower_attribute_types(code) ON DELETE CASCADE,FOREIGN KEY (b_branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE ) ENGINE=INNODB DEFAULT CHARSET=utf8;});
6166
6167     $dbh->do(qq{CREATE TABLE categories_branches(categorycode VARCHAR(10), branchcode VARCHAR(10), FOREIGN KEY (categorycode) REFERENCES categories(categorycode) ON DELETE CASCADE, FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE ) ENGINE=INNODB DEFAULT CHARSET=utf8;});
6168
6169     $dbh->do(qq{CREATE TABLE authorised_values_branches(av_id INTEGER, branchcode VARCHAR(10), FOREIGN KEY (av_id) REFERENCES authorised_values(id) ON DELETE CASCADE, FOREIGN KEY  (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE ) ENGINE=INNODB DEFAULT CHARSET=utf8;});
6170
6171     print "Upgrade to $DBversion done (Bug 7919: Display of values depending on the connexion library)\n";
6172     SetVersion($DBversion);
6173 }
6174
6175 $DBversion = "3.11.00.006";
6176 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6177     $dbh->do(q{
6178         UPDATE virtualshelves SET sortfield="copyrightdate" where sortfield="year";
6179     });
6180     print "Upgrade to $DBversion done (Bug 9167: Update the virtualshelves.sortfield column with 'copyrightdate' if needed)\n";
6181     SetVersion($DBversion);
6182 }
6183
6184 $DBversion = "3.11.00.007";
6185 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6186     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ar', 'language', 'de', 'Arabisch')");
6187     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hy', 'language', 'de', 'Armenisch')");
6188     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'bg', 'language', 'de', 'Bulgarisch')");
6189     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'zh', 'language', 'de', 'Chinesisch')");
6190     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'cs', 'language', 'de', 'Tschechisch')");
6191     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'da', 'language', 'de', 'Dänisch')");
6192     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nl', 'language', 'de', 'Niederländisch')");
6193     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'en', 'language', 'de', 'Englisch')");
6194     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fi', 'language', 'de', 'Finnisch')");
6195     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fr', 'language', 'de', 'Französisch')");
6196     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'fr', 'Laotien')");
6197     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'lo', 'language', 'de', 'Laotisch')");
6198     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'el', 'language', 'de', 'Griechisch (Nach 1453)')");
6199     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'he', 'language', 'de', 'Hebräisch')");
6200     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hi', 'language', 'de', 'Hindi')");
6201     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'hu', 'language', 'de', 'Ungarisch')");
6202     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'id', 'language', 'de', 'Indonesisch')");
6203     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'it', 'language', 'de', 'Italienisch')");
6204     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ja', 'language', 'de', 'Japanisch')");
6205     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ko', 'language', 'de', 'Koreanisch')");
6206     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'la', 'language', 'de', 'Latein')");
6207     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'fr', 'Galicien')");
6208     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'gl', 'language', 'de', 'Galizisch')");
6209     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nb', 'language', 'de', 'Norwegisch bokm&#229;l')");
6210     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'nn', 'language', 'de', 'Norwegisch nynorsk')");
6211     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'fa', 'language', 'de', 'Persisch')");
6212     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pl', 'language', 'de', 'Polnisch')");
6213     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'pt', 'language', 'de', 'Portugiesisch')");
6214     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ro', 'language', 'de', 'Rumänisch')");
6215     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ru', 'language', 'de', 'Russisch')");
6216     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'fr', 'Serbe')");
6217     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sr', 'language', 'de', 'Serbisch')");
6218     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'es', 'language', 'de', 'Spanisch')");
6219     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'sv', 'language', 'de', 'Schwedisch')");
6220     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'fr', 'Tétoum')");
6221     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tet', 'language', 'de', 'Tetum')");
6222     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'th', 'language', 'de', 'Thailändisch')");
6223     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'tr', 'language', 'de', 'Türkisch')");
6224     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'uk', 'language', 'de', 'Ukrainisch')");
6225     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'fr', 'Ourdou')");
6226     $dbh->do("INSERT INTO language_descriptions (subtag, type, lang, description) VALUES( 'ur', 'language', 'de', 'Urdu')");
6227     print "Upgrade to $DBversion done (Bug 9056: add German and a couple of French translations to language_descriptions)\n";
6228     SetVersion ($DBversion);
6229 }
6230
6231 $DBversion = "3.11.00.008";
6232 if (CheckVersion($DBversion)) {
6233     $dbh->do("
6234         CREATE TABLE IF NOT EXISTS `borrower_modifications` (
6235           `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6236           `verification_token` varchar(255) NOT NULL DEFAULT '',
6237           `borrowernumber` int(11) NOT NULL DEFAULT '0',
6238           `cardnumber` varchar(16) DEFAULT NULL,
6239           `surname` mediumtext,
6240           `firstname` text,
6241           `title` mediumtext,
6242           `othernames` mediumtext,
6243           `initials` text,
6244           `streetnumber` varchar(10) DEFAULT NULL,
6245           `streettype` varchar(50) DEFAULT NULL,
6246           `address` mediumtext,
6247           `address2` text,
6248           `city` mediumtext,
6249           `state` text,
6250           `zipcode` varchar(25) DEFAULT NULL,
6251           `country` text,
6252           `email` mediumtext,
6253           `phone` text,
6254           `mobile` varchar(50) DEFAULT NULL,
6255           `fax` mediumtext,
6256           `emailpro` text,
6257           `phonepro` text,
6258           `B_streetnumber` varchar(10) DEFAULT NULL,
6259           `B_streettype` varchar(50) DEFAULT NULL,
6260           `B_address` varchar(100) DEFAULT NULL,
6261           `B_address2` text,
6262           `B_city` mediumtext,
6263           `B_state` text,
6264           `B_zipcode` varchar(25) DEFAULT NULL,
6265           `B_country` text,
6266           `B_email` text,
6267           `B_phone` mediumtext,
6268           `dateofbirth` date DEFAULT NULL,
6269           `branchcode` varchar(10) DEFAULT NULL,
6270           `categorycode` varchar(10) DEFAULT NULL,
6271           `dateenrolled` date DEFAULT NULL,
6272           `dateexpiry` date DEFAULT NULL,
6273           `gonenoaddress` tinyint(1) DEFAULT NULL,
6274           `lost` tinyint(1) DEFAULT NULL,
6275           `debarred` date DEFAULT NULL,
6276           `debarredcomment` varchar(255) DEFAULT NULL,
6277           `contactname` mediumtext,
6278           `contactfirstname` text,
6279           `contacttitle` text,
6280           `guarantorid` int(11) DEFAULT NULL,
6281           `borrowernotes` mediumtext,
6282           `relationship` varchar(100) DEFAULT NULL,
6283           `ethnicity` varchar(50) DEFAULT NULL,
6284           `ethnotes` varchar(255) DEFAULT NULL,
6285           `sex` varchar(1) DEFAULT NULL,
6286           `password` varchar(30) DEFAULT NULL,
6287           `flags` int(11) DEFAULT NULL,
6288           `userid` varchar(75) DEFAULT NULL,
6289           `opacnote` mediumtext,
6290           `contactnote` varchar(255) DEFAULT NULL,
6291           `sort1` varchar(80) DEFAULT NULL,
6292           `sort2` varchar(80) DEFAULT NULL,
6293           `altcontactfirstname` varchar(255) DEFAULT NULL,
6294           `altcontactsurname` varchar(255) DEFAULT NULL,
6295           `altcontactaddress1` varchar(255) DEFAULT NULL,
6296           `altcontactaddress2` varchar(255) DEFAULT NULL,
6297           `altcontactaddress3` varchar(255) DEFAULT NULL,
6298           `altcontactstate` text,
6299           `altcontactzipcode` varchar(50) DEFAULT NULL,
6300           `altcontactcountry` text,
6301           `altcontactphone` varchar(50) DEFAULT NULL,
6302           `smsalertnumber` varchar(50) DEFAULT NULL,
6303           `privacy` int(11) DEFAULT NULL,
6304           PRIMARY KEY (`verification_token`,`borrowernumber`),
6305           KEY `verification_token` (`verification_token`),
6306           KEY `borrowernumber` (`borrowernumber`)
6307         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6308 ");
6309
6310     $dbh->do("
6311         INSERT INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
6312         ('PatronSelfRegistration', '0', NULL, 'If enabled, patrons will be able to register themselves via the OPAC.', 'YesNo'),
6313         ('PatronSelfRegistrationVerifyByEmail', '0', NULL, 'If enabled, any patron attempting to register themselves via the OPAC will be required to verify themselves via email to activate his or her account.', 'YesNo'),
6314         ('PatronSelfRegistrationDefaultCategory', '', '', 'A patron registered via the OPAC will receive a borrower category code set in this system preference.', 'free'),
6315         ('PatronSelfRegistrationExpireTemporaryAccountsDelay', '0', NULL, 'If PatronSelfRegistrationDefaultCategory is enabled, this system preference controls how long a patron can have a temporary status before the account is deleted automatically. It is an integer value representing a number of days to wait before deleting a temporary patron account. Setting it to 0 disables the deleting of temporary accounts.', 'Integer'),
6316         ('PatronSelfRegistrationBorrowerMandatoryField',  'surname|firstname', NULL ,  'Choose the mandatory fields for a patron''s account, when registering via the OPAC.',  'free'),
6317         ('PatronSelfRegistrationBorrowerUnwantedField',  '', NULL ,  'Name the fields you don''t want to display when registering a new patron via the OPAC.',  'free');
6318     ");
6319
6320     $dbh->do("
6321     INSERT INTO  letter ( `module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content` )
6322     VALUES ( 'members', 'OPAC_REG_VERIFY', '', 'Opac Self-Registration Verification Email', '1', 'Verify Your Account', 'Hello!
6323
6324     Your library account has been created. Please verify your email address by clicking this link to complete the signup process:
6325
6326     http://<<OPACBaseURL>>/cgi-bin/koha/opac-registration-verify.pl?token=<<borrower_modifications.verification_token>>
6327
6328     If you did not initiate this request, you may safely ignore this one-time message. The request will expire shortly.'
6329     )");
6330
6331     print "Upgrade to $DBversion done (Bug 7067: Add Patron Self Registration)\n";
6332     SetVersion ($DBversion);
6333 }
6334
6335 $DBversion = "3.11.00.009";
6336 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6337     $dbh->do("
6338         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
6339         ('SeparateHoldings', '0', 'Separate current branch holdings from other holdings', NULL, 'YesNo'),
6340         ('SeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings', 'homebranch|holdingbranch', 'Choice'),
6341         ('OpacSeparateHoldings', '0', 'Separate current branch holdings from other holdings (OPAC)', NULL, 'YesNo'),
6342         ('OpacSeparateHoldingsBranch', 'homebranch', 'Branch used to separate holdings (OPAC)', 'homebranch|holdingbranch', 'Choice')
6343     ");
6344
6345     print "Upgrade to $DBversion done (Bug 7674: Add systempreferences SeparateHoldings, SeparateHoldingsBranch, OpacSeparateHoldings and OpacSeparateHoldingsBranch) \n";
6346     SetVersion ($DBversion);
6347 }
6348
6349 $DBversion = "3.11.00.010";
6350 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
6351     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RenewalSendNotice', '0', '', NULL, 'YesNo')");
6352     $dbh->do(q{
6353         INSERT INTO `letter` (`module`, `code`, `name`, `title`, `content`) VALUES
6354         ('circulation','RENEWAL','Item Renewals','Item Renewals','The following items have been renewed:\r\n----\r\n<<biblio.title>>\r\n----\r\nThank you for visiting <<branches.branchname>>.');
6355     });
6356     print "Upgrade to $DBversion done (Bug 9151 - Renewal notice according to patron alert preferences)\n";
6357     SetVersion($DBversion);
6358 }
6359
6360 $DBversion = "3.11.00.011";
6361 if ( CheckVersion($DBversion) ) {
6362    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaEnabled','not','Show a HTML5 media player in a tab on opac-detail.pl for media files catalogued in field 856.','not|opac|staff|both','Choice');");
6363    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('HTML5MediaExtensions','webm|ogg|ogv|oga|vtt','Media file extensions','','free');");
6364    print "Upgrade to $DBversion done (Bug 8377: Add HTML5MediaEnabled and HTML5MediaExtensions sysprefs)\n";
6365    SetVersion ($DBversion);
6366 }
6367
6368 $DBversion = "3.11.00.012";
6369 if ( CheckVersion($DBversion) ) {
6370     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AllowHoldsOnPatronsPossessions', '1', 'Allow holds on records that patron have items of it',NULL,'YesNo')");
6371     print "Upgrade to $DBversion done (Bug 9206: Only allow place holds in records that the patron don't have in his possession)\n";
6372     SetVersion($DBversion);
6373 }
6374
6375 $DBversion = "3.11.00.013";
6376 if ( CheckVersion($DBversion) ) {
6377     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('NotesBlacklist','','List of notes fields that should not appear in the title notes/description separator of details',NULL,'free')");
6378     print "Upgrade to $DBversion done (Bug 9162 - Add a system preference to set which notes fields appears on title notes/description separator)\n";
6379     SetVersion($DBversion);
6380 }
6381
6382 $DBversion = "3.11.00.014";
6383 if ( CheckVersion($DBversion) ) {
6384    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserCSS', '', 'Add CSS to be included in the SCO module in an embedded <style> tag.', 'free' )");
6385    $dbh->do("INSERT INTO systempreferences ( variable, value, explanation, type ) VALUES ( 'SCOUserJS', '', 'Define custom javascript for inclusion in the SCO module', 'free' )");
6386    print "Upgrade to $DBversion done (Bug 9009: Add SCOUserCSS and SCOUserJS sysprefs)\n";
6387 }
6388
6389 $DBversion = "3.11.00.015";
6390 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6391     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('RentalsInNoissuesCharge', '1', 'Rental charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6392     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('ManInvInNoissuesCharge', '1', 'MANUAL_INV charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
6393     print "Upgrade to $DBversion done (Add sysprefs RentalsInNoissuesCharge and ManInvInNoissuesCharge.)\n";
6394     SetVersion($DBversion);
6395 }
6396
6397 $DBversion = "3.11.00.016";
6398 if ( CheckVersion($DBversion) ) {
6399    $dbh->do(q{
6400         UPDATE userflags SET flagdesc="<b>Required for staff login.</b> Staff access, allows viewing of catalogue in staff client." where flagdesc="Modify login / permissions for staff users";
6401         });
6402    $dbh->do(q{
6403         UPDATE userflags SET flagdesc="Edit Authorities" where flagdesc="Allow to edit authorities";
6404         });
6405    $dbh->do(q{
6406         UPDATE userflags SET flagdesc="Allow access to the reports module" where flagdesc="Allow to access to the reports module";
6407         });
6408    $dbh->do(q{
6409         UPDATE userflags SET flagdesc="Set library management parameters (deprecated)" where flagdesc="Set library management parameters";
6410         });
6411    $dbh->do(q{
6412         UPDATE userflags SET flagdesc="Manage serial subscriptions" where flagdesc="Allow to manage serials subscriptions";
6413         });
6414    $dbh->do(q{
6415         UPDATE userflags SET flagdesc="Manage patrons fines and fees" where flagdesc="Update borrower charges";
6416         });
6417    $dbh->do(q{
6418         UPDATE userflags SET flagdesc="Check out and check in items" where flagdesc="Circulate books";
6419         });
6420    $dbh->do(q{
6421         UPDATE userflags SET flagdesc="Manage Koha system settings (Administration panel)" where flagdesc="Set Koha system parameters";
6422         });
6423    $dbh->do(q{
6424         UPDATE userflags SET flagdesc="Add or modify patrons" where flagdesc="Add or modify borrowers";
6425         });
6426    $dbh->do(q{
6427         UPDATE userflags SET flagdesc="Use all tools (expand for granular tools permissions)" where flagdesc="Use tools (export, import, barcodes)";
6428         });
6429    $dbh->do(q{
6430         UPDATE userflags SET flagdesc="Allow staff members to modify permissions for other staff members" where flagdesc="Set user permissions";
6431         });
6432    $dbh->do(q{
6433         UPDATE permissions SET description="Perform batch modification of patrons" where description="Perform batch modifivation of patrons";
6434         });
6435
6436    print "Upgrade to $DBversion done (Bug 9382 (updated with bug 9745) - refresh permission descriptions to make more sense)\n";
6437    SetVersion ($DBversion);
6438 }
6439
6440 $DBversion ="3.11.00.017";
6441 if ( CheckVersion($DBversion) ) {
6442     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReviews','0','Display book review snippets from IDreamBooks.com','','YesNo');");
6443     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksReadometer','0','Display Readometer from IDreamBooks.com','','YesNo');");
6444     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('IDreamBooksResults','0','Display IDreamBooks.com rating in search results','','YesNo');");
6445     print "Upgrade to $DBversion done (Add IDreamBooks enhanced content)\n";
6446     SetVersion($DBversion);
6447 }
6448
6449 $DBversion = "3.11.00.018";
6450 if ( CheckVersion($DBversion) ) {
6451    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACNumbersPreferPhrase','0', NULL, 'Control the use of phr operator in callnumber and standard number OPAC searches', 'YesNo')");
6452    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('IntranetNumbersPreferPhrase','0', NULL, 'Control the use of phr operator in callnumber and standard number staff client searches', 'YesNo')");
6453    print "Upgrade to $DBversion done (Bug 9395: Problem with callnumber and standard number search in OPAC and Staff Client)\n";
6454    SetVersion ($DBversion);
6455 }
6456
6457 $DBversion = "3.11.00.019";
6458 if ( CheckVersion($DBversion) ) {
6459     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorityField100', 'afrey50      ba0', NULL, NULL, 'Textarea')");
6460     print "Upgrade to $DBversion done (Bug 9145 - Add syspref UNIMARCAuthorityField100)\n";
6461     SetVersion ($DBversion);
6462 }
6463
6464 $DBversion = "3.11.00.020";
6465 if ( CheckVersion($DBversion) ) {
6466     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UNIMARCField100Language', 'fre','UNIMARC field 100 default language',NULL,'short')");
6467     print "Upgrade to $DBversion done (Bug 8347 - Koha forces UNIMARC 100 field code language to 'fre')\n";
6468     SetVersion($DBversion);
6469 }
6470
6471 $DBversion ="3.11.00.021";
6472 if ( CheckVersion($DBversion) ) {
6473     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OPACPopupAuthorsSearch','0','Display the list of authors when clicking on one author.','','YesNo');");
6474     print "Upgrade to $DBversion done (Bug 5888 - Subject search pop-up for the OPAC)\n";
6475     SetVersion($DBversion);
6476 }
6477
6478 $DBversion = "3.11.00.022";
6479 if ( CheckVersion($DBversion) ) {
6480     $dbh->do(
6481 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('Persona',0,'Use Mozilla Persona for login','','YesNo')"
6482     );
6483     print "Upgrade to $DBversion done (Bug 9587 - Allow login via Persona)\n";
6484     SetVersion($DBversion);
6485 }
6486
6487 $DBversion = "3.11.00.023";
6488 if ( CheckVersion($DBversion) ) {
6489     $dbh->do("UPDATE z3950servers SET host = 'lx2.loc.gov', port = 210, db = 'LCDB', syntax = 'USMARC', encoding = 'utf8' WHERE name = 'LIBRARY OF CONGRESS'");
6490     print "Upgrade to $DBversion done (Bug 9520 - Update default LOC Z39.50 target)\n";
6491     SetVersion($DBversion);
6492 }
6493
6494 $DBversion = "3.11.00.024";
6495 if ( CheckVersion($DBversion) ) {
6496     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacItemLocation','callnum','Show the shelving location of items in the opac','callnum|ccode|location','Choice');");
6497     print "Upgrade to $DBversion done (Bug 5079: Add OpacItemLocation syspref)\n";
6498     SetVersion ($DBversion);
6499 }
6500
6501 $DBversion = "3.11.00.025";
6502 if ( CheckVersion($DBversion) ) {
6503     $dbh->do(
6504         "CREATE TABLE linktracker (
6505   id int(11) NOT NULL AUTO_INCREMENT,
6506   biblionumber int(11) DEFAULT NULL,
6507   itemnumber int(11) DEFAULT NULL,
6508   borrowernumber int(11) DEFAULT NULL,
6509   url text,
6510   timeclicked datetime DEFAULT NULL,
6511   PRIMARY KEY (id),
6512   KEY bibidx (biblionumber),
6513   KEY itemidx (itemnumber),
6514   KEY borridx (borrowernumber),
6515   KEY dateidx (timeclicked)
6516     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
6517     );
6518     $dbh->do( "
6519   INSERT INTO systempreferences (variable,value,explanation,options,type)
6520   VALUES('TrackClicks','0','Track links clicked',NULL,'Integer')" );
6521     print
6522 "Upgrade to $DBversion done (Adds feature Bug 8917, the ability to track links clicked)\n";
6523     SetVersion($DBversion);
6524 }
6525
6526 $DBversion = "3.11.00.026";
6527 if ( CheckVersion($DBversion) ) {
6528     $dbh->do(qq{
6529         ALTER TABLE import_records ADD INDEX batch_id_record_type ( import_batch_id, record_type );
6530     });
6531     print "Upgrade to $DBversion done (Bug 9207: Add new index batch_id_record_type to import_records)\n";
6532     SetVersion($DBversion);
6533 }
6534
6535 $DBversion = "3.11.00.027";
6536 if ( CheckVersion($DBversion) ) {
6537     $dbh->do(q{
6538         INSERT INTO permissions ( module_bit, code, description )
6539         VALUES  ( '1', 'overdues_report', 'Execute overdue items report' )
6540     });
6541     # add new permission for users with all report permissions and circulation remaining permission
6542     $dbh->do(q{
6543         INSERT INTO user_permissions (borrowernumber, module_bit, code)
6544         SELECT user_permissions.borrowernumber, 1, 'overdues_report'
6545         FROM user_permissions
6546         LEFT JOIN borrowers USING(borrowernumber)
6547         WHERE borrowers.flags & (1 << 16)
6548         AND user_permissions.code = 'circulate_remaining_permissions'
6549     });
6550     print "Upgrade to $DBversion done ( Add circ permission overdues_report )\n";
6551     SetVersion($DBversion);
6552 }
6553
6554 $DBversion = "3.11.00.028";
6555 if ( CheckVersion($DBversion) ) {
6556     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('PatronSelfRegistrationAdditionalInstructions', '', NULL , 'A free text field to display additional instructions to newly self registered patrons.', 'free'    );");
6557     print "Upgrade to $DBversion done (Bug 9756 - Patron self registration missing the system preference PatronSelfRegistrationAdditionalInstructions)\n";
6558     SetVersion($DBversion);
6559 }
6560
6561 $DBversion = "3.11.00.029";
6562 if (CheckVersion($DBversion)) {
6563     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseQueryParser', '0', 'If enabled, try to use QueryParser for queries.', NULL, 'YesNo')");
6564     print "Upgrade to $DBversion done (Bug 9239: Make it possible for Koha to use QueryParser)\n";
6565     SetVersion ($DBversion);
6566 }
6567
6568 $DBversion = "3.11.00.030";
6569 if ( CheckVersion($DBversion) ) {
6570     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('FinesIncludeGracePeriod','1','If enabled, fines calculations will include the grace period.',NULL,'YesNo');");
6571     print "Upgrade to $DBversion done (Add system preference FinesIncludeGracePeriod)\n";
6572     SetVersion($DBversion);
6573 }
6574
6575 $DBversion = "3.11.00.100";
6576 if ( CheckVersion($DBversion) ) {
6577     print "Upgrade to $DBversion done (3.12-alpha release)\n";
6578     SetVersion ($DBversion);
6579 }
6580
6581 $DBversion = "3.11.00.101";
6582 if ( CheckVersion($DBversion) ) {
6583    $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('UNIMARCAuthorsFacetsSeparator',', ', 'UNIMARC authors facets separator', NULL, 'short')");
6584    print "Upgrade to $DBversion done (Bug 9341: Problem with UNIMARC authors facets)\n";
6585    SetVersion ($DBversion);
6586 }
6587
6588 $DBversion = "3.11.00.102";
6589 if ( CheckVersion($DBversion) ) {
6590     $dbh->do(q{
6591         DELETE FROM systempreferences WHERE variable='NoZebra'
6592     });
6593     $dbh->do(q{
6594         DELETE FROM systempreferences WHERE variable='QueryRemoveStopwords'
6595     });
6596     print "Upgrade to $DBversion done (Remove deprecated NoZebra and QueryRemoveStopwords sysprefs)\n";
6597     SetVersion($DBversion);
6598 }
6599
6600 $DBversion = "3.11.00.103";
6601 if ( CheckVersion($DBversion) ) {
6602     $dbh->do("DELETE FROM systempreferences WHERE variable = 'insecure';");
6603     print "Upgrade to $DBversion done (Bug 9827 - Remove 'insecure' system preference)\n";
6604     SetVersion($DBversion);
6605 }
6606
6607 $DBversion = "3.11.00.104";
6608 if ( CheckVersion($DBversion) ) {
6609     print "Upgrade to $DBversion done (3.12-alpha2 release)\n";
6610     SetVersion ($DBversion);
6611 }
6612
6613 $DBversion = "3.11.00.105";
6614 if ( CheckVersion($DBversion) ) {
6615     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
6616         $sth = $dbh->prepare(
6617 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '029'"
6618         );
6619         $sth->execute;
6620         my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6621
6622         for my $frameworkcode ( keys %$frameworkcodes ) {
6623             $dbh->do( "
6624     INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6625     libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6626     value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6627     ('029', 'a', 'OCLC library identifier', 'OCLC library identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6628     ('029', 'b', 'System control number', 'System control number', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6629     ('029', 'c', 'OAI set name', 'OAI set name', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL),
6630     ('029', 't', 'Content type identifier', 'Content type identifier', 0, 0, '', 0, '', '', '', 0, -6, '$frameworkcode', '', '', NULL)
6631    " );
6632         }
6633
6634         for my $tag ( '863', '864', '865' ) {
6635             $sth = $dbh->prepare(
6636 "SELECT frameworkcode FROM marc_tag_structure WHERE tagfield = '$tag'"
6637             );
6638             $sth->execute;
6639             my $frameworkcodes = $sth->fetchall_hashref('frameworkcode');
6640
6641             for my $frameworkcode ( keys %$frameworkcodes ) {
6642                 $dbh->do( "
6643      INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian,
6644      libopac, repeatable, mandatory, kohafield, tab, authorised_value, authtypecode,
6645      value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
6646      ('$tag', '6', 'Linkage', 'Linkage', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6647      ('$tag', '8', 'Field link and sequence number', 'Field link and sequence number', 0, 0, '', 8, '', '', '', NULL, 5, '$frameworkcode', '', '', NULL),
6648      ('$tag', 'a', 'First level of enumeration', 'First level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6649      ('$tag', 'b', 'Second level of enumeration', 'Second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6650      ('$tag', 'c', 'Third level of enumeration', 'Third level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6651      ('$tag', 'd', 'Fourth level of enumeration', 'Fourth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6652      ('$tag', 'e', 'Fifth level of enumeration', 'Fifth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6653      ('$tag', 'f', 'Sixth level of enumeration', 'Sixth level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6654      ('$tag', 'g', 'Alternative numbering scheme, first level of enumeration', 'Alternative numbering scheme, first level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6655      ('$tag', 'h', 'Alternative numbering scheme, second level of enumeration', 'Alternative numbering scheme, second level of enumeration', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6656      ('$tag', 'i', 'First level of chronology', 'First level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6657      ('$tag', 'j', 'Second level of chronology', 'Second level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6658      ('$tag', 'k', 'Third level of chronology', 'Third level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6659      ('$tag', 'l', 'Fourth level of chronology', 'Fourth level of chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6660      ('$tag', 'm', 'Alternative numbering scheme, chronology', 'Alternative numbering scheme, chronology', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6661      ('$tag', 'n', 'Converted Gregorian year', 'Converted Gregorian year', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6662      ('$tag', 'o', 'Type of unit', 'Type of unit', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6663      ('$tag', 'p', 'Piece designation', 'Piece designation', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6664      ('$tag', 'q', 'Piece physical condition', 'Piece physical condition', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6665      ('$tag', 's', 'Copyright article-fee code', 'Copyright article-fee code', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6666      ('$tag', 't', 'Copy number', 'Copy number', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6667      ('$tag', 'v', 'Issuing date', 'Issuing date', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6668      ('$tag', 'w', 'Break indicator', 'Break indicator', 0, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6669      ('$tag', 'x', 'Nonpublic note', 'Nonpublic note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL),
6670      ('$tag', 'z', 'Public note', 'Public note', 1, 0, '', 8, '', '', '', 0, 5, '$frameworkcode', '', '', NULL)
6671     " );
6672             }
6673         }
6674     }
6675     print "Upgrade to $DBversion done (Bug 9353: Missing subfields on MARC21 frameworks)\n";
6676     SetVersion($DBversion);
6677 }
6678
6679
6680 $DBversion = "3.11.00.106";
6681 if ( CheckVersion($DBversion) ) {
6682     $dbh->do("INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES ('19', 'plugins', 'Koha plugins', '0')");
6683     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES
6684               ('19', 'manage', 'Manage plugins ( install / uninstall )'),
6685               ('19', 'tool', 'Use tool plugins'),
6686               ('19', 'report', 'Use report plugins'),
6687               ('19', 'configure', 'Configure plugins')
6688             ");
6689     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('UseKohaPlugins','0','Enable or disable the ability to use Koha Plugins.','','YesNo')");
6690
6691     $dbh->do("
6692         CREATE TABLE IF NOT EXISTS plugin_data (
6693             plugin_class varchar(255) NOT NULL,
6694             plugin_key varchar(255) NOT NULL,
6695             plugin_value text,
6696             PRIMARY KEY (plugin_class,plugin_key)
6697         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6698     ");
6699
6700     print "Upgrade to $DBversion done (Bug 7804: Added plugin system.)\n";
6701     SetVersion($DBversion);
6702 }
6703
6704 $DBversion = "3.11.00.107";
6705 if ( CheckVersion($DBversion) ) {
6706    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('TimeFormat','24hr','12hr|24hr','Defines the global time format for visual output.','Choice')");
6707    print "Upgrade to $DBversion done (Bug 9014: Add syspref TimeFormat)\n";
6708    SetVersion ($DBversion);
6709 }
6710
6711 $DBversion = "3.11.00.108";
6712 if ( CheckVersion($DBversion) ) {
6713     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;");
6714     $dbh->do("UPDATE action_logs SET info=(SELECT itemnumber FROM items WHERE biblionumber= action_logs.info LIMIT 1) WHERE module='CIRCULATION' AND action in ('ISSUE','RETURN');");
6715     $dbh->do("ALTER TABLE action_logs CHANGE timestamp timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;");
6716     print "Upgrade to $DBversion done (Bug 7241: Fix on circulation logs)\n";
6717     print "WARNING about bug 7241: to partially correct the broken logs, the log history is filled with the first found item for each biblio.\n";
6718     SetVersion($DBversion);
6719 }
6720
6721 $DBversion = "3.11.00.109";
6722 if ( CheckVersion($DBversion) ) {
6723    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('DisplayIconsXSLT', '1', '', 'If ON, displays the format, audience, and material type icons in XSLT MARC21 results and detail pages.', 'YesNo');");
6724    print "Upgrade to $DBversion done (Bug 9403: Add DisplayIconsXSLT)\n";
6725    SetVersion ($DBversion);
6726 }
6727
6728 $DBversion = "3.11.00.110";
6729 if ( CheckVersion($DBversion) ) {
6730     $dbh->do("ALTER TABLE pending_offline_operations CHANGE barcode barcode VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
6731     $dbh->do("ALTER TABLE pending_offline_operations ADD amount DECIMAL( 28, 6 ) NULL DEFAULT NULL");
6732     print "Upgrade to $DBversion done (Bug 8220 - Allow koc uploads to go to process queue)\n";
6733     SetVersion ($DBversion);
6734 }
6735
6736 $DBversion = "3.11.00.111";
6737 if ( CheckVersion($DBversion) ) {
6738     my $sth = $dbh->prepare("
6739         SELECT module, code, branchcode, content
6740         FROM letter
6741         WHERE content LIKE '%<fine>%'
6742     ");
6743     $sth->execute;
6744     my $sth_update = $dbh->prepare("UPDATE letter SET content = ? WHERE module = ? AND code = ? AND branchcode = ?");
6745     while(my $row = $sth->fetchrow_hashref){
6746         $row->{content} =~ s/<fine>\w+<\/fine>/<<items.fine>>/;
6747         $sth_update->execute($row->{content}, $row->{module}, $row->{code}, $row->{branchcode});
6748     }
6749     print "Upgrade to $DBversion done (use new <<items.fine>> syntax in notices)\n";
6750     SetVersion($DBversion);
6751 }
6752
6753 $DBversion = "3.11.00.112";
6754 if ( CheckVersion($DBversion) ) {
6755     $dbh->do(qq{
6756         ALTER TABLE issuingrules ADD COLUMN renewalperiod int(4) DEFAULT NULL AFTER renewalsallowed
6757     });
6758     $dbh->do(qq{
6759         UPDATE issuingrules SET renewalperiod = issuelength
6760     });
6761     print "Upgrade to $DBversion done (Bug 8365: Add colum issuingrules.renewalperiod)\n";
6762     SetVersion ($DBversion);
6763 }
6764
6765 $DBversion = "3.11.00.113";
6766 if ( CheckVersion($DBversion) ) {
6767     $dbh->do(q{
6768         ALTER TABLE branchcategories ADD show_in_pulldown BOOLEAN NOT NULL DEFAULT '0',
6769         ADD INDEX ( show_in_pulldown )
6770     });
6771     print "Upgrade to $DBversion done (Bug 9257 - Add groups to normal search pulldown)\n";
6772     SetVersion ($DBversion);
6773 }
6774
6775 $DBversion = "3.11.00.115";
6776 if ( CheckVersion($DBversion) ) {
6777     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('HighlightOwnItemsOnOPAC','0','','If on, and a patron is logged into the OPAC, items from his or her home library will be emphasized and shown first in search results and item details.','YesNo')");
6778     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('HighlightOwnItemsOnOPACWhich','PatronBranch','PatronBranch|OpacURLBranch','Decides which branch''s items to emphasize. If PatronBranch, emphasize the logged in user''s library''s items. If OpacURLBranch, highlight the items of the Apache var BRANCHCODE defined in Koha''s Apache configuration file.','Choice')");
6779     print "Upgrade to $DBversion done (Bug 7740: Add syspref HighlightOwnItemsOnOPAC)\n";
6780     SetVersion ($DBversion);
6781 }
6782
6783 $DBversion = "3.11.00.116";
6784 if ( CheckVersion($DBversion) ) {
6785     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN serialid;});
6786     $dbh->do(q{ALTER TABLE aqorders DROP COLUMN subscription;});
6787     $dbh->do(q{ALTER TABLE aqorders ADD COLUMN subscriptionid INT(11) DEFAULT NULL;});
6788     $dbh->do(q{ALTER TABLE aqorders ADD CONSTRAINT aqorders_subscriptionid FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE;});
6789     $dbh->do(q{ALTER TABLE subscription ADD COLUMN reneweddate DATE DEFAULT NULL;});
6790     print "Upgrade to $DBversion done (Bug 5343: table aqorders: DROP serialid and subscription fields and ADD subscriptionid, table subscription: ADD reneweddate)\n";
6791     SetVersion ($DBversion);
6792 }
6793
6794 $DBversion = "3.11.00.200";
6795 if ( CheckVersion($DBversion) ) {
6796     print "Upgrade to $DBversion done (3.12-beta1 release)\n";
6797     SetVersion ($DBversion);
6798 }
6799
6800 $DBversion = "3.11.00.201";
6801 if ( CheckVersion($DBversion) ) {
6802     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'BIBSYS' AND host LIKE 'z3950.bibsys.no'");
6803     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'NORBOK' AND host LIKE 'z3950.nb.no'");
6804     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'SAMBOK' AND host LIKE 'z3950.nb.no'");
6805     $dbh->do("UPDATE z3950servers SET encoding = 'ISO_8859-1' WHERE name = 'DEICHMAN' AND host like 'z3950.deich.folkebibl.no'");
6806     print "Upgrade to $DBversion done (Bug 9498 - Update encoding for Norwegian sample Z39.50 servers)\n";
6807     SetVersion($DBversion);
6808 }
6809
6810 $DBversion = "3.11.00.202";
6811 if ( CheckVersion($DBversion) ) {
6812    $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ca', 'language', 'Catalan','2013-01-12' )");
6813    $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'ca','cat')");
6814    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'es', 'Catalán')");
6815    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'en', 'Catalan')");
6816    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'fr', 'Catalan')");
6817    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'ca', 'Català')");
6818    $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'ca', 'language', 'de', 'Katalanisch')");
6819    print "Upgrade to $DBversion done (Bug 9381: Add Catalan laguage)\n";
6820    SetVersion ($DBversion);
6821 }
6822
6823 $DBversion = "3.11.00.203";
6824 if ( CheckVersion($DBversion) ) {
6825     $dbh->do(q{ALTER TABLE suggestions CHANGE COLUMN title title VARCHAR(255) DEFAULT NULL;});
6826     print "Upgrade to $DBversion done (Bug 2046 - increasing title column length for suggestions)\n";
6827     SetVersion ($DBversion);
6828 }
6829
6830 $DBversion = "3.11.00.300";
6831 if ( CheckVersion($DBversion) ) {
6832     print "Upgrade to $DBversion done (3.12-beta3 release)\n";
6833     SetVersion ($DBversion);
6834 }
6835
6836 $DBversion = "3.11.00.301";
6837 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
6838     #issues
6839     $dbh->do(q{
6840         ALTER TABLE `issues`
6841             ADD KEY `itemnumber_idx` (`itemnumber`),
6842             ADD KEY `branchcode_idx` (`branchcode`),
6843             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6844     });
6845     $dbh->do(q{
6846         ALTER TABLE `old_issues`
6847             ADD KEY `branchcode_idx` (`branchcode`),
6848             ADD KEY `issuingbranch_idx` (`issuingbranch`)
6849     });
6850     #items
6851     $dbh->do(q{
6852         ALTER TABLE `items` ADD KEY `itype_idx` (`itype`)
6853     });
6854     $dbh->do(q{
6855         ALTER TABLE `deleteditems` ADD KEY `itype_idx` (`itype`)
6856     });
6857     # biblioitems
6858     $dbh->do(q{
6859         ALTER TABLE `biblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6860     });
6861     $dbh->do(q{
6862         ALTER TABLE `deletedbiblioitems` ADD KEY `itemtype_idx` (`itemtype`)
6863     });
6864     # statistics
6865     $dbh->do(q{
6866         ALTER TABLE `statistics`
6867             ADD KEY `branch_idx` (`branch`),
6868             ADD KEY `proccode_idx` (`proccode`),
6869             ADD KEY `type_idx` (`type`),
6870             ADD KEY `usercode_idx` (`usercode`),
6871             ADD KEY `itemnumber_idx` (`itemnumber`),
6872             ADD KEY `itemtype_idx` (`itemtype`),
6873             ADD KEY `borrowernumber_idx` (`borrowernumber`),
6874             ADD KEY `associatedborrower_idx` (`associatedborrower`),
6875             ADD KEY `ccode_idx` (`ccode`)
6876     });
6877
6878     print "Upgrade to $DBversion done (Bug 9681: Add some database indexes)\n";
6879     SetVersion($DBversion);
6880 }
6881
6882 $DBversion = "3.12.00.000";
6883 if ( CheckVersion($DBversion) ) {
6884     print "Upgrade to $DBversion done (3.12.0 release)\n";
6885     SetVersion ($DBversion);
6886 }
6887
6888 $DBversion = '3.13.00.000';
6889 if ( CheckVersion($DBversion) ) {
6890     print "Upgrade to $DBversion done (start the journey to Koha Pi)\n";
6891     SetVersion ($DBversion);
6892 }
6893
6894 $DBversion = "3.13.00.001";
6895 if ( CheckVersion($DBversion) ) {
6896     $dbh->do("INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('UseCourseReserves', '0', NULL, 'Enable the course reserves feature.', 'YesNo')");
6897     $dbh->do("INSERT INTO userflags (bit,flag,flagdesc,defaulton) VALUES ('18','coursereserves','Course Reserves','0')");
6898     $dbh->do("
6899 CREATE TABLE `courses` (
6900   `course_id` int(11) NOT NULL AUTO_INCREMENT,
6901   `department` varchar(20) DEFAULT NULL,
6902   `course_number` varchar(255) DEFAULT NULL,
6903   `section` varchar(255) DEFAULT NULL,
6904   `course_name` varchar(255) DEFAULT NULL,
6905   `term` varchar(20) DEFAULT NULL,
6906   `staff_note` mediumtext,
6907   `public_note` mediumtext,
6908   `students_count` varchar(20) DEFAULT NULL,
6909   `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',
6910   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6911    PRIMARY KEY (`course_id`)
6912 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6913     ");
6914
6915     $dbh->do("
6916 CREATE TABLE `course_instructors` (
6917   `course_id` int(11) NOT NULL,
6918   `borrowernumber` int(11) NOT NULL,
6919   PRIMARY KEY (`course_id`,`borrowernumber`),
6920   KEY `borrowernumber` (`borrowernumber`)
6921 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6922     ");
6923
6924     $dbh->do("
6925 ALTER TABLE `course_instructors`
6926   ADD CONSTRAINT `course_instructors_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`),
6927   ADD CONSTRAINT `course_instructors_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6928     ");
6929
6930     $dbh->do("
6931 CREATE TABLE `course_items` (
6932   `ci_id` int(11) NOT NULL AUTO_INCREMENT,
6933   `itemnumber` int(11) NOT NULL,
6934   `itype` varchar(10) DEFAULT NULL,
6935   `ccode` varchar(10) DEFAULT NULL,
6936   `holdingbranch` varchar(10) DEFAULT NULL,
6937   `location` varchar(80) DEFAULT NULL,
6938   `enabled` enum('yes','no') NOT NULL DEFAULT 'no',
6939   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6940    PRIMARY KEY (`ci_id`),
6941    UNIQUE KEY `itemnumber` (`itemnumber`),
6942    KEY `holdingbranch` (`holdingbranch`)
6943 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6944     ");
6945
6946     $dbh->do("
6947 ALTER TABLE `course_items`
6948   ADD CONSTRAINT `course_items_ibfk_2` FOREIGN KEY (`holdingbranch`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
6949   ADD CONSTRAINT `course_items_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE;
6950 ");
6951
6952     $dbh->do("
6953 CREATE TABLE `course_reserves` (
6954   `cr_id` int(11) NOT NULL AUTO_INCREMENT,
6955   `course_id` int(11) NOT NULL,
6956   `ci_id` int(11) NOT NULL,
6957   `staff_note` mediumtext,
6958   `public_note` mediumtext,
6959   `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
6960    PRIMARY KEY (`cr_id`),
6961    UNIQUE KEY `pseudo_key` (`course_id`,`ci_id`),
6962    KEY `course_id` (`course_id`)
6963 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
6964 ");
6965
6966     $dbh->do("
6967 ALTER TABLE `course_reserves`
6968   ADD CONSTRAINT `course_reserves_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `courses` (`course_id`);
6969     ");
6970
6971     $dbh->do("
6972 INSERT INTO permissions (module_bit, code, description) VALUES
6973   (18, 'manage_courses', 'Add, edit and delete courses'),
6974   (18, 'add_reserves', 'Add course reserves'),
6975   (18, 'delete_reserves', 'Remove course reserves')
6976 ;
6977     ");
6978
6979
6980     print "Upgrade to $DBversion done (Add Course Reserves ( system preference UseCourseReserves ))\n";
6981     SetVersion($DBversion);
6982 }
6983
6984 $DBversion = "3.13.00.002";
6985 if ( CheckVersion($DBversion) ) {
6986    $dbh->do("UPDATE systempreferences SET variable = 'IndependentBranches' WHERE variable = 'IndependantBranches'");
6987    print "Upgrade to $DBversion done (Bug 10080 - Change system pref IndependantBranches to IndependentBranches)\n";
6988    SetVersion ($DBversion);
6989 }
6990
6991 $DBversion = '3.13.00.003';
6992 if ( CheckVersion($DBversion) ) {
6993     $dbh->do("ALTER TABLE serial DROP itemnumber");
6994     print "Upgrade to $DBversion done (Bug 7718 - Remove itemnumber column from serials table)\n";
6995     SetVersion($DBversion);
6996 }
6997
6998 $DBversion = "3.13.00.004";
6999 if(CheckVersion($DBversion)) {
7000     $dbh->do(
7001 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacShowHoldNotes',0,'Show hold notes on OPAC','','YesNo')"
7002     );
7003     print "Upgrade to $DBversion done (Bug 9722: Allow users to add notes when placing a hold in OPAC)\n";
7004     SetVersion($DBversion);
7005 }
7006
7007 $DBversion = "3.13.00.005";
7008 if(CheckVersion($DBversion)) {
7009     my $intra= C4::Context->preference("intranetstylesheet");
7010     #if this pref is not blank or starting with http, https or / [root], then
7011     #add an additional / to the front
7012     if($intra && $intra !~ /^(\/|https?)/) {
7013         $dbh->do("UPDATE systempreferences SET value=? WHERE variable=?",
7014             undef,('/'.$intra,"intranetstylesheet"));
7015         print "WARNING: Your system preference intranetstylesheet has been prefixed with a slash to make it an absolute path.\n";
7016     }
7017     print "Upgrade to $DBversion done (Bug 10052: Make intranetstylesheet and intranetcolorstylesheet behave exactly like their opac counterparts)\n";
7018     SetVersion ($DBversion);
7019 }
7020
7021 $DBversion = "3.13.00.006";
7022 if ( CheckVersion($DBversion) ) {
7023     $dbh->do(q{
7024         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
7025         VALUES ('CalculateFinesOnReturn','1','Switch to control if overdue fines are calculated on return or not', '', 'YesNo')
7026     });
7027     print "Upgrade to $DBversion done (Bug 10120: Fines on item return controlled by a systempreference)\n";
7028     SetVersion($DBversion);
7029 }
7030
7031 $DBversion = "3.13.00.007";
7032 if ( CheckVersion($DBversion) ) {
7033     $dbh->do("UPDATE systempreferences SET variable='OpacHoldNotes' WHERE variable='OpacShowHoldNotes'");
7034     print "Upgrade to $DBversion done (Bug 10343: Rename OpacShowHoldNotes to OpacHoldNotes)\n";
7035     SetVersion($DBversion);
7036 }
7037
7038 $DBversion = "3.13.00.008";
7039 if ( CheckVersion($DBversion) ) {
7040     $dbh->do("
7041 CREATE TABLE IF NOT EXISTS borrower_files (
7042   file_id int(11) NOT NULL AUTO_INCREMENT,
7043   borrowernumber int(11) NOT NULL,
7044   file_name varchar(255) NOT NULL,
7045   file_type varchar(255) NOT NULL,
7046   file_description varchar(255) DEFAULT NULL,
7047   file_content longblob NOT NULL,
7048   date_uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7049   PRIMARY KEY (file_id),
7050   KEY borrowernumber (borrowernumber),
7051   CONSTRAINT borrower_files_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7052 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7053     ");
7054     print "Upgrade to $DBversion done (Bug 10443: make sure borrower_files table exists)\n";
7055     SetVersion($DBversion);
7056 }
7057
7058 $DBversion = "3.13.00.009";
7059 if ( CheckVersion($DBversion) ) {
7060     $dbh->do("ALTER TABLE aqorders DROP COLUMN biblioitemnumber");
7061     print "Upgrade to $DBversion done (Bug 9987 - Drop column aqorders.biblioitemnumber)\n";
7062     SetVersion($DBversion);
7063 }
7064
7065 $DBversion = "3.13.00.010";
7066 if ( CheckVersion($DBversion) ) {
7067     $dbh->do(
7068         q{
7069 INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('AcqWarnOnDuplicateInvoice','0','Warn librarians when they try to create a duplicate invoice', '', 'YesNo');
7070 }
7071     );
7072     print
7073 "Upgrade to $DBversion done (Bug 10366 - Add system preference to enabling warning librarian when invoice is duplicated)\n";
7074     SetVersion($DBversion);
7075 }
7076
7077 $DBversion = "3.13.00.011";
7078 if ( CheckVersion($DBversion) ) {
7079     $dbh->do("UPDATE language_rfc4646_to_iso639 SET iso639_2_code='ita' WHERE rfc4646_subtag='it'");
7080     print "Upgrade to $DBversion done (Bug 9519: Wrong language code for Italian in the advanced search language limitations)\n";
7081     SetVersion($DBversion);
7082 }
7083
7084 $DBversion = "3.13.00.012";
7085 if ( CheckVersion($DBversion) ) {
7086     $dbh->do("ALTER TABLE issuingrules MODIFY COLUMN overduefinescap decimal(28,6) DEFAULT NULL;");
7087     print "Upgrade to $DBversion done (Bug 10490: Correct datatype for overduefinescap in issuingrules)\n";
7088     SetVersion($DBversion);
7089 }
7090
7091 $DBversion ="3.13.00.013";
7092 if ( CheckVersion($DBversion) ) {
7093     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('AllowTooManyOverride', '1', 'If on, allow staff to override and check out items when the patron has reached the maximum number of allowed checkouts', '', 'YesNo');");
7094     print "Upgrade to $DBversion done (Bug 9576: add AllowTooManyOverride syspref to enable or disable issue limit confirmation)\n";
7095     SetVersion($DBversion);
7096 }
7097
7098 $DBversion = "3.13.00.014";
7099 if ( CheckVersion($DBversion) ) {
7100     $dbh->do("ALTER TABLE courses MODIFY COLUMN department varchar(80) DEFAULT NULL;");
7101     $dbh->do("ALTER TABLE courses MODIFY COLUMN term       varchar(80) DEFAULT NULL;");
7102     print "Upgrade to $DBversion done (Bug 10604: correct width of courses.department and courses.term)\n";
7103     SetVersion($DBversion);
7104 }
7105
7106 $DBversion = "3.13.00.015";
7107 if ( CheckVersion($DBversion) ) {
7108     $dbh->do(
7109 "INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('itemBarcodeFallbackSearch','','If set, enables the automatic use of a keyword catalog search if the phrase entered as a barcode on the checkout page does not turn up any results during an item barcode search',NULL,'YesNo')"
7110     );
7111     print "Upgrade to $DBversion done (Bug 7494: Add itemBarcodeFallbackSearch syspref)\n";
7112     SetVersion($DBversion);
7113 }
7114
7115 $DBversion = "3.13.00.016";
7116 if ( CheckVersion($DBversion) ) {
7117     $dbh->do(q{
7118         ALTER TABLE items CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7119     });
7120
7121     $dbh->do(q{
7122         ALTER TABLE deleteditems CHANGE wthdrawn withdrawn TINYINT( 1 ) NOT NULL DEFAULT  '0'
7123     });
7124
7125     $dbh->do(q{
7126         UPDATE saved_sql SET savedsql = REPLACE(savedsql, 'wthdrawn', 'withdrawn')
7127     });
7128
7129     $dbh->do(q{
7130         UPDATE marc_subfield_structure SET kohafield = 'items.withdrawn' WHERE kohafield = 'items.wthdrawn'
7131     });
7132
7133     print "Upgrade to $DBversion done (Bug 10550 - Fix database typo wthdrawn)\n";
7134     SetVersion($DBversion);
7135 }
7136
7137 $DBversion = "3.13.00.017";
7138 if ( CheckVersion($DBversion) ) {
7139     $dbh->do(
7140 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientKey','','Client key for OverDrive integration','30','Free')"
7141     );
7142     $dbh->do(
7143 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveClientSecret','','Client key for OverDrive integration','30','YesNo')"
7144     );
7145     $dbh->do(
7146 "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('OverDriveLibraryID','','Library ID for OverDrive integration','','Integer')"
7147     );
7148     print "Upgrade to $DBversion done (Bug 10320 - Show results from library's OverDrive collection in OPAC search)\n";
7149     SetVersion($DBversion);
7150 }
7151
7152 $DBversion = "3.13.00.018";
7153 if ( CheckVersion($DBversion) ) {
7154     $dbh->do(qq{DROP TABLE IF EXISTS aqorders_transfers;});
7155     $dbh->do(qq{
7156         CREATE TABLE aqorders_transfers (
7157           ordernumber_from int(11) NULL,
7158           ordernumber_to int(11) NULL,
7159           timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7160           UNIQUE KEY ordernumber_from (ordernumber_from),
7161           UNIQUE KEY ordernumber_to (ordernumber_to),
7162           CONSTRAINT aqorders_transfers_ordernumber_from FOREIGN KEY (ordernumber_from) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE,
7163           CONSTRAINT aqorders_transfers_ordernumber_to FOREIGN KEY (ordernumber_to) REFERENCES aqorders (ordernumber) ON DELETE SET NULL ON UPDATE CASCADE
7164         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7165     });
7166     print "Upgrade to $DBversion done (Bug 5349: Add aqorders_transfers table)\n";
7167     SetVersion($DBversion);
7168 }
7169
7170 $DBversion = "3.13.00.019";
7171 if ( CheckVersion($DBversion) ) {
7172     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsg VARCHAR(255) AFTER summary;");
7173     $dbh->do("ALTER TABLE itemtypes ADD COLUMN checkinmsgtype CHAR(16) DEFAULT 'message' NOT NULL AFTER checkinmsg;");
7174     print "Upgrade to $DBversion done (Bug 10513 - Light up a warning/message when returning a chosen item type)\n";
7175     SetVersion($DBversion);
7176 }
7177
7178 $DBversion = "3.13.00.020";
7179 if ( CheckVersion($DBversion) ) {
7180     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('WhenLostForgiveFine','0',NULL,'If ON, Forgives the fines on an item when it is lost.','YesNo')");
7181     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('WhenLostChargeReplacementFee','1',NULL,'If ON, Charge the replacement price when a patron loses an item.','YesNo')");
7182     print "Upgrade to $DBversion done (Bug 7639: system preferences to forgive fines on lost items)\n";
7183     SetVersion($DBversion);
7184 }
7185
7186 $DBversion ="3.13.00.021";
7187 if ( CheckVersion($DBversion) ) {
7188     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('ConfirmFutureHolds','0','Number of days for confirming future holds','','Integer');");
7189     print "Upgrade to $DBversion done (Bug 9761: Add ConfirmFutureHolds pref)\n";
7190     SetVersion($DBversion);
7191 }
7192
7193 $DBversion = "3.13.00.022";
7194 if ( CheckVersion($DBversion) ) {
7195     $dbh->do("DELETE from auth_tag_structure WHERE tagfield IN ('68a','68b')");
7196     $dbh->do("DELETE from auth_subfield_structure WHERE tagfield IN ('68a','68b')");
7197     print "Upgrade to $DBversion done (Bug 10687 - Delete erroneous tags 68a and 68b on default MARC21 auth framework)\n";
7198     SetVersion($DBversion);
7199 }
7200
7201 $DBversion = "3.13.00.023";
7202 if ( CheckVersion($DBversion) ) {
7203     $dbh->do("ALTER TABLE borrowers CHANGE password password VARCHAR(60);");
7204     print "Upgrade to $DBversion done (Bug 9611 upgrading password storage system)\n";
7205     SetVersion($DBversion);
7206 }
7207
7208 $DBversion = "3.13.00.024";
7209 if ( CheckVersion($DBversion) ) {
7210     $dbh->do(q{ALTER TABLE z3950servers ADD COLUMN recordtype VARCHAR(45) NOT NULL DEFAULT 'biblio' AFTER description;});
7211     print "Upgrade to $DBversion done (Bug 10096 - Add a Z39.50 interface for authority searching)\n";
7212 }
7213
7214 $DBversion = "3.13.00.025";
7215 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7216    $dbh->do("ALTER TABLE oai_sets_mappings ADD COLUMN operator varchar(8) NOT NULL default 'equal' AFTER marcsubfield;");
7217    print "Upgrade to $DBversion done (Bug 9295: OAI notequal: add operator column to OAI mappings table)\n";
7218    SetVersion ($DBversion);
7219 }
7220
7221 $DBversion = "3.13.00.026";
7222 if ( CheckVersion($DBversion) ) {
7223     $dbh->do(q|
7224         ALTER TABLE auth_subfield_structure ADD COLUMN defaultvalue TEXT DEFAULT NULL AFTER frameworkcode
7225     |);
7226     print "Upgrade to $DBversion done (Bug 10602: Add the column auth_subfield_structure.defaultvalue)\n";
7227     SetVersion($DBversion);
7228 }
7229
7230 $DBversion = "3.13.00.027";
7231 if ( CheckVersion($DBversion) ) {
7232     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('AllowOfflineCirculation','0','','If on, enables HTML5 offline circulation functionality.','YesNo')");
7233     print "Upgrade to $DBversion done (Bug 10240: Add syspref AllowOfflineCirculation)\n";
7234     SetVersion ($DBversion);
7235 }
7236
7237 $DBversion = "3.13.00.028";
7238 if ( CheckVersion($DBversion) ) {
7239     $dbh->do(q{
7240         ALTER TABLE export_format ADD type VARCHAR(255) DEFAULT 'marc' AFTER encoding
7241     });
7242     $dbh->do(q{
7243         ALTER TABLE export_format CHANGE marcfields content mediumtext NOT NULL
7244     });
7245     print "Upgrade to $DBversion done (Bug 10853: Add new field export_format.type and rename export_format.marcfields with export_format.content)\n";
7246     SetVersion($DBversion);
7247 }
7248
7249 $DBversion = "3.13.00.029";
7250 if ( CheckVersion($DBversion) ) {
7251     $dbh->do(q{
7252         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type )
7253         VALUES ( "issues to claim", "Default CSV export for serial issue claims",
7254                 "SUPPLIER=aqbooksellers.name|TITLE=subscription.title|ISSUE NUMBER=serial.serialseq|LATE SINCE=serial.planneddate",
7255                 ",", "sql" )
7256     });
7257     print "Upgrade to $DBversion done (Bug 10854: Add the default CSV profile for claiming issues)\n";
7258     SetVersion($DBversion);
7259 }
7260
7261 $DBversion = "3.13.00.030";
7262 if ( CheckVersion($DBversion) ) {
7263     $dbh->do(qq{
7264         DELETE FROM patronimage WHERE NOT EXISTS (SELECT * FROM borrowers WHERE borrowers.cardnumber = patronimage.cardnumber)
7265     });
7266
7267     $dbh->do(qq{
7268         ALTER TABLE patronimage ADD borrowernumber INT( 11 ) NULL FIRST
7269     });
7270
7271     $dbh->{AutoCommit} = 0;
7272     $dbh->{RaiseError} = 1;
7273
7274     eval {
7275         $dbh->do(qq{
7276             UPDATE patronimage LEFT JOIN borrowers USING ( cardnumber ) SET patronimage.borrowernumber = borrowers.borrowernumber
7277         });
7278         $dbh->commit();
7279     };
7280
7281     if ($@) {
7282         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber) failed! Transaction aborted because $@\n";
7283         eval { $dbh->rollback };
7284     }
7285     else {
7286         $dbh->do(qq{
7287             ALTER TABLE patronimage DROP FOREIGN KEY patronimage_fk1
7288         });
7289         $dbh->do(qq{
7290             ALTER TABLE patronimage DROP PRIMARY KEY, ADD PRIMARY KEY( borrowernumber )
7291         });
7292         $dbh->do(qq{
7293             ALTER TABLE patronimage DROP cardnumber
7294         });
7295         $dbh->do(qq{
7296             ALTER TABLE patronimage ADD FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON DELETE CASCADE ON UPDATE CASCADE
7297         });
7298
7299         print "Upgrade to $DBversion done (Bug 10636 - patronimage should have borrowernumber as PK, not cardnumber)\n";
7300         SetVersion($DBversion);
7301     }
7302
7303     $dbh->{AutoCommit} = 1;
7304     $dbh->{RaiseError} = 0;
7305 }
7306
7307 $DBversion = "3.13.00.031";
7308 if ( CheckVersion($DBversion) ) {
7309
7310     $dbh->do(q{
7311         CREATE TABLE IF NOT EXISTS `patron_lists` (
7312           patron_list_id int(11) NOT NULL AUTO_INCREMENT,
7313           name varchar(255) CHARACTER SET utf8 NOT NULL,
7314           owner int(11) NOT NULL,
7315           PRIMARY KEY (patron_list_id),
7316           KEY owner (owner)
7317         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7318     });
7319
7320     $dbh->do(q{
7321         ALTER TABLE `patron_lists`
7322           ADD CONSTRAINT patron_lists_ibfk_1 FOREIGN KEY (`owner`) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7323     });
7324
7325     $dbh->do(q{
7326         CREATE TABLE patron_list_patrons (
7327           patron_list_patron_id int(11) NOT NULL AUTO_INCREMENT,
7328           patron_list_id int(11) NOT NULL,
7329           borrowernumber int(11) NOT NULL,
7330           PRIMARY KEY (patron_list_patron_id),
7331           KEY patron_list_id (patron_list_id),
7332           KEY borrowernumber (borrowernumber)
7333         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7334     });
7335
7336     $dbh->do(q{
7337         ALTER TABLE `patron_list_patrons`
7338           ADD CONSTRAINT patron_list_patrons_ibfk_1 FOREIGN KEY (patron_list_id) REFERENCES patron_lists (patron_list_id) ON DELETE CASCADE ON UPDATE CASCADE,
7339           ADD CONSTRAINT patron_list_patrons_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE;
7340     });
7341
7342     $dbh->do(q{
7343         INSERT INTO permissions (module_bit, code, description) VALUES
7344         (13, 'manage_patron_lists', 'Add, edit and delete patron lists and their contents')
7345     });
7346
7347     print "Upgrade to $DBversion done (Bug 10565 - Add a 'Patron List' feature for storing and manipulating collections of patrons)\n";
7348     SetVersion($DBversion);
7349 }
7350
7351 $DBversion = "3.13.00.032";
7352 if ( CheckVersion($DBversion) ) {
7353     $dbh->do("ALTER TABLE aqorders ADD COLUMN orderstatus varchar(16) DEFAULT 'new' AFTER parent_ordernumber");
7354     $dbh->do("UPDATE aqorders SET orderstatus='ordered' WHERE basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)");
7355     $dbh->do(q{
7356         UPDATE aqorders SET orderstatus='partial'
7357         WHERE quantity > quantityreceived
7358         AND quantityreceived > 0
7359         AND ordernumber IN (
7360             SELECT parent_ordernumber
7361             FROM (
7362                 SELECT DISTINCT(parent_ordernumber)
7363                 FROM aqorders
7364                 WHERE ordernumber != parent_ordernumber
7365             ) AS aq
7366         )
7367         AND basketno IN (SELECT basketno FROM aqbasket WHERE closedate IS NOT NULL)
7368     });
7369     $dbh->do("UPDATE aqorders SET orderstatus='complete' WHERE quantity=quantityreceived");
7370     $dbh->do("UPDATE aqorders SET orderstatus='cancelled' WHERE datecancellationprinted IS NOT NULL");
7371     print "Upgrade to $DBversion done (Bug 5336: Add the new column aqorders.orderstatus)\n";
7372     SetVersion($DBversion);
7373 }
7374
7375 $DBversion = "3.13.00.033";
7376 if ( CheckVersion($DBversion) ) {
7377     $dbh->do(qq|
7378         DROP TABLE IF EXISTS subscription_frequencies
7379     |);
7380     $dbh->do(qq|
7381         CREATE TABLE subscription_frequencies (
7382             id INTEGER NOT NULL AUTO_INCREMENT,
7383             description TEXT NOT NULL,
7384             displayorder INT DEFAULT NULL,
7385             unit ENUM('day','week','month','year') DEFAULT NULL,
7386             unitsperissue INTEGER NOT NULL DEFAULT '1',
7387             issuesperunit INTEGER NOT NULL DEFAULT '1',
7388             PRIMARY KEY (id)
7389         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7390     |);
7391
7392     $dbh->do(qq|
7393         DROP TABLE IF EXISTS subscription_numberpatterns
7394     |);
7395     $dbh->do(qq|
7396         CREATE TABLE subscription_numberpatterns (
7397             id INTEGER NOT NULL AUTO_INCREMENT,
7398             label VARCHAR(255) NOT NULL,
7399             displayorder INTEGER DEFAULT NULL,
7400             description TEXT NOT NULL,
7401             numberingmethod VARCHAR(255) NOT NULL,
7402             label1 VARCHAR(255) DEFAULT NULL,
7403             add1 INTEGER DEFAULT NULL,
7404             every1 INTEGER DEFAULT NULL,
7405             whenmorethan1 INTEGER DEFAULT NULL,
7406             setto1 INTEGER DEFAULT NULL,
7407             numbering1 VARCHAR(255) DEFAULT NULL,
7408             label2 VARCHAR(255) DEFAULT NULL,
7409             add2 INTEGER DEFAULT NULL,
7410             every2 INTEGER DEFAULT NULL,
7411             whenmorethan2 INTEGER DEFAULT NULL,
7412             setto2 INTEGER DEFAULT NULL,
7413             numbering2 VARCHAR(255) DEFAULT NULL,
7414             label3 VARCHAR(255) DEFAULT NULL,
7415             add3 INTEGER DEFAULT NULL,
7416             every3 INTEGER DEFAULT NULL,
7417             whenmorethan3 INTEGER DEFAULT NULL,
7418             setto3 INTEGER DEFAULT NULL,
7419             numbering3 VARCHAR(255) DEFAULT NULL,
7420             PRIMARY KEY (id)
7421         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
7422     |);
7423
7424     $dbh->do(qq|
7425         INSERT INTO subscription_frequencies (description, unit, unitsperissue, issuesperunit, displayorder)
7426         VALUES
7427             ('2/day', 'day', 1, 2, 1),
7428             ('1/day', 'day', 1, 1, 2),
7429             ('3/week', 'week', 1, 3, 3),
7430             ('1/week', 'week', 1, 1, 4),
7431             ('1/2 weeks', 'week', 2, 1, 5),
7432             ('1/3 weeks', 'week', 3, 1, 6),
7433             ('1/month', 'month', 1, 1, 7),
7434             ('1/2 months', 'month', 2, 1, 8),
7435             ('1/3 months', 'month', 3, 1, 9),
7436             ('2/year', 'month', 6, 1, 10),
7437             ('1/year', 'year', 1, 1, 11),
7438             ('1/2 year', 'year', 2, 1, 12),
7439             ('Irregular', NULL, 1, 1, 13)
7440     |);
7441
7442     # Used to link existing subscription to newly created frequencies
7443     my $frequencies_mapping = {     # keys are old frequency numbers, values are the new ones
7444         1 => 2,     # daily (n/week)
7445         2 => 4,     # 1/week
7446         3 => 5,     # 1/2 weeks
7447         4 => 6,     # 1/3 weeks
7448         5 => 7,     # 1/month
7449         6 => 8,     # 1/2 months (6/year)
7450         7 => 9,     # 1/3 months (1/quarter)
7451         8 => 9,    # 1/quarter (seasonal)
7452         9 => 10,    # 2/year
7453         10 => 11,   # 1/year
7454         11 => 12,   # 1/2 years
7455         12 => 1,    # 2/day
7456         16 => 13,   # Without periodicity
7457         32 => 13,   # Irregular
7458         48 => 13    # Unknown
7459     };
7460
7461     $dbh->do(qq|
7462         INSERT INTO subscription_numberpatterns
7463             (label, displayorder, description, numberingmethod,
7464             label1, add1, every1, whenmorethan1, setto1, numbering1,
7465             label2, add2, every2, whenmorethan2, setto2, numbering2,
7466             label3, add3, every3, whenmorethan3, setto3, numbering3)
7467         VALUES
7468             ('Number', 1, 'Simple Numbering method', 'No.{X}',
7469             'Number', 1, 1, 99999, 1, NULL,
7470             NULL, NULL, NULL, NULL, NULL, NULL,
7471             NULL, NULL, NULL, NULL, NULL, NULL),
7472
7473             ('Volume, Number, Issue', 2, 'Volume Number Issue 1', 'Vol.{X}, Number {Y}, Issue {Z}',
7474             'Volume', 1, 48, 99999, 1, NULL,
7475             'Number', 1, 4, 12, 1, NULL,
7476             'Issue', 1, 1, 4, 1, NULL),
7477
7478             ('Volume, Number', 3, 'Volume Number 1', 'Vol {X}, No {Y}',
7479             'Volume', 1, 12, 99999, 1, NULL,
7480             'Number', 1, 1, 12, 1, NULL,
7481             NULL, NULL, NULL, NULL, NULL, NULL),
7482
7483             ('Seasonal', 4, 'Season Year', '{X} {Y}',
7484             'Season', 1, 1, 3, 0, 'season',
7485             'Year', 1, 4, 99999, 1, NULL,
7486             NULL, NULL, NULL, NULL, NULL, NULL)
7487     |);
7488
7489     $dbh->do(qq|
7490         ALTER TABLE subscription
7491         MODIFY COLUMN numberpattern INTEGER DEFAULT NULL,
7492         MODIFY COLUMN periodicity INTEGER DEFAULT NULL
7493     |);
7494
7495     # Update existing subscriptions
7496
7497     my $query = qq|
7498         SELECT subscriptionid, periodicity, numberingmethod,
7499             add1, every1, whenmorethan1, setto1,
7500             add2, every2, whenmorethan2, setto2,
7501             add3, every3, whenmorethan3, setto3
7502         FROM subscription
7503         ORDER BY subscriptionid
7504     |;
7505     my $sth = $dbh->prepare($query);
7506     $sth->execute;
7507     my $insert_numberpatterns_sth = $dbh->prepare(qq|
7508         INSERT INTO subscription_numberpatterns
7509              (label, displayorder, description, numberingmethod,
7510             label1, add1, every1, whenmorethan1, setto1, numbering1,
7511             label2, add2, every2, whenmorethan2, setto2, numbering2,
7512             label3, add3, every3, whenmorethan3, setto3, numbering3)
7513         VALUES
7514             (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7515     |);
7516     my $check_numberpatterns_sth = $dbh->prepare(qq|
7517         SELECT * FROM subscription_numberpatterns
7518         WHERE (add1 = ? OR (add1 IS NULL AND ? IS NULL)) AND (add2 = ? OR (add2 IS NULL AND ? IS NULL))
7519         AND (add3 = ? OR (add3 IS NULL AND ? IS NULL)) AND (every1 = ? OR (every1 IS NULL AND ? IS NULL))
7520         AND (every2 = ? OR (every2 IS NULL AND ? IS NULL)) AND (every3 = ? OR (every3 IS NULL AND ? IS NULL))
7521         AND (whenmorethan1 = ? OR (whenmorethan1 IS NULL AND ? IS NULL)) AND (whenmorethan2 = ? OR (whenmorethan2 IS NULL AND ? IS NULL))
7522         AND (whenmorethan3 = ? OR (whenmorethan3 IS NULL AND ? IS NULL)) AND (setto1 = ? OR (setto1 IS NULL AND ? IS NULL))
7523         AND (setto2 = ? OR (setto2 IS NULL AND ? IS NULL)) AND (setto3 = ? OR (setto3 IS NULL AND ? IS NULL))
7524         AND (numberingmethod = ? OR (numberingmethod IS NULL AND ? IS NULL))
7525         LIMIT 1
7526     |);
7527     my $update_subscription_sth = $dbh->prepare(qq|
7528         UPDATE subscription
7529         SET numberpattern = ?,
7530             periodicity = ?
7531         WHERE subscriptionid = ?
7532     |);
7533
7534     my $i = 1;
7535     while(my $sub = $sth->fetchrow_hashref) {
7536         $check_numberpatterns_sth->execute(
7537             $sub->{add1}, $sub->{add1}, $sub->{add2}, $sub->{add2}, $sub->{add3}, $sub->{add3},
7538             $sub->{every1}, $sub->{every1}, $sub->{every2}, $sub->{every2}, $sub->{every3}, $sub->{every3},
7539             $sub->{whenmorethan1}, $sub->{whenmorethan1}, $sub->{whenmorethan2}, $sub->{whenmorethan2},
7540             $sub->{whenmorethan3}, $sub->{whenmorethan3}, $sub->{setto1}, $sub->{setto1}, $sub->{setto2},
7541             $sub->{setto2}, $sub->{setto3}, $sub->{setto3}, $sub->{numberingmethod}, $sub->{numberingmethod}
7542         );
7543         my $p = $check_numberpatterns_sth->fetchrow_hashref;
7544         if (defined $p) {
7545             # Pattern already exists, link to it
7546             $update_subscription_sth->execute($p->{id},
7547                 $frequencies_mapping->{$sub->{periodicity}},
7548                 $sub->{subscriptionid});
7549         } else {
7550             # Create a new numbering pattern for this subscription
7551             my $ok = $insert_numberpatterns_sth->execute(
7552                 "Backup pattern $i", 4+$i, "Automatically created pattern by updatedatabase", $sub->{numberingmethod},
7553                 "X", $sub->{add1}, $sub->{every1}, $sub->{whenmorethan1}, $sub->{setto1}, undef,
7554                 "Y", $sub->{add2}, $sub->{every2}, $sub->{whenmorethan2}, $sub->{setto2}, undef,
7555                 "Z", $sub->{add3}, $sub->{every3}, $sub->{whenmorethan3}, $sub->{setto3}, undef
7556             );
7557             if($ok) {
7558                 my $id = $dbh->last_insert_id(undef, undef, 'subscription_numberpatterns', undef);
7559                 # Link to subscription_numberpatterns and subscription_frequencies
7560                 $update_subscription_sth->execute($id,
7561                     $frequencies_mapping->{$sub->{periodicity}},
7562                     $sub->{subscriptionid});
7563             }
7564             $i++;
7565         }
7566     }
7567
7568     # Remove now useless columns
7569     $dbh->do(qq|
7570         ALTER TABLE subscription
7571         DROP COLUMN numberingmethod,
7572         DROP COLUMN add1,
7573         DROP COLUMN every1,
7574         DROP COLUMN whenmorethan1,
7575         DROP COLUMN setto1,
7576         DROP COLUMN add2,
7577         DROP COLUMN every2,
7578         DROP COLUMN whenmorethan2,
7579         DROP COLUMN setto2,
7580         DROP COLUMN add3,
7581         DROP COLUMN every3,
7582         DROP COLUMN whenmorethan3,
7583         DROP COLUMN setto3,
7584         DROP COLUMN dow,
7585         DROP COLUMN issuesatonce,
7586         DROP COLUMN hemisphere,
7587         ADD COLUMN countissuesperunit INTEGER NOT NULL DEFAULT 1 AFTER periodicity,
7588         ADD COLUMN skip_serialseq BOOLEAN NOT NULL DEFAULT 0 AFTER irregularity,
7589         ADD COLUMN locale VARCHAR(80) DEFAULT NULL AFTER numberpattern,
7590         ADD CONSTRAINT subscription_ibfk_1 FOREIGN KEY (periodicity) REFERENCES subscription_frequencies (id) ON DELETE SET NULL ON UPDATE CASCADE,
7591         ADD CONSTRAINT subscription_ibfk_2 FOREIGN KEY (numberpattern) REFERENCES subscription_numberpatterns (id) ON DELETE SET NULL ON UPDATE CASCADE
7592     |);
7593
7594     # Set firstacquidate if not already set (firstacquidate is now mandatory)
7595     my $get_first_planneddate_sth = $dbh->prepare(qq|
7596         SELECT planneddate
7597         FROM serial
7598         WHERE subscriptionid = ?
7599         ORDER BY serialid
7600         LIMIT 1
7601     |);
7602     my $update_firstacquidate_sth = $dbh->prepare(qq|
7603         UPDATE subscription
7604         SET firstacquidate = ?
7605         WHERE subscriptionid = ?
7606     |);
7607
7608     sanitize_zero_date('subscription', 'firstacquidate');
7609     my $get_subscriptions_sth = $dbh->prepare(qq|
7610         SELECT subscriptionid, startdate
7611         FROM subscription
7612         WHERE firstacquidate IS NULL
7613           OR firstacquidate = '0000-00-00'
7614     |);
7615     $get_subscriptions_sth->execute;
7616     while ( my ($subscriptionid, $startdate) = $get_subscriptions_sth->fetchrow ) {
7617         # Try to get the planned date of the first serial
7618         $get_first_planneddate_sth->execute($subscriptionid);
7619         my ($first_planneddate) = $get_first_planneddate_sth->fetchrow;
7620         if ($first_planneddate and $first_planneddate =~ /^\d{4}-\d{2}-\d{2}$/) {
7621             $update_firstacquidate_sth->execute($first_planneddate, $subscriptionid);
7622         } else {
7623             # Defaults to subscription start date
7624             $update_firstacquidate_sth->execute($startdate, $subscriptionid);
7625         }
7626     }
7627
7628     print "Upgrade to $DBversion done (Bug 7688: add subscription_frequencies and subscription_numberpatterns tables)\n";
7629     SetVersion($DBversion);
7630 }
7631
7632 $DBversion = "3.13.00.034";
7633 if ( CheckVersion($DBversion) ) {
7634     $dbh->do("
7635         ALTER TABLE `import_batches`
7636         CHANGE `item_action` `item_action`
7637           ENUM( 'always_add', 'add_only_for_matches', 'add_only_for_new', 'ignore', 'replace' )
7638           NOT NULL DEFAULT 'always_add'
7639     ");
7640     print "Upgrade to $DBversion done (Bug 7131 - way to overlay items in in marc import)\n";
7641     SetVersion($DBversion);
7642 }
7643
7644 $DBversion ="3.13.00.035";
7645 if ( CheckVersion($DBversion) ) {
7646     $dbh->do(q{
7647 CREATE TABLE borrower_debarments (
7648   borrower_debarment_id int(11) NOT NULL AUTO_INCREMENT,
7649   borrowernumber int(11) NOT NULL,
7650   expiration date DEFAULT NULL,
7651   `type` enum('SUSPENSION','OVERDUES','MANUAL') NOT NULL DEFAULT 'MANUAL',
7652   `comment` text,
7653   manager_id int(11) DEFAULT NULL,
7654   created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
7655   updated timestamp NULL DEFAULT NULL,
7656   PRIMARY KEY (borrower_debarment_id),
7657   KEY borrowernumber (borrowernumber) ,
7658   CONSTRAINT `borrower_debarments_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`)
7659     ON DELETE CASCADE ON UPDATE CASCADE
7660 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7661     });
7662
7663     # debarments with end date
7664     $dbh->do(q{
7665 INSERT INTO borrower_debarments ( borrowernumber, expiration, comment ) SELECT borrowernumber, debarred, debarredcomment FROM borrowers WHERE debarred IS NOT NULL AND debarred <> '9999-12-31'
7666     });
7667     # debarments with no end date
7668     $dbh->do(q{
7669 INSERT INTO borrower_debarments ( borrowernumber, comment ) SELECT borrowernumber, debarredcomment FROM borrowers WHERE debarred = '9999-12-31'
7670     });
7671
7672     $dbh->do(q{
7673 INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
7674 ('AutoRemoveOverduesRestrictions','0','Defines whether an OVERDUES debarment should be lifted automatically if all overdue items are returned by the patron.','YesNo')
7675     });
7676
7677     print "Upgrade to $DBversion done (Bug 2720 - Overdues which debar automatically should undebar automatically when returned)\n";
7678     SetVersion($DBversion);
7679 }
7680
7681 $DBversion = "3.13.00.036";
7682 if ( CheckVersion($DBversion) ) {
7683     $dbh->do(qq{
7684         INSERT INTO systempreferences (variable, value, explanation, options, type)
7685         VALUES ('StaffDetailItemSelection', '1', 'Enable item selection in record detail page', NULL, 'YesNo')
7686     });
7687     print "Upgrade to $DBversion done (Add system preference StaffDetailItemSelection)\n";
7688     SetVersion($DBversion);
7689 }
7690
7691 $DBversion = "3.13.00.037";
7692 if ( CheckVersion($DBversion) ) {
7693     #add phone if it is not there already (explains the ignore option)
7694     $dbh->do("
7695 INSERT IGNORE INTO message_transport_types (message_transport_type) values ('phone');
7696     ");
7697     print "Upgrade to $DBversion done (Bug 10572: Add phone to message_transport_types table for new installs)\n";
7698     SetVersion($DBversion);
7699 }
7700
7701 $DBversion = "3.13.00.038";
7702 if ( CheckVersion($DBversion) ) {
7703     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES(15, 'superserials', 'Manage subscriptions from any branch (only applies when IndependentBranches is used)')");
7704     print "Upgrade to $DBversion done (Bug 8435: Add superserials permission)\n";
7705     SetVersion($DBversion);
7706 }
7707
7708 $DBversion = "3.13.00.039";
7709 if ( CheckVersion($DBversion) ) {
7710     $dbh->do("
7711         ALTER TABLE aqbasket ADD branch varchar(10) default NULL
7712     ");
7713     $dbh->do("
7714         ALTER TABLE aqbasket
7715         ADD CONSTRAINT aqbasket_ibfk_4 FOREIGN KEY (branch)
7716             REFERENCES branches (branchcode)
7717             ON UPDATE CASCADE ON DELETE SET NULL
7718     ");
7719     $dbh->do("
7720         DROP TABLE IF EXISTS aqbasketusers
7721     ");
7722     $dbh->do("
7723         CREATE TABLE aqbasketusers (
7724             basketno int(11) NOT NULL,
7725             borrowernumber int(11) NOT NULL,
7726             PRIMARY KEY (basketno,borrowernumber),
7727             CONSTRAINT aqbasketusers_ibfk_1 FOREIGN KEY (basketno) REFERENCES aqbasket (basketno) ON DELETE CASCADE ON UPDATE CASCADE,
7728             CONSTRAINT aqbasketusers_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
7729         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7730     ");
7731     $dbh->do("
7732         INSERT INTO permissions (module_bit, code, description)
7733         VALUES (11, 'order_manage_all', 'Manage all orders and baskets, regardless of restrictions on them')
7734     ");
7735
7736     print "Upgrade to $DBversion done (Add branch and users list to baskets. "
7737         . "New permission order_manage_all)\n";
7738     SetVersion($DBversion);
7739 }
7740
7741 $DBversion = "3.13.00.040";
7742 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
7743     $dbh->do("CREATE TABLE IF NOT EXISTS marc_modification_templates (
7744               template_id int(11) NOT NULL auto_increment,
7745               name text NOT NULL,
7746               PRIMARY KEY  (template_id)
7747               ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
7748     );
7749
7750     $dbh->do("
7751       CREATE TABLE IF NOT EXISTS marc_modification_template_actions (
7752       mmta_id int(11) NOT NULL auto_increment,
7753       template_id int(11) NOT NULL,
7754       ordering int(3) NOT NULL,
7755       action enum('delete_field','update_field','move_field','copy_field') NOT NULL,
7756       field_number smallint(6) NOT NULL default '0',
7757       from_field varchar(3) NOT NULL,
7758       from_subfield varchar(1) NULL,
7759       field_value varchar(100) default NULL,
7760       to_field varchar(3) default NULL,
7761       to_subfield varchar(1) default NULL,
7762       to_regex_search text,
7763       to_regex_replace text,
7764       to_regex_modifiers varchar(8) default '',
7765       conditional enum('if','unless') default NULL,
7766       conditional_field varchar(3) default NULL,
7767       conditional_subfield varchar(1) default NULL,
7768       conditional_comparison enum('exists','not_exists','equals','not_equals') default NULL,
7769       conditional_value text,
7770       conditional_regex tinyint(1) NOT NULL default '0',
7771       description text,
7772       PRIMARY KEY  (mmta_id),
7773       CONSTRAINT `mmta_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `marc_modification_templates` (`template_id`) ON DELETE CASCADE ON UPDATE CASCADE
7774       ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
7775     ");
7776
7777     $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'marc_modification_templates', 'Manage marc modification templates')");
7778
7779     print "Upgrade to $DBversion done ( Bug 8015: Added tables for MARC Modification Framework )\n";
7780     SetVersion($DBversion);
7781 }
7782
7783 $DBversion = "3.13.00.041";
7784 if(CheckVersion($DBversion)) {
7785     $dbh->do(q{
7786         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('AcqItemSetSubfieldsWhenReceived','','Set subfields for item when items are created when receiving (e.g. o=5|a="foo bar")','','Free');
7787     });
7788     print "Upgrade to $DBversion done (Bug 10986: Added AcqItemSetSubfieldsWhenReceived syspref)\n";
7789     SetVersion($DBversion);
7790 }
7791
7792 $DBversion = "3.13.00.042";
7793 if(CheckVersion($DBversion)) {
7794     print "Upgrade to $DBversion done (Koha 3.14 beta)\n";
7795     SetVersion($DBversion);
7796 }
7797
7798 $DBversion = "3.13.00.043";
7799 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
7800     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('SearchEngine','Zebra','Solr|Zebra','Search Engine','Choice')");
7801     print "Upgrade to $DBversion done (Bug 11196: Add system preference SearchEngine if missing )\n";
7802     SetVersion($DBversion);
7803 }
7804
7805 $DBversion = "3.14.00.000";
7806 if ( CheckVersion($DBversion) ) {
7807     print "Upgrade to $DBversion done (3.14.0 release)\n";
7808     SetVersion ($DBversion);
7809 }
7810
7811 $DBversion = '3.15.00.000';
7812 if ( CheckVersion($DBversion) ) {
7813     print "Upgrade to $DBversion done (the road goes ever on)\n";
7814     SetVersion ($DBversion);
7815 }
7816
7817 $DBversion = "3.15.00.001";
7818 if ( CheckVersion($DBversion) ) {
7819     $dbh->do("UPDATE systempreferences SET value='clear' where variable = 'CircAutoPrintQuickSlip' and value = '0'");
7820     $dbh->do("UPDATE systempreferences SET value='qslip' where variable = 'CircAutoPrintQuickSlip' and value = '1'");
7821     $dbh->do("UPDATE systempreferences SET explanation = 'Choose what should happen when an empty barcode field is submitted in circulation: Display a print quick slip window, Display a print slip window or Clear the screen.', type = 'Choice' where variable = 'CircAutoPrintQuickSlip'");
7822     print "Upgrade to $DBversion done (Bug 11040: Add option to print full slip when checking out a null barcode)\n";
7823     SetVersion($DBversion);
7824 }
7825
7826 $DBversion = "3.15.00.002";
7827 if(CheckVersion($DBversion)) {
7828     $dbh->do("ALTER TABLE deleteditems MODIFY materials text;");
7829     print "Upgrade to $DBversion done (Bug 11275: alter deleteditems.materials from varchar(10) to text)\n";
7830     SetVersion($DBversion);
7831 }
7832
7833 $DBversion = "3.15.00.003";
7834 if ( CheckVersion($DBversion) ) {
7835     $dbh->do(q{
7836         UPDATE accountlines
7837         SET description = ''
7838         WHERE description IN (
7839             ' New Card',
7840             ' Fine',
7841             ' Sundry',
7842             'Writeoff',
7843             ' Account Management fee',
7844             'Payment,thanks', 'Payment,thanks - ',
7845             ' Lost Item'
7846         )
7847     });
7848     print "Upgrade to $DBversion done (Bug 2546: Update fine descriptions)\n";
7849     SetVersion($DBversion);
7850 }
7851
7852 $DBversion = "3.15.00.004";
7853 if ( CheckVersion($DBversion) ) {
7854     if ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
7855         $dbh->do(qq{
7856             INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
7857             kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link,
7858             defaultvalue) VALUES
7859             ('015', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7860             ('020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7861             ('024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7862             ('027', 'q', 'Qualifying information', 'Qualifying information', 1, 0, '', 0, '', '', '', 0, 0, '', '', '', NULL),
7863             ('800', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7864             ('810', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7865             ('811', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL),
7866             ('830', '7', 'Control subfield', 'Control subfield', 0, 0, '', 8, '', '', '', NULL, -6, '', '', '', NULL);
7867         });
7868         $dbh->do(qq{
7869             INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
7870             mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
7871             ('', '020', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', ''),
7872             ('', '024', 'q', 'Qualifying information', 'Qualifying information', 1, 0, 0, NULL, NULL, NULL, 0, 0, '', '', '');
7873         });
7874     }
7875     print "Upgrade to $DBversion done (Bug 10970 - Update MARC21 frameworks to Update Nr. 17 - DB update)\n";
7876     SetVersion($DBversion);
7877 }
7878
7879 $DBversion = "3.15.00.005";
7880 if ( CheckVersion($DBversion) ) {
7881    $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AcquisitionDetails', '1', '', 'Hide/Show acquisition details on the biblio detail page.', 'YesNo');");
7882    print "Upgrade to $DBversion done (Bug 8230: Add AcquisitionDetails system preference)\n";
7883    SetVersion ($DBversion);
7884 }
7885
7886 $DBversion = "3.15.00.006";
7887 if(CheckVersion($DBversion)) {
7888     $dbh->do(q{
7889         ALTER TABLE `borrowers`
7890         ADD KEY `surname_idx` (`surname`(255)),
7891         ADD KEY `firstname_idx` (`firstname`(255)),
7892         ADD KEY `othernames_idx` (`othernames`(255))
7893     });
7894     print "Upgrade to $DBversion done (Bug 11249 - Add DB indexes on borrower names)\n";
7895     SetVersion($DBversion);
7896 }
7897
7898 $DBversion = "3.15.00.007";
7899 if ( CheckVersion($DBversion) ) {
7900    $dbh->do("ALTER TABLE items ADD itemlost_on DATETIME NULL AFTER itemlost");
7901    $dbh->do("ALTER TABLE items ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7902    $dbh->do("ALTER TABLE deleteditems ADD itemlost_on DATETIME NULL AFTER itemlost");
7903    $dbh->do("ALTER TABLE deleteditems ADD withdrawn_on DATETIME NULL AFTER withdrawn");
7904    print "Upgrade to $DBversion done (Bug 9673 - Track when items are marked as lost or withdrawn)\n";
7905    SetVersion ($DBversion);
7906 }
7907
7908 $DBversion = "3.15.00.008";
7909 if ( CheckVersion($DBversion) ) {
7910     $dbh->do(q{
7911         ALTER TABLE collections_tracking CHANGE ctId collections_tracking_id integer(11) NOT NULL auto_increment;
7912     });
7913     print "Upgrade to $DBversion done (Bug 11384) - change name of collections_tracker.ctId column)\n";
7914    SetVersion ($DBversion);
7915 }
7916
7917 $DBversion = "3.15.00.009";
7918 if ( CheckVersion($DBversion) ) {
7919     $dbh->do(q{
7920         ALTER TABLE suggestions MODIFY suggesteddate DATE NOT NULL
7921     });
7922     print "Upgrade to $DBversion done (Bug 11391) - drop default value on suggestions.suggesteddate column)\n";
7923    SetVersion ($DBversion);
7924 }
7925
7926 $DBversion = "3.15.00.010";
7927 if(CheckVersion($DBversion)) {
7928     $dbh->do("ALTER TABLE deleteditems DROP COLUMN marc");
7929     print "Upgrade to $DBversion done (Bug 6331: remove obsolete column in deleteditems.marc)\n";
7930     SetVersion ($DBversion);
7931 }
7932
7933 $DBversion = "3.15.00.011";
7934 if(CheckVersion($DBversion)) {
7935     $dbh->do("UPDATE marc_subfield_structure SET maxlength=9999 WHERE maxlength IS NULL OR maxlength=0;");
7936     print "Upgrade to $DBversion done (Bug 8018: set 9999 as default max length for subfields)\n";
7937     SetVersion ($DBversion);
7938 }
7939
7940 $DBversion = "3.15.00.012";
7941 if ( CheckVersion($DBversion) ) {
7942     $dbh->do(q{
7943         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'force_checkout', 'Force checkout if a limitation exists')
7944     });
7945     $dbh->do(q{
7946         INSERT INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_restrictions', 'Manage restrictions for accounts')
7947     });
7948     $dbh->do(q{
7949         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7950             SELECT user_permissions.borrowernumber, 1, 'force_checkout'
7951             FROM user_permissions
7952             LEFT JOIN borrowers USING(borrowernumber)
7953             WHERE borrowers.flags & (1 << 1)
7954     });
7955     $dbh->do(q{
7956         INSERT INTO user_permissions (borrowernumber, module_bit, code)
7957             SELECT user_permissions.borrowernumber, 1, 'manage_restrictions'
7958             FROM user_permissions
7959             LEFT JOIN borrowers USING(borrowernumber)
7960             WHERE borrowers.flags & (1 << 1)
7961     });
7962
7963     print "Upgrade to $DBversion done (Bug 10863 - Add permissions force_checkout and manage_restrictions)\n";
7964     SetVersion($DBversion);
7965 }
7966
7967 $DBversion = "3.15.00.013";
7968 if(CheckVersion($DBversion)) {
7969     $dbh->do(q{
7970         UPDATE systempreferences
7971         SET explanation = 'Upon receiving items, update their subfields if they were created when placing an order (e.g. o=5|a="foo bar")'
7972         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7973     });
7974
7975     $dbh->do(q{
7976         UPDATE systempreferences
7977         SET value = ''
7978         WHERE variable = "AcqItemSetSubfieldsWhenReceived"
7979             AND value = "0"
7980     });
7981     print "Upgrade to $DBversion done (Bug 11237: Update explanation and default value for AcqItemSetSubfieldsWhenReceived syspref)\n";
7982     SetVersion($DBversion);
7983 }
7984
7985 $DBversion = "3.15.00.014";
7986 if (CheckVersion($DBversion)) {
7987     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('SelfCheckReceiptPrompt', '1', 'NULL', 'If ON, print receipt dialog pops up when self checkout is finished.', 'YesNo');");
7988     print "Upgrade to $DBversion done (Bug 11415: add system preference for automatic self checkout receipt printing)\n";
7989     SetVersion($DBversion);
7990 }
7991
7992 $DBversion = "3.15.00.015";
7993 if (CheckVersion($DBversion)) {
7994     $dbh->do("INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
7995         ('OpacSuggestionManagedBy',1,'','Show the name of the staff member who managed a suggestion in OPAC','YesNo');");
7996     print "Upgrade to $DBversion done (Bug 10907: Add OpacSuggestionManagedBy system preference)\n";
7997     SetVersion($DBversion);
7998 }
7999
8000 $DBversion = "3.15.00.016";
8001 if (CheckVersion($DBversion)) {
8002     $dbh->do("ALTER TABLE biblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8003     $dbh->do("ALTER TABLE deletedbiblioitems CHANGE url url TEXT NULL DEFAULT NULL");
8004     print "Upgrade to $DBversion done (Bug 11268 - Biblioitems URL field is too small for some URLs)\n";
8005     SetVersion($DBversion);
8006 }
8007
8008 $DBversion = "3.15.00.017";
8009 if(CheckVersion($DBversion)) {
8010     $dbh->do(q{
8011         UPDATE systempreferences
8012         SET explanation = 'Define the contents of UNIMARC authority control field 100 position 08-35'
8013         WHERE variable = "UNIMARCAuthorityField100"
8014     });
8015     $dbh->do(q{
8016         UPDATE systempreferences
8017         SET explanation = 'Define the contents of MARC21 authority control field 008 position 06-39'
8018         WHERE variable = "MARCAuthorityControlField008"
8019     });
8020     $dbh->do(q{
8021         UPDATE systempreferences
8022         SET explanation = 'Define MARC Organization Code for MARC21 records - http://www.loc.gov/marc/organizations/orgshome.html'
8023         WHERE variable = "MARCOrgCode"
8024     });
8025     print "Upgrade to $DBversion done (Bug 11611 - fix possible confusion between UNIMARC and MARC21 in some sysprefs)\n";
8026     SetVersion($DBversion);
8027 }
8028
8029 $DBversion = "3.15.00.018";
8030 if ( CheckVersion($DBversion) ) {
8031     $dbh->{AutoCommit} = 0;
8032     $dbh->{RaiseError} = 1;
8033
8034     eval {
8035         $dbh->selectcol_arrayref(q|SELECT COUNT(*) FROM roadtype|);
8036     };
8037     unless ( $@ ) {
8038         my $av_added = $dbh->do(q|
8039             INSERT INTO authorised_values(category, authorised_value, lib, lib_opac)
8040                 SELECT 'ROADTYPE', roadtypeid, road_type, road_type
8041                 FROM roadtype;
8042         |);
8043
8044         my $rt_deleted = $dbh->do(q|
8045             DELETE FROM roadtype
8046         |);
8047
8048         if ( $av_added == $rt_deleted or $rt_deleted eq "0E0" ) {
8049             $dbh->do(q|
8050                 DROP TABLE roadtype;
8051             |);
8052             $dbh->commit;
8053             print "Upgrade to $DBversion done (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values)\n";
8054             SetVersion($DBversion);
8055         } else {
8056             print "Upgrade to $DBversion failed (Bug 7372: Move road types from the roadtype table to the ROADTYPE authorised values.\nTransaction aborted because $@\n)";
8057             $dbh->rollback;
8058         }
8059     }
8060     $dbh->{AutoCommit} = 1;
8061     $dbh->{RaiseError} = 0;
8062 }
8063
8064 $DBversion = "3.15.00.019";
8065 if ( CheckVersion($DBversion) ) {
8066     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OpacMaxItemsToDisplay','50','','Max items to display at the OPAC on a biblio detail','Integer')");
8067     print "Upgrade to $DBversion done (Bug 11256: Add system preference OpacMaxItemsToDisplay)\n";
8068     SetVersion($DBversion);
8069 }
8070
8071 $DBversion = "3.15.00.020";
8072 if ( CheckVersion($DBversion) ) {
8073     $dbh->do(q|
8074         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('MaxItemsForBatch','1000',NULL,'Max number of items record to process in a batch (modification or deletion)','Integer')
8075     |);
8076     print "Upgrade to $DBversion done (Bug 11343: Add system preference MaxItemsForBatch )\n";
8077     SetVersion($DBversion);
8078 }
8079
8080 $DBversion = "3.15.00.021";
8081 if(CheckVersion($DBversion)) {
8082     $dbh->do(q{
8083         ALTER TABLE `action_logs`
8084             DROP KEY timestamp,
8085             ADD KEY `timestamp_idx` (`timestamp`),
8086             ADD KEY `user_idx` (`user`),
8087             ADD KEY `module_idx` (`module`(255)),
8088             ADD KEY `action_idx` (`action`(255)),
8089             ADD KEY `object_idx` (`object`),
8090             ADD KEY `info_idx` (`info`(255))
8091     });
8092     print "Upgrade to $DBversion done (Bug 3445: Add indexes to action_logs table)\n";
8093     SetVersion($DBversion);
8094 }
8095
8096 $DBversion = "3.15.00.022";
8097 if (CheckVersion($DBversion)) {
8098     $dbh->do(q|
8099         DELETE FROM systempreferences WHERE variable= "memberofinstitution"
8100     |);
8101     print "Upgrade to $DBversion done (Bug 11751: Remove memberofinstitytion system preference)\n";
8102     SetVersion($DBversion);
8103 }
8104
8105 $DBversion = "3.15.00.023";
8106 if ( CheckVersion($DBversion) ) {
8107    $dbh->do("
8108        INSERT INTO systempreferences (variable,value,options,explanation,type)
8109        VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free');
8110     ");
8111    print "Upgrade to $DBversion done (Bug 10861: Add CardnumberLength syspref)\n";
8112    SetVersion ($DBversion);
8113 }
8114
8115 $DBversion = "3.15.00.024";
8116 if ( CheckVersion($DBversion) ) {
8117     $dbh->do(q{
8118         DELETE FROM systempreferences WHERE variable = 'NoZebraIndexes'
8119     });
8120     print "Upgrade to $DBversion done (Bug 10012 - remove last vestiges of NoZebra)\n";
8121     SetVersion($DBversion);
8122 }
8123
8124 $DBversion = "3.15.00.025";
8125 if ( CheckVersion($DBversion) ) {
8126     $dbh->do(q{
8127         DROP TABLE aqorderdelivery;
8128     });
8129     print "Upgrade to $DBversion done (Bug 11928 - remove unused table)\n";
8130     SetVersion($DBversion);
8131 }
8132
8133 $DBversion = "3.15.00.026";
8134 if ( CheckVersion($DBversion) ) {
8135     $dbh->do(q{
8136         UPDATE language_descriptions SET description = 'Հայերեն' WHERE subtag = 'hy' AND lang = 'hy';
8137     });
8138     print "Upgrade to $DBversion done (Bug 11973 - Fix Armenian language description)\n";
8139     SetVersion($DBversion);
8140 }
8141
8142 $DBversion = "3.15.00.027";
8143 if (CheckVersion($DBversion)) {
8144     $dbh->do(q{
8145         ALTER TABLE opac_news ADD branchcode varchar(10) DEFAULT NULL
8146                                   AFTER idnew,
8147                               ADD CONSTRAINT opac_news_branchcode_ibfk
8148                                   FOREIGN KEY (branchcode)
8149                                   REFERENCES branches (branchcode)
8150                                   ON DELETE CASCADE ON UPDATE CASCADE;
8151     });
8152     print "Upgrade to $DBversion done (Bug 7567: Add branchcode to opac_news)\n";
8153     SetVersion($DBversion);
8154 }
8155
8156 $DBversion = "3.15.00.028";
8157 if(CheckVersion($DBversion)) {
8158     $dbh->do(q{
8159         ALTER TABLE issuingrules ADD norenewalbefore int(4) default NULL AFTER renewalperiod
8160     });
8161     print "Upgrade to $DBversion done (Bug 7413: Allow OPAC renewal x days before due date)\n";
8162     SetVersion($DBversion);
8163 }
8164
8165 $DBversion = "3.15.00.029";
8166 if ( CheckVersion($DBversion) ) {
8167     $dbh->do(q{
8168         UPDATE borrower_debarments SET expiration = NULL WHERE expiration = '9999-12-31'
8169     });
8170     print "Upgrade to $DBversion done (Bug 11846 - correct borrower_debarments with expiration 9999-12-31)\n";
8171     SetVersion($DBversion);
8172 }
8173
8174 $DBversion = "3.15.00.030";
8175 if(CheckVersion($DBversion)) {
8176     $dbh->do(q|
8177         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('OPACMySummaryNote','','','Note to display on the patron summary page. This note only appears if the patron is connected.','Free')
8178     |);
8179     print "Upgrade to $DBversion done (Bug 12052: Add OPACMySummaryNote syspref)\n";
8180     SetVersion($DBversion);
8181 }
8182
8183 $DBversion = "3.15.00.031";
8184 if ( CheckVersion($DBversion) ) {
8185    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'writeoff', 'Write off fines and fees')");
8186    $dbh->do("INSERT INTO permissions (module_bit, code, description) VALUES ('10', 'remaining_permissions', 'Remaining permissions for managing fines and fees')");
8187    print "Upgrade to $DBversion done (Bug 9448 - Add separate permission for writing off fees)\n";
8188    SetVersion ($DBversion);
8189 }
8190
8191 $DBversion = "3.15.00.032";
8192 if ( CheckVersion($DBversion) ) {
8193     $dbh->do("ALTER TABLE aqorders CHANGE notes order_internalnote MEDIUMTEXT;");
8194     $dbh->do("ALTER TABLE aqorders ADD COLUMN order_vendornote MEDIUMTEXT AFTER order_internalnote;");
8195     print "Upgrade to $DBversion done (Bug 9416 - In each order, add a new note made for the vendor)\n";
8196    SetVersion ($DBversion);
8197 }
8198
8199 $DBversion = "3.15.00.033";
8200 if ( CheckVersion($DBversion) ) {
8201     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NoLoginInstructions', '', '60|10', 'Instructions to display on the OPAC login form when a patron is not logged in', 'Textarea')");
8202     print "Upgrade to $DBversion done (Bug 10951: Add NoLoginInstructions pref)\n";
8203     SetVersion($DBversion);
8204 }
8205
8206 $DBversion = "3.15.00.034";
8207 if ( CheckVersion($DBversion) ) {
8208     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('AdvancedSearchLanguages','','','ISO 639-2 codes of languages you wish to see appear as an advanced search option.  Example: eng|fra|ita','Textarea')");
8209     print "Upgrade to $DBversion done (Bug 10986: system preferences to limit languages in advanced search )\n";
8210     SetVersion ($DBversion);
8211 }
8212
8213 $DBversion = "3.15.00.035";
8214 if ( CheckVersion($DBversion) ) {
8215     #insert a notice for sharing a list and accepting a share
8216     $dbh->do("
8217 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8218 VALUES ( 'members', 'SHARE_INVITE', '', 'Invitation for sharing a list', '0', 'Share list <<listname>>', 'Dear patron,
8219
8220 One of our patrons, <<borrowers.firstname>> <<borrowers.surname>>, invites you to share a list <<listname>> in our library catalog.
8221
8222 To access this shared list, please click on the following URL or copy-and-paste it into your browser address bar.
8223
8224 <<shareurl>>
8225
8226 In case you are not a patron in our library or do not want to accept this invitation, please ignore this mail. Note also that this invitation expires within two weeks.
8227
8228 Thank you.
8229
8230 Your library.'
8231     )");
8232     $dbh->do("
8233 INSERT INTO letter (module, code, branchcode, name, is_html, title, content)
8234 VALUES ( 'members', 'SHARE_ACCEPT', '', 'Notification about an accepted share', '0', 'Share on list <<listname>> accepted', 'Dear patron,
8235
8236 We want to inform you that <<borrowers.firstname>> <<borrowers.surname>> accepted your invitation to share your list <<listname>> in our library catalog.
8237
8238 Thank you.
8239
8240 Your library.'
8241     )");
8242     print "Upgrade to $DBversion done (Bug 9032: Share a list)\n";
8243     SetVersion($DBversion);
8244 }
8245
8246 $DBversion = "3.15.00.036";
8247 if ( CheckVersion($DBversion) ) {
8248     $dbh->do(q{
8249         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
8250         VALUES('AllowMultipleIssuesOnABiblio',1,'Allow/Don\'t allow patrons to check out multiple items from one biblio','','YesNo')
8251     });
8252
8253     print "Upgrade to $DBversion done (Bug 10859 - Add system preference AllowMultipleIssuesOnABiblio)\n";
8254     SetVersion($DBversion);
8255 }
8256
8257 $DBversion = "3.15.00.037";
8258 if(CheckVersion($DBversion)) {
8259     $dbh->do(q{
8260         ALTER TABLE itemtypes ADD sip_media_type VARCHAR( 3 ) DEFAULT NULL AFTER checkinmsgtype
8261     });
8262     $dbh->do(q{
8263         INSERT INTO authorised_values (category, authorised_value, lib) VALUES
8264          ('SIP_MEDIA_TYPE', '000', 'Other'),
8265          ('SIP_MEDIA_TYPE', '001', 'Book'),
8266          ('SIP_MEDIA_TYPE', '002', 'Magazine'),
8267          ('SIP_MEDIA_TYPE', '003', 'Bound journal'),
8268          ('SIP_MEDIA_TYPE', '004', 'Audio tape'),
8269          ('SIP_MEDIA_TYPE', '005', 'Video tape'),
8270          ('SIP_MEDIA_TYPE', '006', 'CD/CDROM'),
8271          ('SIP_MEDIA_TYPE', '007', 'Diskette'),
8272          ('SIP_MEDIA_TYPE', '008', 'Book with diskette'),
8273          ('SIP_MEDIA_TYPE', '009', 'Book with CD'),
8274          ('SIP_MEDIA_TYPE', '010', 'Book with audio tape')
8275     });
8276     print "Upgrade to $DBversion done (Bug 11351 - Add support for SIP2 media type)\n";
8277     SetVersion($DBversion);
8278 }
8279
8280 $DBversion = '3.15.00.038';
8281 if ( CheckVersion($DBversion) ) {
8282     $dbh->do(q{
8283         INSERT INTO  systempreferences (
8284             variable,
8285             value,
8286             options,
8287             explanation,
8288             type
8289             )
8290         VALUES (
8291             'DisplayLibraryFacets',  'holding',  'home|holding|both',  'Defines which library facets to display.',  'Choice'
8292         );
8293     });
8294     print "Upgrade to $DBversion done (Bug 11334 - Add facet for home library)\n";
8295     SetVersion ($DBversion);
8296 }
8297
8298 $DBversion = "3.15.00.039";
8299 if ( CheckVersion($DBversion) ) {
8300
8301     $dbh->do( q{
8302         ALTER TABLE letter ADD COLUMN message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email' AFTER content
8303     } );
8304
8305     $dbh->do( q{
8306         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8307     } );
8308
8309     $dbh->do( q{
8310         ALTER TABLE letter DROP PRIMARY KEY, ADD PRIMARY KEY (`module`,`code`,`branchcode`, message_transport_type);
8311     } );
8312
8313     $dbh->do( q{
8314         CREATE TABLE overduerules_transport_types(
8315             id INT(11) NOT NULL AUTO_INCREMENT,
8316             branchcode varchar(10) NOT NULL DEFAULT '',
8317             categorycode VARCHAR(10) NOT NULL DEFAULT '',
8318             letternumber INT(1) NOT NULL DEFAULT 1,
8319             message_transport_type VARCHAR(20) NOT NULL DEFAULT 'email',
8320             PRIMARY KEY (id),
8321             CONSTRAINT overduerules_fk FOREIGN KEY (branchcode, categorycode) REFERENCES overduerules (branchcode, categorycode) ON DELETE CASCADE ON UPDATE CASCADE,
8322             CONSTRAINT mtt_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types (message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
8323         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8324     } );
8325
8326     my $sth = $dbh->prepare( q{
8327         SELECT * FROM overduerules;
8328     } );
8329
8330     $sth->execute;
8331     my $sth_insert_mtt = $dbh->prepare( q{
8332         INSERT INTO overduerules_transport_types (branchcode, categorycode, letternumber, message_transport_type) VALUES ( ?, ?, ?, ? )
8333     } );
8334     while ( my $row = $sth->fetchrow_hashref ) {
8335         my $branchcode = $row->{branchcode};
8336         my $categorycode = $row->{categorycode};
8337         for my $letternumber ( 1 .. 3 ) {
8338             next unless $row->{"letter$letternumber"};
8339             $sth_insert_mtt->execute(
8340                 $branchcode, $categorycode, $letternumber, 'email'
8341             );
8342         }
8343     }
8344
8345     print "Upgrade done (Bug 9016: Adds multi transport types management for notices)\n";
8346     SetVersion($DBversion);
8347 }
8348
8349 $DBversion = "3.15.00.040";
8350 if ( CheckVersion($DBversion) ) {
8351     $dbh->do(q|
8352         UPDATE message_transports SET letter_code='HOLD' WHERE letter_code='HOLD_PHONE' OR letter_code='HOLD_PRINT'
8353     |);
8354     $dbh->do(q|
8355         UPDATE letter SET code='HOLD', message_transport_type='print' WHERE code='HOLD_PRINT'
8356     |);
8357     $dbh->do(q|
8358         UPDATE letter SET code='HOLD', message_transport_type='phone' WHERE code='HOLD_PHONE'
8359     |);
8360     print "Upgrade to $DBversion done (Bug 10845: Multi transport types for holds)\n";
8361     SetVersion($DBversion);
8362 }
8363
8364 $DBversion = "3.15.00.041";
8365 if ( CheckVersion($DBversion) ) {
8366     my ( $name ) = $dbh->selectrow_array(q|
8367         SELECT name FROM letter WHERE code="HOLD"
8368     |);
8369     $dbh->do(q|
8370         UPDATE letter
8371         SET code="HOLD",
8372             message_transport_type="phone",
8373             name= ?
8374         WHERE code="HOLD_PHONE"
8375     |, {}, $name);
8376
8377     ( $name ) = $dbh->selectrow_array(q|
8378         SELECT name FROM letter WHERE code="PREDUE"
8379     |);
8380     $dbh->do(q|
8381         UPDATE letter
8382         SET code="PREDUE",
8383             message_transport_type="phone",
8384             name= ?
8385         WHERE code="PREDUE_PHONE"
8386     |, {}, $name);
8387
8388     ( $name ) = $dbh->selectrow_array(q|
8389         SELECT name FROM letter WHERE code="OVERDUE"
8390     |);
8391     $dbh->do(q|
8392         UPDATE letter
8393         SET code="OVERDUE",
8394             message_transport_type="phone",
8395             name= ?
8396         WHERE code="OVERDUE_PHONE"
8397     |, {}, $name);
8398
8399     print "Upgrade to $DBversion done (Bug 11867: Update letters *_PHONE)\n";
8400     SetVersion($DBversion);
8401 }
8402
8403 $DBversion = "3.15.00.042";
8404 if ( CheckVersion($DBversion) ) {
8405     $dbh->do(q{
8406         INSERT INTO systempreferences
8407             (variable,value,explanation,options,type)
8408         VALUES
8409             ('SpecifyReturnDate',0,'Define whether to display \"Specify Return Date\" form in Circulation','','YesNo')
8410     });
8411     print "Upgrade to $DBversion done (Bug 10694 - Allow arbitrary backdating of returns)\n";
8412     SetVersion($DBversion);
8413 }
8414
8415 $DBversion = "3.15.00.043";
8416 if ( CheckVersion($DBversion) ) {
8417     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('MarcFieldsToOrder','','Set the mapping values for a new order line created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea')");
8418    print "Upgrade to $DBversion done (Bug 7180: Added MarcFieldsToOrder syspref)\n";
8419    SetVersion ($DBversion);
8420 }
8421
8422 $DBversion = "3.15.00.044";
8423 if ( CheckVersion($DBversion) ) {
8424     $dbh->do("ALTER TABLE currency ADD isocode VARCHAR(5) default NULL AFTER symbol;");
8425     print "Upgrade to $DBversion done (Added isocode to the currency table)\n";
8426     SetVersion($DBversion);
8427 }
8428
8429 $DBversion = "3.15.00.045";
8430 if ( CheckVersion($DBversion) ) {
8431     $dbh->do("
8432         INSERT INTO systempreferences (variable,value,explanation,options,type)
8433         VALUES (
8434             'BlockExpiredPatronOpacActions',
8435             '0',
8436             'Set whether an expired patron can perform opac actions such as placing holds or renew books, can be overridden on a per patron-type basis',
8437             NULL,
8438             'YesNo'
8439         )
8440     ");
8441     $dbh->do("ALTER TABLE `categories` ADD COLUMN `BlockExpiredPatronOpacActions` TINYINT(1) DEFAULT -1 NOT NULL AFTER category_type");
8442     print "Upgraded to $DBversion done (Bug 6739 - expired patrons not blocked from opac actions)\n";
8443     SetVersion ($DBversion);
8444 }
8445
8446 $DBversion = "3.15.00.046";
8447 if ( CheckVersion($DBversion) ) {
8448     $dbh->do(q|
8449         ALTER TABLE search_history ADD COLUMN type VARCHAR(16) NOT NULL DEFAULT 'biblio' AFTER query_cgi
8450     |);
8451     print "Upgrade to $DBversion done (Bug 10807 - Add db field search_history.type)\n";
8452     SetVersion($DBversion);
8453 }
8454
8455 $DBversion = "3.15.00.047";
8456 if ( CheckVersion($DBversion) ) {
8457     $dbh->do(q|
8458         INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES ('EnableSearchHistory','0','','Enable or disable search history','YesNo')
8459     |);
8460     print "Upgrade to $DBversion done (Bug 10862: Add EnableSearchHistory syspref)\n";
8461     SetVersion($DBversion);
8462 }
8463
8464 $DBversion = "3.15.00.048";
8465 if ( CheckVersion($DBversion) ) {
8466     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacSuppressionRedirect','1','Redirect the opac detail page for suppressed records to an explanatory page (otherwise redirect to 404 error page)','','YesNo')");
8467     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('OpacSuppressionMessage', '','Display this message on the redirect page for suppressed biblios','70|10','Textarea')");
8468     print "Upgrade to $DBversion done (Bug 10195: Records hidden with OpacSuppression can still be accessed)\n";
8469     SetVersion($DBversion);
8470 }
8471
8472 $DBversion = "3.15.00.049";
8473 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8474     $dbh->do("ALTER TABLE biblioitems DROP INDEX isbn");
8475     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn");
8476     $dbh->do("ALTER TABLE biblioitems DROP INDEX issn_idx");
8477     $dbh->do("ALTER TABLE biblioitems
8478               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8479               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8480     ");
8481     $dbh->do("ALTER TABLE biblioitems
8482               ADD INDEX isbn ( isbn ( 255 ) ),
8483               ADD INDEX issn ( issn ( 255 ) )
8484     ");
8485
8486     $dbh->do("ALTER TABLE deletedbiblioitems DROP INDEX isbn");
8487     $dbh->do("ALTER TABLE deletedbiblioitems
8488               CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL,
8489               CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL
8490     ");
8491     $dbh->do("ALTER TABLE deletedbiblioitems
8492               ADD INDEX isbn ( isbn ( 255 ) )
8493     ");
8494
8495     print "Upgrade to $DBversion done (Bug 5377 - Biblioitems isbn and issn fields too small for multiple ISBN and ISSN)\n";
8496     SetVersion($DBversion);
8497 }
8498
8499 $DBversion = "3.15.00.050";
8500 if ( CheckVersion($DBversion) ) {
8501     $dbh->do("
8502         INSERT INTO systempreferences (
8503             variable,
8504             value,
8505             explanation,
8506             type
8507         ) VALUES (
8508             'AggressiveMatchOnISBN',
8509             '0',
8510             'If enabled, attempt to match aggressively by trying all variations of the ISBNs in the imported record as a phrase in the ISBN fields of already cataloged records when matching on ISBN with the record import tool',
8511             'YesNo'
8512         )
8513     ");
8514
8515     print "Upgrade to $DBversion done (Bug 10500 - Improve isbn matching when importing records)\n";
8516     SetVersion($DBversion);
8517 }
8518
8519 $DBversion = "3.15.00.051";
8520 if ( CheckVersion($DBversion) ) {
8521     print "Upgrade to $DBversion done (Koha 3.16 beta)\n";
8522     SetVersion($DBversion);
8523 }
8524
8525 $DBversion = "3.15.00.052";
8526 if ( CheckVersion($DBversion) ) {
8527     print "Upgrade to $DBversion done (Koha 3.16 RC)\n";
8528     SetVersion($DBversion);
8529 }
8530
8531 $DBversion = "3.16.00.000";
8532 if ( CheckVersion($DBversion) ) {
8533     print "Upgrade to $DBversion done (3.16.0 release)\n";
8534     SetVersion ($DBversion);
8535 }
8536
8537 $DBversion = '3.17.00.000';
8538 if ( CheckVersion($DBversion) ) {
8539     print "Upgrade to $DBversion done (there is no time to rest on our laurels)\n";
8540     SetVersion ($DBversion);
8541 }
8542
8543 $DBversion = '3.17.00.001';
8544 if ( CheckVersion($DBversion) ) {
8545    $dbh->do("UPDATE systempreferences SET variable = 'AuthoritySeparator' WHERE variable = 'authoritysep'");
8546    print "Upgrade to $DBversion done (Bug 10330 - Rename system preference authoritysep to AuthoritySeparator)\n";
8547    SetVersion ($DBversion);
8548 }
8549
8550 $DBversion = "3.17.00.002";
8551 if (CheckVersion($DBversion)) {
8552     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,type) VALUES('AcqEnableFiles','0','If enabled, allows librarians to upload and attach arbitrary files to invoice records.','YesNo')");
8553     $dbh->do("
8554 CREATE TABLE IF NOT EXISTS `misc_files` (
8555   `file_id` int(11) NOT NULL AUTO_INCREMENT,
8556   `table_tag` varchar(255) NOT NULL,
8557   `record_id` int(11) NOT NULL,
8558   `file_name` varchar(255) NOT NULL,
8559   `file_type` varchar(255) NOT NULL,
8560   `file_description` varchar(255) DEFAULT NULL,
8561   `file_content` longblob NOT NULL, -- file content
8562   `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
8563   PRIMARY KEY (`file_id`),
8564   KEY `table_tag` (`table_tag`),
8565   KEY `record_id` (`record_id`)
8566 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
8567     ");
8568     print "Upgrade to $DBversion done (Bug 3050 - Add an option to upload scanned invoices)\n";
8569     SetVersion($DBversion);
8570 }
8571
8572 $DBversion = "3.17.00.003";
8573 if (CheckVersion($DBversion)) {
8574     $dbh->do("UPDATE systempreferences SET type = 'Choice', options = '0|1|force' WHERE variable = 'OPACItemHolds'");
8575     print "Upgrade to $DBversion done (Bug 7825 - Changed OPACItemHolds syspref to Choice)\n";
8576     SetVersion($DBversion);
8577 }
8578
8579 $DBversion = "3.17.00.004";
8580 if (CheckVersion($DBversion)) {
8581     $dbh->do("ALTER TABLE categories ADD default_privacy ENUM( 'default', 'never', 'forever' ) NOT NULL DEFAULT 'default' AFTER category_type");
8582     print "Upgrade to $DBversion done (Bug 6254 - can't set patron privacy by default)\n";
8583     SetVersion($DBversion);
8584 }
8585
8586 $DBversion = "3.17.00.005";
8587 if (CheckVersion($DBversion)) {
8588     $dbh->do(q|
8589         ALTER TABLE issuingrules
8590         ADD maxsuspensiondays INT(11) DEFAULT NULL AFTER finedays;
8591     |);
8592     print "Upgrade to $DBversion done (Bug 12230: Add new issuing rule maxsuspensiondays)\n";
8593     SetVersion($DBversion);
8594 }
8595
8596 $DBversion = "3.17.00.006";
8597 if ( CheckVersion($DBversion) ) {
8598     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OpacLocationBranchToDisplay',  'holding',  'holding|home|both',  'In the OPAC, under location show which branch for Location in the record details.',  'Choice')");
8599     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('OpacLocationBranchToDisplayShelving',  'holding',  'holding|home|both',  'In the OPAC, display the shelving location under which which column',  'Choice')");
8600     print "Upgrade to $DBversion done (Bug 7720 - Ambiguity in OPAC Details location.)\n";
8601     SetVersion($DBversion);
8602 }
8603
8604 $DBversion = "3.17.00.007";
8605 if (CheckVersion($DBversion)) {
8606     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('UpdateNotForLoanStatusOnCheckin', '', 'NULL', 'This is a list of value pairs. When an item is checked in, if the not for loan value on the left matches the items not for loan value it will be updated to the right-hand value. E.g. ''-1: 0'' will cause an item that was set to ''Ordered'' to now be available for loan. Each pair of values should be on a separate line.', 'Free');");
8607     print "Upgrade to $DBversion done (Bug 11629 - Add ability to update not for loan status on checkin)\n";
8608     SetVersion($DBversion);
8609 }
8610
8611 $DBversion = "3.17.00.008";
8612 if ( CheckVersion($DBversion) ) {
8613     $dbh->do(q|
8614         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('OPACAcquisitionDetails','0', '','Show the acquisition details at the OPAC','YesNo')
8615     |);
8616     print "Upgrade to $DBversion done (Bug 11169 - Add OPACAcquisitionDetails syspref)\n";
8617     SetVersion($DBversion);
8618 }
8619
8620 $DBversion = "3.17.00.009";
8621 if ( CheckVersion($DBversion) ) {
8622     $dbh->do(q{
8623         DELETE FROM systempreferences WHERE variable = 'UseTablesortForCirc'
8624     });
8625
8626     print "Upgrade to $DBversion done (Bug 11703 - Remove UseTablesortForCirc syspref)\n";
8627     SetVersion($DBversion);
8628 }
8629
8630 $DBversion = "3.17.00.010";
8631 if ( CheckVersion($DBversion) ) {
8632     $dbh->do("DELETE FROM systempreferences WHERE variable='opacsmallimage'");
8633     print "Upgrade to $DBversion done (Bug 11347 - PROG/CCSR deprecation: Remove opacsmallimage system preference)\n";
8634     SetVersion($DBversion);
8635 }
8636
8637 $DBversion = "3.17.00.011";
8638 if ( CheckVersion($DBversion) ) {
8639     $dbh->do("INSERT INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'hr', 'language', 'Croatian','2014-07-24' )");
8640     $dbh->do("INSERT INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'hr','hrv')");
8641     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'hr', 'Hrvatski')");
8642     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'en', 'Croatian')");
8643     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'fr', 'Croate')");
8644     $dbh->do("INSERT INTO language_descriptions(subtag, type, lang, description) VALUES( 'hr', 'language', 'de', 'Kroatisch')");
8645     print "Upgrade to $DBversion done (Bug 12649: Add Croatian language)\n";
8646     SetVersion ($DBversion);
8647 }
8648
8649 $DBversion = "3.17.00.012";
8650 if ( CheckVersion($DBversion) ) {
8651     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowFiltersPulldownMobile'");
8652     print "Upgrade to $DBversion done ( Bug 12512 - PROG/CCSR deprecation: Remove OpacShowFiltersPulldownMobile system preference )\n";
8653     SetVersion ($DBversion);
8654 }
8655
8656 $DBversion = "3.17.00.013";
8657 if ( CheckVersion($DBversion) ) {
8658     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('maxreserves',50,'System-wide maximum number of holds a patron can place','','Integer')");
8659     print "Upgrade to $DBversion done (Re-add system preference maxreserves)\n";
8660     SetVersion ($DBversion);
8661 }
8662
8663 $DBversion = '3.17.00.014';
8664 if ( CheckVersion($DBversion) ) {
8665     $dbh->do("
8666         INSERT INTO systempreferences (variable,value,explanation,type) VALUES
8667         ('OverdueNoticeCalendar',0,'Take calendar into consideration when working out sending overdue notices','YesNo')
8668     ");
8669     print "Upgrade to $DBversion done (Bug 12529 - Adding a syspref to allow the overdue notices to consider the calendar when generating notices)\n";
8670     SetVersion($DBversion);
8671 }
8672
8673 $DBversion = "3.17.00.015";
8674 if ( CheckVersion($DBversion) ) {
8675     $dbh->do(q{
8676         CREATE TABLE IF NOT EXISTS columns_settings (
8677             module varchar(255) NOT NULL,
8678             page varchar(255) NOT NULL,
8679             tablename varchar(255) NOT NULL,
8680             columnname varchar(255) NOT NULL,
8681             cannot_be_toggled int(1) NOT NULL DEFAULT 0,
8682             is_hidden int(1) NOT NULL DEFAULT 0,
8683             PRIMARY KEY(module, page, tablename, columnname)
8684         ) ENGINE=InnoDB DEFAULT CHARSET=utf8
8685     });
8686     print "Upgrade to $DBversion done (Bug 10212 - Create new table columns_settings)\n";
8687     SetVersion ($DBversion);
8688 }
8689
8690 $DBversion = "3.17.00.016";
8691 if ( CheckVersion($DBversion) ) {
8692     $dbh->do("CREATE TABLE aqcontacts (
8693         id int(11) NOT NULL auto_increment,
8694         name varchar(100) default NULL,
8695         position varchar(100) default NULL,
8696         phone varchar(100) default NULL,
8697         altphone varchar(100) default NULL,
8698         fax varchar(100) default NULL,
8699         email varchar(100) default NULL,
8700         notes mediumtext,
8701         claimacquisition BOOLEAN NOT NULL DEFAULT 0,
8702         claimissues BOOLEAN NOT NULL DEFAULT 0,
8703         acqprimary BOOLEAN NOT NULL DEFAULT 0,
8704         serialsprimary BOOLEAN NOT NULL DEFAULT 0,
8705         booksellerid int(11) not NULL,
8706         PRIMARY KEY  (id),
8707         CONSTRAINT booksellerid_aqcontacts_fk FOREIGN KEY (booksellerid)
8708             REFERENCES aqbooksellers (id) ON DELETE CASCADE ON UPDATE CASCADE
8709         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
8710     $dbh->do("INSERT INTO aqcontacts (name, position, phone, altphone, fax,
8711             email, notes, booksellerid, claimacquisition, claimissues, acqprimary, serialsprimary)
8712         SELECT contact, contpos, contphone, contaltphone, contfax, contemail,
8713             contnotes, id, 1, 1, 1, 1 FROM aqbooksellers;");
8714     $dbh->do("ALTER TABLE aqbooksellers DROP COLUMN contact,
8715         DROP COLUMN contpos, DROP COLUMN contphone,
8716         DROP COLUMN contaltphone, DROP COLUMN contfax,
8717         DROP COLUMN contemail, DROP COLUMN contnotes;");
8718     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contact>>', '<<aqcontacts.name>>')");
8719     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contpos>>', '<<aqcontacts.position>>')");
8720     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contphone>>', '<<aqcontacts.phone>>')");
8721     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contaltphone>>', '<<aqcontacts.altphone>>')");
8722     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contfax>>', '<<aqcontacts.contfax>>')");
8723     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contemail>>', '<<aqcontacts.contemail>>')");
8724     $dbh->do("UPDATE letter SET content = replace(content, '<<aqbooksellers.contnotes>>', '<<aqcontacts.contnotes>>')");
8725     print "Upgrade to $DBversion done (Bug 10402: Move bookseller contacts to separate table)\n";
8726     SetVersion($DBversion);
8727 }
8728
8729 $DBversion = "3.17.00.017";
8730 if ( CheckVersion($DBversion) ) {
8731     # Correct invalid recordtypes (should be very exceptional)
8732     $dbh->do(q{
8733         UPDATE z3950servers set recordtype='biblio' WHERE recordtype NOT IN ('authority','biblio')
8734     });
8735     # Correct invalid server types (should also be very exceptional)
8736     $dbh->do(q{
8737         UPDATE z3950servers set type='zed' WHERE type <> 'zed'
8738     });
8739     # Adjust table
8740     $dbh->do(q{
8741         ALTER TABLE z3950servers
8742         DROP COLUMN icon,
8743         DROP COLUMN description,
8744         DROP COLUMN position,
8745         MODIFY COLUMN id int NOT NULL AUTO_INCREMENT FIRST,
8746         MODIFY COLUMN recordtype enum('authority','biblio') NOT NULL DEFAULT 'biblio',
8747         CHANGE COLUMN name servername mediumtext NOT NULL,
8748         CHANGE COLUMN type servertype enum('zed','sru') NOT NULL DEFAULT 'zed',
8749         ADD COLUMN sru_options varchar(255) default NULL,
8750         ADD COLUMN sru_fields mediumtext default NULL,
8751         ADD COLUMN add_xslt mediumtext default NULL
8752     });
8753     print "Upgrade to $DBversion done (Bug 6536: Z3950 improvements)\n";
8754     SetVersion ($DBversion);
8755 }
8756
8757 $DBversion = "3.17.00.018";
8758 if ( CheckVersion($DBversion) ) {
8759     $dbh->do("INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('HoldsInNoissuesCharge', '0', 'Hold charges block checkouts (added to noissuescharge).',NULL,'YesNo');");
8760     print "Upgrade to $DBversion done (Bug 12205: Add HoldsInNoissuesCharge systempreference)\n";
8761     SetVersion($DBversion);
8762 }
8763
8764 $DBversion = "3.17.00.019";
8765 if ( CheckVersion($DBversion) ) {
8766     $dbh->do("INSERT INTO `systempreferences` (variable,value,explanation,options,type) VALUES('NotHighlightedWords','and|or|not',NULL,'List of words to NOT highlight when OpacHighlightedWords is enabled','free')"
8767     );
8768     print "Upgrade to $DBversion done (Bug 6149: Operator highlighted in search results)\n";
8769     SetVersion($DBversion);
8770 }
8771
8772 $DBversion = "3.17.00.020";
8773 if(C4::Context->preference("Version") < TransformToNum($DBversion) ) {
8774     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ExpireReservesOnHolidays', '1', NULL, 'If false, reserves at a library will not be canceled on days the library is not open.', 'YesNo')");
8775     print "Upgrade to $DBversion done (Bug 8735 - Expire holds waiting only on days the library is open)\n";
8776     SetVersion ($DBversion);
8777 }
8778
8779 $DBversion = "3.17.00.021";
8780 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
8781     my $pref = C4::Context->preference('HomeOrHoldingBranch');
8782     $dbh->do("INSERT INTO `systempreferences` (variable,value,options,explanation,type)
8783        VALUES ('StaffSearchResultsDisplayBranch', ?,'homebranch|holdingbranch','Controls the display of the home or holding branch for staff search results','choice')", undef, $pref);
8784     print "Upgrade to $DBversion done (Bug 12582 - Control of branch displayed in search results linked to HomeOrHoldingBranch)\n";
8785     SetVersion ($DBversion);
8786 }
8787
8788 $DBversion = '3.17.00.022';
8789 if ( CheckVersion($DBversion) ) {
8790     my @temp= $dbh->selectrow_array(qq|
8791         SELECT count(*)
8792         FROM marc_subfield_structure
8793         WHERE kohafield='permanent_location' OR kohafield='items.permanent_location'
8794     |);
8795     print "Upgrade to $DBversion done (Bug 7817: Check for permanent_location)\n";
8796     if( $temp[0] ) {
8797         print "WARNING for Koha administrator: Your database contains one or more mappings for permanent_location to the MARC structure. This item field however is for internal use and should not be linked to a MARC (sub)field. Please correct it. See also Bugzilla reports 7817 and 12818.\n";
8798     }
8799     SetVersion($DBversion);
8800 }
8801
8802 $DBversion = "3.17.00.023";
8803 if ( CheckVersion($DBversion) ) {
8804     $dbh->do(q{
8805         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AcqItemSetSubfieldsWhenReceiptIsCancelled','', '','Upon cancelling a receipt, update the items subfields if they were created when placing an order (e.g. o=5|a="bar foo")', 'Free')
8806     });
8807     print "Upgrade to $DBversion done (Bug 11169 - Add AcqItemSetSubfieldsWhenReceiptIsCancelled syspref)\n";
8808     SetVersion($DBversion);
8809 }
8810
8811 $DBversion = "3.17.00.024";
8812 if(CheckVersion($DBversion)) {
8813     $dbh->do(q{
8814         ALTER TABLE issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8815     });
8816     $dbh->do(q{
8817         ALTER TABLE old_issues ADD auto_renew BOOLEAN default FALSE AFTER renewals
8818     });
8819     $dbh->do(q{
8820         ALTER TABLE issuingrules ADD auto_renew BOOLEAN default FALSE AFTER norenewalbefore
8821     });
8822     print "Upgrade to $DBversion done (Bug 11577: [ENH] Automatic renewal feature)\n";
8823     SetVersion($DBversion);
8824 }
8825
8826 $DBversion = '3.17.00.025';
8827 if ( CheckVersion($DBversion) ) {
8828     $dbh->do(qq{
8829         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('StatisticsFields','location|itype|ccode','Define fields (from the items table) used for statistics members',NULL,'Free')
8830     });
8831     print "Upgrade to $DBversion done (Bug 12728: Checked syspref StatisticsFields)\n";
8832 }
8833
8834 $DBversion = "3.17.00.026";
8835 if ( CheckVersion($DBversion) ) {
8836     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
8837         $dbh->do("UPDATE marc_subfield_structure SET liblibrarian = 'Encoded bitrate', libopac = 'Encoded bitrate' WHERE tagfield = '347' AND tagsubfield = 'f'");
8838         $dbh->do("UPDATE marc_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','610','611','710','711','810','811') AND tagsubfield = 'c'");
8839         $dbh->do("UPDATE auth_subfield_structure SET repeatable = 1 WHERE tagfield IN ('110','111','410','411','510','511','710','711') AND tagsubfield = 'c'");
8840         print "Upgrade to $DBversion done (Bug 12435 - Update MARC21 frameworks to Update No. 18 (April 2014))\n";
8841     }
8842     SetVersion($DBversion);
8843 }
8844
8845 $DBversion = "3.17.00.027";
8846 if ( CheckVersion($DBversion) ) {
8847     $dbh->do(q{
8848         DELETE FROM systempreferences WHERE variable = 'SearchEngine'
8849     });
8850     print "Upgrade to $DBversion done (Bug 12538 - Remove SearchEngine syspref)\n";
8851     SetVersion($DBversion);
8852 }
8853
8854 $DBversion = "3.17.00.028";
8855 if ( CheckVersion($DBversion) ) {
8856     $dbh->do(q{
8857         INSERT INTO systempreferences (variable,value) VALUES('OpacCustomSearch','');
8858     });
8859     print "Upgrade to $DBversion done (Bug 12296 - search box replaceable with a system preference)\n";
8860     SetVersion($DBversion);
8861 }
8862
8863 $DBversion = "3.17.00.029";
8864 if ( CheckVersion($DBversion) ) {
8865     $dbh->do("ALTER TABLE  `items` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8866     $dbh->do("ALTER TABLE  `deleteditems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8867     $dbh->do("ALTER TABLE  `biblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8868     $dbh->do("ALTER TABLE  `deletedbiblioitems` CHANGE  `cn_sort`  `cn_sort` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
8869     print "Upgrade to $DBversion done (Bug 12424 - ddc sorting of call numbers truncates long Cutter parts)\n";
8870     SetVersion ($DBversion);
8871 }
8872
8873 $DBversion = "3.17.00.030";
8874 if ( CheckVersion($DBversion) ) {
8875     $dbh->do(
8876         q{
8877        INSERT INTO systempreferences (variable, value, options, explanation, type )
8878        VALUES
8879         ('UsageStatsCountry', '', NULL, 'The country where your library is located, to be shown on the Hea Koha community website', 'Choice'),
8880         ('UsageStatsID', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.',  'Free'),
8881         ('UsageStatsLastUpdateTime', '', NULL, 'This preference is part of Koha but it should not be deleted or updated manually.', 'Free'),
8882         ('UsageStatsLibraryName', '', NULL, 'The library name to be shown on Hea Koha community website', 'Free'),
8883         ('UsageStatsLibraryType', 'public', 'public|university', 'The library type to be shown on the Hea Koha community website', 'Choice'),
8884         ('UsageStatsLibraryUrl', '', NULL, 'The library URL to be shown on Hea Koha community website', 'Free'),
8885         ('UsageStats', 0, NULL, 'Share anonymous usage data on the Hea Koha community website.', 'YesNo')
8886     });
8887     print "Upgrade to $DBversion done (Bug 11926: Add UsageStats systempreferences (HEA))\n";
8888     SetVersion ($DBversion);
8889 }
8890
8891 $DBversion = "3.17.00.031";
8892 if ( CheckVersion($DBversion) ) {
8893    $dbh->do("ALTER TABLE saved_sql CHANGE report_name report_name VARCHAR( 255 ) NOT NULL DEFAULT '' ");
8894    print "Upgrade to $DBversion done (Bug 2969: Report Name should be mandatory for saved reports)\n";
8895    SetVersion ($DBversion);
8896 }
8897
8898 $DBversion = "3.17.00.032";
8899 if ( CheckVersion($DBversion) ) {
8900     $dbh->do(
8901 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free')"
8902     );
8903     $dbh->do(
8904 "INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free')"
8905     );
8906     $dbh->do("ALTER TABLE branches ADD branchreplyto mediumtext AFTER branchemail");
8907     $dbh->do("ALTER TABLE branches ADD branchreturnpath mediumtext AFTER branchreplyto");
8908     print "Upgrade to $DBversion done (Bug 9530: Adding replyto and returnpath addresses.)\n";
8909     SetVersion($DBversion);
8910 }
8911
8912 $DBversion = "3.17.00.033";
8913 if ( CheckVersion($DBversion) ) {
8914     $dbh->do(q{
8915         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
8916         VALUES('FacetMaxCount', '20','Specify the max facet count for each category',NULL,'Integer')
8917     });
8918     print "Upgrade to $DBversion done (Bug 13088 - Allow the user to specify a max amount of facets to show)\n";
8919     SetVersion($DBversion);
8920 }
8921
8922 $DBversion = "3.17.00.034";
8923 if ( CheckVersion($DBversion) ) {
8924     $dbh->do(q|
8925         ALTER TABLE aqorders DROP COLUMN cancelledby;
8926     |);
8927
8928     print "Upgrade to $DBversion done (Bug 11007 - DROP column aqorders.cancelledby)\n";
8929     SetVersion($DBversion);
8930 }
8931
8932 $DBversion = "3.17.00.035";
8933 if ( CheckVersion($DBversion) ) {
8934     $dbh->do(q|
8935         ALTER TABLE serial ADD COLUMN claims_count INT(11) DEFAULT 0 after claimdate
8936     |);
8937     $dbh->do(q|
8938         UPDATE serial
8939         SET claims_count = 1
8940         WHERE claimdate IS NOT NULL
8941     |);
8942     print "Upgrade to $DBversion done (Bug 5342: Add claims_count field in serial table)\n";
8943     SetVersion($DBversion);
8944 }
8945
8946 $DBversion = "3.17.00.036";
8947 if ( CheckVersion($DBversion) ) {
8948     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacShowLibrariesPulldownMobile'");
8949     print "Upgrade to $DBversion done ( Bug 12513 - PROG/CCSR deprecation: Remove OpacShowLibrariesPulldownMobile system preference )\n";
8950     SetVersion ($DBversion);
8951 }
8952
8953 $DBversion = "3.17.00.037";
8954 if ( CheckVersion($DBversion) ) {
8955     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlockMobile'");
8956     print "Upgrade to $DBversion done ( Bug 12246 - PROG/CCSR deprecation: Remove OpacMainUserBlockMobile system preference )\n";
8957     SetVersion ($DBversion);
8958 }
8959
8960 $DBversion = "3.17.00.038";
8961 if ( CheckVersion($DBversion) ) {
8962     $dbh->do("DELETE FROM systempreferences WHERE variable='OPACMobileUserCSS'");
8963     print "Upgrade to $DBversion done ( Bug 12245 - PROG/CCSR deprecation: Remove OPACMobileUserCSS system preference )\n";
8964     SetVersion ($DBversion);
8965 }
8966
8967 $DBversion = "3.17.00.039";
8968 if ( CheckVersion($DBversion) ) {
8969     $dbh->do("INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
8970     ('OPACFallback', 'prog', 'bootstrap|prog', 'Define the fallback theme for the OPAC interface.', 'Themes')");
8971     print "Upgrade to $DBversion done (Bug 12539 - PROG/CCSR deprecation: Remove hardcoded theme from C4/Templates.pm)\n";
8972     SetVersion ($DBversion);
8973 }
8974
8975 $DBversion = "3.17.00.040";
8976 if ( CheckVersion($DBversion) ) {
8977     my $opac_theme = C4::Context->preference( 'opacthemes' );
8978     if ( !defined $opac_theme || $opac_theme eq 'prog' || $opac_theme eq 'ccsr' ) {
8979         $dbh->do("UPDATE systempreferences SET value='bootstrap' WHERE variable='opacthemes'");
8980     }
8981     print "Upgrade to $DBversion done (Bug 12223: 'prog' and 'ccsr' themes removed)\n";
8982     SetVersion($DBversion);
8983 }
8984
8985 $DBversion = "3.17.00.041";
8986 if ( CheckVersion($DBversion) ) {
8987     print "Upgrade to $DBversion done (Bug 11346: Deprecate the 'prog' and 'CCSR' themes)\n";
8988     SetVersion($DBversion);
8989 }
8990
8991 $DBversion = "3.17.00.042";
8992 if ( CheckVersion($DBversion) ) {
8993     $dbh->do("DELETE FROM systempreferences WHERE variable='yuipath'");
8994     print "Upgrade to $DBversion done (Bug 12494: Remove yuipath system preference)\n";
8995     SetVersion ($DBversion);
8996 }
8997
8998 $DBversion = "3.17.00.043";
8999 if ( CheckVersion($DBversion) ) {
9000     $dbh->do("
9001         ALTER TABLE aqorders
9002         ADD COLUMN cancellationreason TEXT DEFAULT NULL AFTER datecancellationprinted
9003     ");
9004     print "Upgrade to $DBversion done (Bug 7162: Add aqorders.cancellationreason)\n";
9005     SetVersion ($DBversion);
9006 }
9007
9008 $DBversion = "3.17.00.044";
9009 if ( CheckVersion($DBversion) ) {
9010     $dbh->do(q{
9011         INSERT IGNORE INTO systempreferences
9012             (variable,value,explanation,options,type)
9013             VALUES('OnSiteCheckouts','0','Enable/Disable the on-site checkouts feature','','YesNo');
9014     });
9015     $dbh->do(q{
9016         INSERT IGNORE INTO systempreferences
9017             (variable,value,explanation,options,type)
9018             VALUES('OnSiteCheckoutsForce','0','Enable/Disable the on-site for all cases (Even if a user is debarred, etc.)','','YesNo');
9019     });
9020     $dbh->do(q{
9021         ALTER TABLE issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9022     });
9023     $dbh->do(q{
9024         ALTER TABLE old_issues ADD COLUMN onsite_checkout INT(1) NOT NULL DEFAULT 0 AFTER issuedate;
9025     });
9026     print "Upgrade to $DBversion done (Bug 10860: Add new system preference OnSiteCheckouts + fields [old_]issues.onsite_checkout)\n";
9027     SetVersion($DBversion);
9028 }
9029
9030 $DBversion = "3.17.00.045";
9031 if ( CheckVersion($DBversion) ) {
9032     $dbh->do(q{
9033         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9034         ('LocalHoldsPriority',  '0', NULL,  'Enables the LocalHoldsPriority feature',  'YesNo'),
9035         ('LocalHoldsPriorityItemControl',  'holdingbranch',  'holdingbranch|homebranch',  'decides if the feature operates using the item''s home or holding library.',  'Choice'),
9036         ('LocalHoldsPriorityPatronControl',  'PickupLibrary',  'HomeLibrary|PickupLibrary',  'decides if the feature operates using the library set as the patron''s home library, or the library set as the pickup library for the given hold.',  'Choice')
9037     });
9038     print "Upgrade to $DBversion done (Bug 11126 - Make the holds system optionally give precedence to local holds)\n";
9039     SetVersion($DBversion);
9040 }
9041
9042 $DBversion = "3.17.00.046";
9043 if ( CheckVersion($DBversion) ) {
9044     $dbh->do(q{
9045         CREATE TABLE IF NOT EXISTS items_search_fields (
9046           name VARCHAR(255) NOT NULL,
9047           label VARCHAR(255) NOT NULL,
9048           tagfield CHAR(3) NOT NULL,
9049           tagsubfield CHAR(1) NULL DEFAULT NULL,
9050           authorised_values_category VARCHAR(16) NULL DEFAULT NULL,
9051           PRIMARY KEY(name),
9052           CONSTRAINT items_search_fields_authorised_values_category
9053             FOREIGN KEY (authorised_values_category) REFERENCES authorised_values (category)
9054             ON DELETE SET NULL ON UPDATE CASCADE
9055         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9056     });
9057     print "Upgrade to $DBversion done (Bug 11425: Add items_search_fields table)\n";
9058     SetVersion($DBversion);
9059 }
9060
9061 $DBversion = "3.17.00.047";
9062 if ( CheckVersion($DBversion) ) {
9063     $dbh->do(q{
9064         ALTER TABLE collections
9065             CHANGE colBranchcode colBranchcode VARCHAR( 10 ) NULL DEFAULT NULL,
9066             ADD INDEX ( colBranchcode ),
9067             ADD CONSTRAINT collections_ibfk_1 FOREIGN KEY (colBranchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
9068     });
9069     print "Upgrade to $DBversion done (Bug 8836 - Resurrect Rotating Collections)\n";
9070     SetVersion($DBversion);
9071 }
9072
9073 $DBversion = "3.17.00.048";
9074 if ( CheckVersion($DBversion) ) {
9075     $dbh->do(q|
9076         INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('RentalFeesCheckoutConfirmation', '0', NULL , 'Allow user to confirm when checking out an item with rental fees.', 'YesNo')
9077     |);
9078     print "Upgrade to $DBversion done (Bug 12448 - Add RentalFeesCheckoutConfirmation syspref)\n";
9079     SetVersion($DBversion);
9080 }
9081
9082 $DBversion = "3.17.00.049";
9083 if ( CheckVersion($DBversion) ) {
9084     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'am', 'language', 'Amharic','2014-10-29')");
9085     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'am','amh')");
9086     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'am', 'አማርኛ')");
9087     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'am', 'language', 'en', 'Amharic')");
9088
9089     $dbh->do("UPDATE language_descriptions SET description = 'لعربية' WHERE subtag = 'ar' AND type = 'language' AND lang = 'ar'");
9090
9091     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'az', 'language', 'Azerbaijani','2014-10-30')");
9092     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'az','aze')");
9093     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'az', 'Azərbaycan dili')");
9094     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'az', 'language', 'en', 'Azerbaijani')");
9095
9096     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'be', 'language', 'Byelorussian','2014-10-30')");
9097     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'be','bel')");
9098     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'be', 'Беларуская мова')");
9099     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'be', 'language', 'en', 'Byelorussian')");
9100
9101     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'bn', 'language', 'Bengali','2014-10-30')");
9102     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'bn','ben')");
9103     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'bn', 'বাংলা')");
9104     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'bn', 'language', 'en', 'Bengali')");
9105
9106     $dbh->do("UPDATE language_descriptions SET description = 'Български' WHERE subtag = 'bg' AND type = 'language' AND lang = 'bg'");
9107     $dbh->do("UPDATE language_descriptions SET description = 'Ceština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'");
9108     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικά' WHERE subtag = 'el' AND type = 'language' AND lang = 'el'");
9109     $dbh->do("UPDATE language_descriptions SET description = 'Español' WHERE subtag = 'es' AND type = 'language' AND lang = 'es'");
9110
9111     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'eu', 'language', 'Basque','2014-10-30')");
9112     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'eu','eus')");
9113     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'eu', 'Euskera')");
9114     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'eu', 'language', 'en', 'Basque')");
9115
9116     $dbh->do("UPDATE language_descriptions SET description = 'فارسى' WHERE subtag = 'fa' AND type = 'language' AND lang = 'fa'");
9117     $dbh->do("UPDATE language_descriptions SET description = 'Suomi' WHERE subtag = 'fi' AND type = 'language' AND lang = 'fi'");
9118
9119     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'fo', 'language', 'Faroese','2014-10-30')");
9120     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'fo','fao')");
9121     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'fo', 'Føroyskt')");
9122     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'fo', 'language', 'en', 'Faroese')");
9123
9124     $dbh->do("UPDATE language_descriptions SET description = 'Français' WHERE subtag = 'fr' AND type = 'language' AND lang = 'fr'");
9125     $dbh->do("UPDATE language_descriptions SET description = 'עִבְרִית' WHERE subtag = 'he' AND type = 'language' AND lang = 'he'");
9126     $dbh->do("UPDATE language_descriptions SET description = 'हिन्दी' WHERE subtag = 'hi' AND type = 'language' AND lang = 'hi'");
9127
9128     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'is', 'language', 'Icelandic','2014-10-30')");
9129     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'is','ice')");
9130     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'is', 'Íslenska')");
9131     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'is', 'language', 'en', 'Icelandic')");
9132
9133     $dbh->do("UPDATE language_descriptions SET description = '日本語' WHERE subtag = 'ja' AND type = 'language' AND lang = 'ja'");
9134
9135     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Kannada','2014-10-30')");
9136     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka','kan')");
9137     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ಕನ್ನಡ')");
9138     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Kannada')");
9139
9140     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'km', 'language', 'Khmer','2014-10-30')");
9141     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES( 'km','khm')");
9142     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'km', 'language', 'km', 'ភាសាខ្មែរ')");
9143     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'km', 'language', 'en', 'Khmer')");
9144
9145     $dbh->do("UPDATE language_descriptions SET description = '한국어' WHERE subtag = 'ko' AND type = 'language' AND lang = 'ko'");
9146
9147     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ku', 'language', 'Kurdish','2014-05-13')");
9148     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ku','kur')");
9149     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'ku', 'کوردی')");
9150     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'en', 'Kurdish')");
9151     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'fr', 'Kurde')");
9152     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'de', 'Kurdisch')");
9153     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ku', 'language', 'es', 'Kurdo')");
9154
9155     $dbh->do("UPDATE language_descriptions SET description = 'ພາສາລາວ' WHERE subtag = 'lo' AND type = 'language' AND lang = 'lo'");
9156
9157     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mi', 'language', 'Maori','2014-10-30')");
9158     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mi','mri')");
9159     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'mi', 'Te Reo Māori')");
9160     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mi', 'language', 'en', 'Maori')");
9161
9162     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mn', 'language', 'Mongolian','2014-10-30')");
9163     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mn','mon')");
9164     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'mn', 'Mонгол')");
9165     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mn', 'language', 'en', 'Mongolian')");
9166
9167     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'mr', 'language', 'Marathi','2014-10-30')");
9168     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'mr','mar')");
9169     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'mr', 'मराठी')");
9170     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'mr', 'language', 'en', 'Marathi')");
9171
9172     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ms', 'language', 'Malay','2014-10-30')");
9173     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ms','may')");
9174     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'ms', 'Bahasa melayu')");
9175     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ms', 'language', 'en', 'Malay')");
9176
9177     $dbh->do("UPDATE language_descriptions SET description = 'Norsk bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'nb'");
9178     $dbh->do("UPDATE language_descriptions SET description = 'Norwegian bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'en'");
9179     $dbh->do("UPDATE language_descriptions SET description = 'Norvégien bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'fr'");
9180     $dbh->do("UPDATE language_descriptions SET description = 'Norwegisch bokmål' WHERE subtag = 'nb' AND type = 'language' AND lang = 'de'");
9181
9182     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ne', 'language', 'Nepali','2014-10-30')");
9183     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ne','nep')");
9184     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)VALUES ( 'ne', 'language', 'ne', 'नेपाली')");
9185     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ne', 'language', 'en', 'Nepali')");
9186
9187     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'pbr', 'language', 'Pangwa','2014-10-30')");
9188     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'pbr','pbr')");
9189     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'pbr', 'Ekipangwa')");
9190     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'pbr', 'language', 'en', 'Pangwa')");
9191
9192     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'prs', 'language', 'Dari','2014-10-30')");
9193     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'prs','prs')");
9194     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'prs', 'درى')");
9195     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'prs', 'language', 'en', 'Dari')");
9196
9197     $dbh->do("UPDATE language_descriptions SET description = 'Português' WHERE subtag = 'pt' AND type = 'language' AND lang = 'pt'");
9198     $dbh->do("UPDATE language_descriptions SET description = 'Român' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro'");
9199     $dbh->do("UPDATE language_descriptions SET description = 'Русский' WHERE subtag = 'ru' AND type = 'language' AND lang = 'ru'");
9200
9201     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'rw', 'language', 'Kinyarwanda','2014-10-30')");
9202     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'rw','kin')");
9203     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'rw', 'Ikinyarwanda')");
9204     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'rw', 'language', 'en', 'Kinyarwanda')");
9205
9206     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sd', 'language', 'Sindhi','2014-10-30')");
9207     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sd','snd')");
9208     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'sd', 'سنڌي')");
9209     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sd', 'language', 'en', 'Sindhi')");
9210
9211     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sk', 'language', 'Slovak','2014-10-30')");
9212     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sk','slk')");
9213     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'sk', 'Slovenčina')");
9214     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sk', 'language', 'en', 'Slovak')");
9215
9216     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sl', 'language', 'Slovene','2014-10-30')");
9217     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sl','slv')");
9218     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'sl', 'Slovenščina')");
9219     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sl', 'language', 'en', 'Slovene')");
9220
9221     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sq', 'language', 'Albanian','2014-10-30')");
9222     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sq','sqi')");
9223     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'sq', 'Shqip')");
9224     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sq', 'language', 'en', 'Albanian')");
9225
9226     $dbh->do("UPDATE language_descriptions SET description = 'Cрпски' WHERE subtag = 'sr' AND type = 'language' AND lang = 'sr'");
9227
9228     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'sw', 'language', 'Swahili','2014-10-30')");
9229     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'sw','swa')");
9230     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'sw', 'Kiswahili')");
9231     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'sw', 'language', 'en', 'Swahili')");
9232
9233     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ta', 'language', 'Tamil','2014-10-30')");
9234     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ta','tam')");
9235     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'ta', 'தமிழ்')");
9236     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ta', 'language', 'en', 'Tamil')");
9237
9238     $dbh->do("UPDATE language_descriptions SET description = 'Tetun' WHERE subtag = 'tet' AND type = 'language' AND lang = 'tet'");
9239     $dbh->do("UPDATE language_descriptions SET description = 'ภาษาไทย' WHERE subtag = 'th' AND type = 'language' AND lang = 'th'");
9240
9241     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'tl', 'language', 'Tagalog','2014-10-30')");
9242     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'tl','tgl')");
9243     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'tl', 'Tagalog')");
9244     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'tl', 'language', 'en', 'Tagalog')");
9245
9246     $dbh->do("UPDATE language_descriptions SET description = 'Türkçe' WHERE subtag = 'tr' AND type = 'language' AND lang = 'tr'");
9247     $dbh->do("UPDATE language_descriptions SET description = 'Українська' WHERE subtag = 'uk' AND type = 'language' AND lang = 'uk'");
9248     $dbh->do("UPDATE language_descriptions SET description = 'اردو' WHERE subtag = 'ur' AND type = 'language' AND lang = 'ur'");
9249
9250     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'vi', 'language', 'Vietnamese','2014-10-30')");
9251     $dbh->do("INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'vi','vie')");
9252     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'vi', '㗂越')");
9253     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'vi', 'language', 'en', 'Vietnamese')");
9254
9255     $dbh->do("UPDATE language_descriptions SET description = '中文' WHERE subtag = 'zh' AND type = 'language' AND lang = 'zh'");
9256     $dbh->do("UPDATE language_descriptions SET description = '' WHERE subtag = 'Arab,script' AND type = 'Arab' AND lang = 'العربية'");
9257
9258     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Armn', 'script', 'Armenian','2014-10-30')");
9259     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Armn', 'script', 'Armn', 'Հայոց այբուբեն')");
9260     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Armn', 'script', 'en', 'Armenian')");
9261
9262     $dbh->do("UPDATE language_descriptions SET description = 'Кирилица' WHERE subtag = 'Cyrl' AND type = 'script' AND lang = 'Cyrl'");
9263
9264     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Ethi', 'script', 'Ethiopic','2014-10-30')");
9265     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Ethi', 'script', 'Ethi', 'ግዕዝ')");
9266     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Ethi', 'script', 'en', 'Ethiopic')");
9267
9268     $dbh->do("UPDATE language_descriptions SET description = 'Ελληνικό αλφάβητο' WHERE subtag = 'Grek' AND type = 'script' AND lang = 'Grek'");
9269     $dbh->do("UPDATE language_descriptions SET description = '简体字' WHERE subtag = 'Hans' AND type = 'script' AND lang = 'Hans'");
9270     $dbh->do("UPDATE language_descriptions SET description = '繁體字' WHERE subtag = 'Hant' AND type = 'script' AND lang = 'Hant'");
9271     $dbh->do("UPDATE language_descriptions SET description = 'אָלֶף־בֵּית עִבְרִי' WHERE subtag = 'Hebr' AND type = 'script' AND lang = 'Hebr'");
9272
9273     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Jpan', 'script', 'Japanese','2014-10-30')");
9274     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Jpan', 'script', 'Jpan', '漢字')");
9275     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Jpan', 'script', 'en', 'Japanese')");
9276
9277     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Knda', 'script', 'Kannada','2014-10-30')");
9278     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Knda', 'script', 'Knda', 'ಕನ್ನಡ ಲಿಪಿ')");
9279     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Knda', 'script', 'en', 'Kannada')");
9280
9281     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'Kore', 'script', 'Korean','2014-10-30')");
9282     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'Kore', 'script', 'Kore', '한글')");
9283     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES( 'Kore', 'script', 'en', 'Korean')");
9284
9285     $dbh->do("UPDATE language_descriptions SET description = 'ອັກສອນລາວ' WHERE subtag = 'Laoo' AND type = 'script' AND lang = 'Laoo'");
9286
9287     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AL', 'region', 'Albania','2014-10-30')");
9288     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'en', 'Albania')");
9289     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AL', 'region', 'sq', 'Shqipërisë')");
9290
9291     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'AZ', 'region', 'Azerbaijan','2014-10-30')");
9292     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'en', 'Azerbaijan')");
9293     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'AZ', 'region', 'az', 'Azərbaycan')");
9294
9295     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BE', 'region', 'Belgium','2014-10-30')");
9296     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'en', 'Belgium')");
9297     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BE', 'region', 'nl', 'België')");
9298
9299     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BR', 'region', 'Brazil','2014-10-30')");
9300     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'en', 'Brazil')");
9301     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BR', 'region', 'pt', 'Brasil')");
9302
9303     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'BY', 'region', 'Belarus','2014-10-30')");
9304     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'en', 'Belarus')");
9305     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'BY', 'region', 'be', 'Беларусь')");
9306
9307     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CA', 'region', 'fr', 'Canada')");
9308
9309     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CH', 'region', 'Switzerland','2014-10-30')");
9310     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'en', 'Switzerland')");
9311     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CH', 'region', 'de', 'Schweiz')");
9312
9313     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CN', 'region', 'China','2014-10-30')");
9314     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'en', 'China')");
9315     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CN', 'region', 'zh', '中国')");
9316
9317     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'CZ', 'region', 'Czech Republic','2014-10-30')");
9318     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'en', 'Czech Republic')");
9319     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'CZ', 'region', 'cs', 'Česká republika')");
9320
9321     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'DE', 'region', 'Germany','2014-10-30')");
9322     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'en', 'Germany')");
9323     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DE', 'region', 'de', 'Deutschland')");
9324
9325     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'DK', 'region', 'en', 'Denmark')");
9326
9327     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ES', 'region', 'Spain','2014-10-30')");
9328     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'en', 'Spain')");
9329     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ES', 'region', 'es', 'España')");
9330
9331     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FI', 'region', 'Finland','2014-10-30')");
9332     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'en', 'Finland')");
9333     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FI', 'region', 'fi', 'Suomi')");
9334
9335     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'FO', 'region', 'Faroe Islands','2014-10-30')");
9336     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'en', 'Faroe Islands')");
9337     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'FO', 'region', 'fo', 'Føroyar')");
9338
9339     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'GR', 'region', 'Greece','2014-10-30')");
9340     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'en', 'Greece')");
9341     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'GR', 'region', 'el', 'Ελλάδα')");
9342
9343     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HR', 'region', 'Croatia','2014-10-30')");
9344     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'en', 'Croatia')");
9345     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HR', 'region', 'hr', 'Hrvatska')");
9346
9347     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'HU', 'region', 'Hungary','2014-10-30')");
9348     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'en', 'Hungary')");
9349     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'HU', 'region', 'hu', 'Magyarország')");
9350
9351     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ID', 'region', 'Indonesia','2014-10-30')");
9352     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'en', 'Indonesia')");
9353     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ID', 'region', 'id', 'Indonesia')");
9354
9355     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IS', 'region', 'Iceland','2014-10-30')");
9356     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'en', 'Iceland')");
9357     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IS', 'region', 'is', 'Ísland')");
9358
9359     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'IT', 'region', 'Italy','2014-10-30')");
9360     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'en', 'Italy')");
9361     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'IT', 'region', 'it', 'Italia')");
9362
9363     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'JP', 'region', 'Japan','2014-10-30')");
9364     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'en', 'Japan')");
9365     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'JP', 'region', 'ja', '日本')");
9366
9367     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KE', 'region', 'Kenya','2014-10-30')");
9368     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'en', 'Kenya')");
9369     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KE', 'region', 'rw', 'Kenya')");
9370
9371     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KH', 'region', 'Cambodia','2014-10-30')");
9372     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'en', 'Cambodia')");
9373     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KH', 'region', 'km', 'កម្ពុជា')");
9374
9375     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'KP', 'region', 'North Korea','2014-10-30')");
9376     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'en', 'North Korea')");
9377     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'KP', 'region', 'ko', '조선민주주의인민공화국')");
9378
9379     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'LK', 'region', 'Sri Lanka','2014-10-30')");
9380     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'en', 'Sri Lanka')");
9381     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'LK', 'region', 'ta', 'இலங்கை')");
9382
9383     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'MY', 'region', 'Malaysia','2014-10-30')");
9384     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'en', 'Malaysia')");
9385     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'MY', 'region', 'ms', 'Malaysia')");
9386
9387     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NE', 'region', 'Niger','2014-10-30')");
9388     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'en', 'Niger')");
9389     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NE', 'region', 'ne', 'Niger')");
9390
9391     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NL', 'region', 'Netherlands','2014-10-30')");
9392     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'en', 'Netherlands')");
9393     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NL', 'region', 'nl', 'Nederland')");
9394
9395     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'NO', 'region', 'Norway','2014-10-30')");
9396     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'en', 'Norway')");
9397     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'ne', 'Noreg')");
9398     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'NO', 'region', 'nn', 'Noreg')");
9399
9400     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PH', 'region', 'Philippines','2014-10-30')");
9401     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'en', 'Philippines')");
9402     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PH', 'region', 'tl', 'Pilipinas')");
9403
9404     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PK', 'region', 'Pakistan','2014-10-30')");
9405     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'en', 'Pakistan')");
9406     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PK', 'region', 'sd', 'پاكستان')");
9407
9408     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PL', 'region', 'Poland','2014-10-30')");
9409     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'en', 'Poland')");
9410     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PL', 'region', 'pl', 'Polska')");
9411
9412     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'PT', 'region', 'Portugal','2014-10-30')");
9413     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'en', 'Portugal')");
9414     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'PT', 'region', 'pt', 'Portugal')");
9415
9416     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RO', 'region', 'Romania','2014-10-30')");
9417     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'en', 'Romania')");
9418     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RO', 'region', 'ro', 'România')");
9419
9420     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RU', 'region', 'Russia','2014-10-30')");
9421     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'en', 'Russia')");
9422     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RU', 'region', 'ru', 'Россия')");
9423
9424     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'RW', 'region', 'Rwanda','2014-10-30')");
9425     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'en', 'Rwanda')");
9426     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'RW', 'region', 'rw', 'Rwanda')");
9427
9428     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SE', 'region', 'Sweden','2014-10-30')");
9429     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'en', 'Sweden')");
9430     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SE', 'region', 'sv', 'Sverige')");
9431
9432     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SI', 'region', 'Slovenia','2014-10-30')");
9433     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'en', 'Slovenia')");
9434     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SI', 'region', 'sl', 'Slovenija')");
9435
9436     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'SK', 'region', 'Slovakia','2014-10-30')");
9437     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'en', 'Slovakia')");
9438     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'SK', 'region', 'sk', 'Slovensko')");
9439
9440     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TH', 'region', 'Thailand','2014-10-30')");
9441     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'en', 'Thailand')");
9442     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TH', 'region', 'th', 'ประเทศไทย')");
9443
9444     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TR', 'region', 'Turkey','2014-10-30')");
9445     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'en', 'Turkey')");
9446     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TR', 'region', 'tr', 'Türkiye')");
9447
9448     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'TW', 'region', 'Taiwan','2014-10-30')");
9449     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'en', 'Taiwan')");
9450     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'TW', 'region', 'zh', '台灣')");
9451
9452     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'UA', 'region', 'Ukraine','2014-10-30')");
9453     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'en', 'Ukraine')");
9454     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'UA', 'region', 'uk', 'Україна')");
9455
9456     $dbh->do("INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'VN', 'region', 'Vietnam','2014-10-30')");
9457     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'en', 'Vietnam')");
9458     $dbh->do("INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'VN', 'region', 'vi', 'Việt Nam')");
9459
9460     print "Upgrade to $DBversion done (Bug 12250: Update descriptions for languages, scripts and regions)\n";
9461     SetVersion($DBversion);
9462 }
9463
9464 $DBversion = "3.17.00.050";
9465 if ( CheckVersion($DBversion) ) {
9466     $dbh->do(q|
9467         INSERT INTO permissions (module_bit, code, description) VALUES
9468           (13, 'records_batchdel', 'Perform batch deletion of records (bibliographic or authority)')
9469     |);
9470     print "Upgrade to $DBversion done (Bug 12403: Add permission tools_records_batchdelitem)\n";
9471     SetVersion($DBversion);
9472 }
9473
9474 $DBversion = "3.17.00.051";
9475 if ( CheckVersion($DBversion) ) {
9476     $dbh->do("INSERT INTO systempreferences (variable,value,options,explanation,type) VALUES('GoogleIndicTransliteration','0','','GoogleIndicTransliteration on the OPAC.','YesNo')");
9477     print "Upgrade to $DBversion done (Bug 13211: Added system preferences GoogleIndicTransliteration on the OPAC)\n";
9478     SetVersion($DBversion);
9479 }
9480
9481 $DBversion = "3.17.00.052";
9482 if ( CheckVersion($DBversion) ) {
9483     $dbh->do(q{
9484         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAdvSearchOptions','pubdate|itemtype|language|sorting|location','Show search options','pubdate|itemtype|language|subtype|sorting|location','multiple');
9485     });
9486
9487     $dbh->do(q{
9488         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES('OpacAdvSearchMoreOptions','pubdate|itemtype|language|subtype|sorting|location','Show search options for the expanded view (More options)','pubdate|itemtype|language|subtype|sorting|location','multiple');
9489    });
9490    print "Upgrade to $DBversion done (Bug 9043: Add system preference OpacAdvSearchOptions and OpacAdvSearchMoreOptions)\n";
9491    SetVersion ($DBversion);
9492 }
9493
9494 $DBversion = "3.17.00.053";
9495 if ( CheckVersion($DBversion) ) {
9496     $dbh->do(q{
9497         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'edit_items_restricted', 'Limit item modification to subfields defined in the SubfieldsToAllowForRestrictedEditing preference (please note that edit_item is still required)');
9498     });
9499
9500     $dbh->do(q{
9501         INSERT INTO permissions (module_bit, code, description) VALUES ('9', 'delete_all_items', 'Delete all items at once');
9502     });
9503
9504     $dbh->do(q{
9505         INSERT INTO permissions (module_bit, code, description) VALUES ('13', 'items_batchmod_restricted', 'Limit batch item modification to subfields defined in the SubfieldsToAllowForRestrictedBatchmod preference (please note that items_batchmod is still required)');
9506     });
9507
9508     # The delete_all_items permission should be added to users having the edit_items permission.
9509     $dbh->do(q{
9510         INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, module_bit, "delete_all_items" FROM user_permissions WHERE code="edit_items";
9511     });
9512
9513     # Add 2 new prefs
9514     $dbh->do(q{
9515         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToAllowForRestrictedEditing','','Define a list of subfields for which edition is authorized when edit_items_restricted permission is enabled, separated by spaces. Example: 995\$f 995\$h 995\$j','','Free');
9516     });
9517
9518     $dbh->do(q{
9519         INSERT INTO systempreferences (variable,value,explanation,options,type) VALUES ('SubfieldsToAllowForRestrictedBatchmod','','Define a list of subfields for which edition is authorized when items_batchmod_restricted permission is enabled, separated by spaces. Example: 995\$f 995\$h 995\$j','','Free');
9520     });
9521
9522     print "Upgrade to $DBversion done (Bug 7673: Adds 2 new prefs (SubfieldsToAllowForRestrictedEditing and SubfieldsToAllowForRestrictedBatchmod) and 3 new permissions (edit_items_restricted and delete_all_items and items_batchmod_restricted))\n";
9523     SetVersion($DBversion);
9524 }
9525
9526 $DBversion = "3.17.00.054";
9527 if (CheckVersion($DBversion)) {
9528     $dbh->do(q{
9529         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
9530         ('AllowRenewalIfOtherItemsAvailable','0',NULL,'If enabled, allow a patron to renew an item with unfilled holds if other available items can fill that hold.','YesNo')
9531     });
9532     print "Upgrade to $DBversion done (Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds)\n";
9533     SetVersion($DBversion);
9534 }
9535
9536 $DBversion = "3.17.00.055";
9537 if ( CheckVersion($DBversion) ) {
9538     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEnable', '0', NULL, 'Enable communication with the Norwegian national patron database.', 'YesNo')");
9539     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBEndpoint', '', NULL, 'Which NL endpoint to use.', 'Free')");
9540     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBUsername', '', NULL, 'Username for communication with the Norwegian national patron database.', 'Free')");
9541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBPassword', '', NULL, 'Password for communication with the Norwegian national patron database.', 'Free')");
9542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('NorwegianPatronDBSearchNLAfterLocalHit','0',NULL,'Search NL if a search has already given one or more local hits?.','YesNo')");
9543     $dbh->do("
9544 CREATE TABLE borrower_sync (
9545     borrowersyncid int(11) NOT NULL AUTO_INCREMENT,
9546     borrowernumber int(11) NOT NULL,
9547     synctype varchar(32) NOT NULL,
9548     sync tinyint(1) NOT NULL DEFAULT '0',
9549     syncstatus varchar(10) DEFAULT NULL,
9550     lastsync varchar(50) DEFAULT NULL,
9551     hashed_pin varchar(64) DEFAULT NULL,
9552     PRIMARY KEY (borrowersyncid),
9553     KEY borrowernumber (borrowernumber),
9554     CONSTRAINT borrower_sync_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9555 ) ENGINE=InnoDB DEFAULT CHARSET=utf8"
9556 );
9557     print "Upgrade to $DBversion done (Bug 11401 - Add support for Norwegian national library card)\n";
9558     SetVersion($DBversion);
9559 }
9560
9561 $DBversion = "3.17.00.056";
9562 if ( CheckVersion($DBversion) ) {
9563     $dbh->do(q{
9564         UPDATE systempreferences SET value = 'pubdate,itemtype,language,sorting,location' WHERE variable='OpacAdvSearchOptions'
9565     });
9566
9567     $dbh->do(q{
9568         UPDATE systempreferences SET value = 'pubdate,itemtype,language,subtype,sorting,location' WHERE variable='OpacAdvSearchMoreOptions'
9569     });
9570
9571     print "Upgrade to $DBversion done (Bug 9043 - Update the values for OpacAdvSearchOptions and OpacAdvSearchOptions)\n";
9572     SetVersion($DBversion);
9573 }
9574
9575 $DBversion = "3.17.00.057";
9576 if ( CheckVersion($DBversion) ) {
9577     print "Upgrade to $DBversion done (Koha 3.18 beta)\n";
9578     SetVersion ($DBversion);
9579 }
9580
9581 $DBversion = "3.17.00.058";
9582 if( CheckVersion($DBversion) ){
9583     $dbh->do("INSERT INTO systempreferences (variable, explanation, type) VALUES('DefaultLongOverdueChargeValue','Charge a lost item to the borrower account when the LOST value of the item changes to n',  'integer')");
9584     $dbh->do("INSERT INTO systempreferences (variable, explanation, type) VALUES('DefaultLongOverdueLostValue', 'Set the LOST value of an item to n when the item has been overdue for more than defaultlongoverduedays days.', 'integer')");
9585     $dbh->do("INSERT INTO systempreferences (variable, explanation, type) VALUES('DefaultLongOverdueDays', 'Set the LOST value of an item when the item has been overdue for more than n days.',  'integer')");
9586     print "Upgrade to $DBversion done (Bug 8337: System preferences for longoverdue cron)\n";
9587     SetVersion($DBversion);
9588 }
9589
9590 $DBversion = "3.17.00.059";
9591 if ( CheckVersion($DBversion) ) {
9592     $dbh->do(q{
9593         UPDATE permissions SET description = "Add and delete budgets (but can't modifiy budgets)" WHERE description = "Add and delete budgets (but cant modify budgets)";
9594     });
9595     print "Upgrade to $DBversion done (Bug 10749: Fix typo in budget_add_del permission description)\n";
9596     SetVersion ($DBversion);
9597 }
9598
9599 $DBversion = "3.17.00.060";
9600 if ( CheckVersion($DBversion) ) {
9601     my $count_l = $dbh->selectcol_arrayref(q|
9602         SELECT COUNT(*) FROM letter WHERE message_transport_type='feed'
9603     |);
9604     my $count_mq = $dbh->selectcol_arrayref(q|
9605         SELECT COUNT(*) FROM message_queue WHERE message_transport_type='feed'
9606     |);
9607     my $count_ott = $dbh->selectcol_arrayref(q|
9608         SELECT COUNT(*) FROM overduerules_transport_types WHERE message_transport_type='feed'
9609     |);
9610     my $count_mt = $dbh->selectcol_arrayref(q|
9611         SELECT COUNT(*) FROM message_transports WHERE message_transport_type='feed'
9612     |);
9613     my $count_bmtp = $dbh->selectcol_arrayref(q|
9614         SELECT COUNT(*) FROM borrower_message_transport_preferences WHERE message_transport_type='feed'
9615     |);
9616
9617     my $deleted = 0;
9618     if ( $count_l->[0] == 0 and $count_mq->[0] == 0 and $count_ott->[0] == 0 and $count_mt->[0] == 0 and $count_bmtp->[0] == 0 ) {
9619         $deleted = $dbh->do(q|
9620             DELETE FROM message_transport_types where message_transport_type='feed'
9621         |);
9622         $deleted = $deleted ne '0E0' ? 1 : 0;
9623     }
9624
9625     print "Upgrade to $DBversion done (Bug 12298: Delete the 'feed' message transport type " . ($deleted ? '(deleted!)' : '(not deleted)') . ")\n";
9626     SetVersion($DBversion);
9627 }
9628
9629 $DBversion = "3.18.00.000";
9630 if ( CheckVersion($DBversion) ) {
9631     print "Upgrade to $DBversion done (3.18.0 release)\n";
9632     SetVersion($DBversion);
9633 }
9634
9635 $DBversion = "3.19.00.000";
9636 if ( CheckVersion($DBversion) ) {
9637     print "Upgrade to $DBversion done (there's life after 3.18)\n";
9638     SetVersion ($DBversion);
9639 }
9640
9641 $DBversion = "3.19.00.001";
9642 if ( CheckVersion($DBversion) ) {
9643     $dbh->do("
9644         UPDATE systempreferences
9645         SET options = 'public|school|academic|research|private|societyAssociation|corporate|government|religiousOrg|subscription'
9646         WHERE variable = 'UsageStatsLibraryType'
9647     ");
9648     if ( C4::Context->preference("UsageStatsLibraryType") eq "university" ) {
9649         C4::Context->set_preference("UsageStatsLibraryType", "academic")
9650     }
9651     print "Upgrade to $DBversion done (Bug 13436: Add more options to UsageStatsLibraryType)\n";
9652     SetVersion ($DBversion);
9653 }
9654
9655 $DBversion = "3.19.00.002";
9656 if ( CheckVersion($DBversion) ) {
9657     $dbh->do(q|
9658         UPDATE suggestions SET branchcode="" WHERE branchcode="__ANY__"
9659     |);
9660     print "upgrade to $DBversion done (Bug 10753: replace __ANY__ with empty string in suggestions.branchcode)\n";
9661     SetVersion ($DBversion);
9662 }
9663
9664 $DBversion = "3.19.00.003";
9665 if ( CheckVersion($DBversion) ) {
9666     my ($count) = $dbh->selectrow_array("SELECT COUNT(*) FROM borrowers GROUP BY userid HAVING COUNT(userid) > 1");
9667
9668     if ( $count ) {
9669         print "Upgrade to $DBversion done (Bug 1861 - Unique patrons logins not (totally) enforced) FAILED!\n";
9670         print "Your database has users with duplicate user logins. Please have your administrator deduplicate your user logins.\n";
9671         print "Afterward, your Koha administrator should execute the following database query: ALTER TABLE borrowers DROP INDEX userid, ADD UNIQUE userid (userid)";
9672     } else {
9673         $dbh->do(q{
9674             ALTER TABLE borrowers
9675                 DROP INDEX userid ,
9676                 ADD UNIQUE userid (userid)
9677         });
9678         print "Upgrade to $DBversion done (Bug 1861: Unique patrons logins not (totally) enforced)\n";
9679     }
9680     SetVersion ($DBversion);
9681 }
9682
9683 $DBversion = "3.19.00.004";
9684 if ( CheckVersion($DBversion) ) {
9685     my $pref_value = C4::Context->preference('OpacExportOptions');
9686     $pref_value =~ s/\|/,/g; # multiple is separated by ,
9687     $dbh->do(q{
9688         UPDATE systempreferences
9689             SET value = ?,
9690                 type = 'multiple'
9691         WHERE variable = 'OpacExportOptions'
9692     }, {}, $pref_value );
9693     print "Upgrade to $DBversion done (Bug 13346: OpacExportOptions is now multiple)\n";
9694     SetVersion ($DBversion);
9695 }
9696
9697 $DBversion = "3.19.00.005";
9698 if(CheckVersion($DBversion)) {
9699     $dbh->do(q{
9700         ALTER TABLE authorised_values MODIFY COLUMN category VARCHAR(32) NOT NULL DEFAULT ''
9701     });
9702
9703     $dbh->do(q{
9704         ALTER TABLE borrower_attribute_types MODIFY COLUMN authorised_value_category VARCHAR(32) DEFAULT NULL
9705     });
9706
9707     print "Upgrade to $DBversion done (Bug 13379: Modify authorised_values.category to varchar(32))\n";
9708     SetVersion($DBversion);
9709 }
9710
9711 $DBversion = "3.19.00.006";
9712 if ( CheckVersion($DBversion) ) {
9713     $dbh->do(q|SET foreign_key_checks = 0|);
9714     my $sth = $dbh->table_info( '','','','TABLE' );
9715     my ( $cat, $schema, $name, $type, $remarks );
9716     while ( ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
9717         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
9718         $table_sth->execute;
9719         my @table = $table_sth->fetchrow_array;
9720         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
9721             if ( $name eq 'marc_subfield_structure' ) {
9722                 $dbh->do(q|
9723                     ALTER TABLE marc_subfield_structure
9724                     MODIFY COLUMN tagfield varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9725                     MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '',
9726                     MODIFY COLUMN liblibrarian varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9727                     MODIFY COLUMN libopac varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9728                     MODIFY COLUMN kohafield varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
9729                     MODIFY COLUMN authorised_value varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9730                     MODIFY COLUMN authtypecode varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
9731                     MODIFY COLUMN value_builder varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
9732                     MODIFY COLUMN frameworkcode varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
9733                     MODIFY COLUMN seealso varchar(1100) COLLATE utf8_unicode_ci DEFAULT NULL,
9734                     MODIFY COLUMN link varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL
9735                 |);
9736                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9737             }
9738             else {
9739                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
9740             }
9741         }
9742     }
9743     $dbh->do(q|SET foreign_key_checks = 1|);;
9744
9745     print "Upgrade to $DBversion done (Bug 11944: Convert DB tables to utf8_unicode_ci)\n";
9746     SetVersion($DBversion);
9747 }
9748
9749 $DBversion = "3.19.00.007";
9750 if ( CheckVersion($DBversion) ) {
9751     my $orphan_budgets = $dbh->selectall_arrayref(q|
9752         SELECT budget_id, budget_name, budget_code
9753         FROM aqbudgets
9754         WHERE   budget_parent_id IS NOT NULL
9755             AND budget_parent_id NOT IN (
9756                 SELECT DISTINCT budget_id FROM aqbudgets
9757             )
9758     |, { Slice => {} } );
9759
9760     if ( @$orphan_budgets ) {
9761         for my $b ( @$orphan_budgets ) {
9762             print "Fund $b->{budget_name} (code:$b->{budget_code}, id:$b->{budget_id}) does not have a parent, it may cause problem\n";
9763         }
9764         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: FAIL)\n";
9765     } else {
9766         print "Upgrade to $DBversion done (Bug 12905: Check budget integrity: OK)\n";
9767     }
9768     SetVersion ($DBversion);
9769 }
9770
9771 $DBversion = "3.19.00.008";
9772 if ( CheckVersion($DBversion) ) {
9773     my $number_of_orders_not_linked = $dbh->selectcol_arrayref(q|
9774         SELECT COUNT(*)
9775         FROM aqorders o
9776         WHERE NOT EXISTS (
9777             SELECT NULL
9778             FROM aqbudgets b
9779             WHERE b.budget_id = o.budget_id
9780         );
9781     |);
9782
9783     if ( $number_of_orders_not_linked->[0] > 0 ) {
9784         $dbh->do(q|
9785             INSERT INTO aqbudgetperiods(budget_period_startdate, budget_period_enddate, budget_period_active, budget_period_description, budget_period_total) VALUES ( CAST(NOW() AS date), CAST(NOW() AS date), 0, "WARNING: This budget has been automatically created by the updatedatabase script, please see bug 12601 for more information", 0)
9786         |);
9787         my $budget_period_id = $dbh->last_insert_id( undef, undef, 'aqbudgetperiods', undef );
9788         $dbh->do(qq|
9789             INSERT INTO aqbudgets(budget_code, budget_name, budget_amount, budget_period_id) VALUES ( "BACKUP_TMP", "WARNING: fund created by the updatedatabase script, please see bug 12601", 0, $budget_period_id );
9790         |);
9791         my $budget_id = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
9792         $dbh->do(qq|
9793             UPDATE aqorders o
9794             SET budget_id = $budget_id
9795             WHERE NOT EXISTS (
9796                 SELECT NULL
9797                 FROM aqbudgets b
9798                 WHERE b.budget_id = o.budget_id
9799             )
9800         |);
9801     }
9802
9803     $dbh->do(q|
9804         ALTER TABLE aqorders
9805         ADD CONSTRAINT aqorders_budget_id_fk FOREIGN KEY (budget_id) REFERENCES aqbudgets(budget_id) ON DELETE CASCADE ON UPDATE CASCADE
9806     |);
9807
9808     print "Upgrade to $DBversion done (Bug 12601: Add new foreign key aqorders.budget_id" . ( ( $number_of_orders_not_linked->[0] > 0 )  ? ' WARNING: temporary budget and fund have been created (search for "BACKUP_TMP"). At least one of your order was not linked to a budget' : '' ) . ")\n";
9809     SetVersion($DBversion);
9810 }
9811
9812 $DBversion = "3.19.00.009";
9813 if ( CheckVersion($DBversion) ) {
9814     $dbh->do(q|
9815         UPDATE suggestions s SET s.budgetid = NULL
9816         WHERE NOT EXISTS (
9817             SELECT NULL
9818             FROM aqbudgets b
9819             WHERE b.budget_id = s.budgetid
9820         );
9821     |);
9822
9823     $dbh->do(q|
9824         ALTER TABLE suggestions
9825         ADD CONSTRAINT suggestions_budget_id_fk FOREIGN KEY (budgetid) REFERENCES aqbudgets(budget_id) ON DELETE SET NULL ON UPDATE CASCADE
9826     |);
9827
9828     print "Upgrade to $DBversion done (Bug 13007: Add new foreign key suggestions.budgetid)\n";
9829     SetVersion($DBversion);
9830 }
9831
9832 $DBversion = "3.19.00.010";
9833 if ( CheckVersion($DBversion) ) {
9834     $dbh->do(q|
9835         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
9836         VALUES('SessionRestrictionByIP','1','Check for Change in  Remote IP address for Session Security. Disable when remote ip address changes frequently.','','YesNo')
9837     |);
9838     print "Upgrade to $DBversion done (Bug 5511: SessionRestrictionByIP)\n";
9839     SetVersion ($DBversion);
9840 }
9841
9842 $DBversion = "3.19.00.011";
9843 if ( CheckVersion($DBversion) ) {
9844     $dbh->do(q|
9845         INSERT INTO userflags (bit, flag, flagdesc, defaulton) VALUES
9846         (20, 'lists', 'Lists', 0)
9847     |);
9848     $dbh->do(q|
9849         INSERT INTO permissions (module_bit, code, description) VALUES
9850         (20, 'delete_public_lists', 'Delete public lists')
9851     |);
9852     print "Upgrade to $DBversion done (Bug 13417: Add permission to delete public lists)\n";
9853     SetVersion ($DBversion);
9854 }
9855
9856 $DBversion = "3.19.00.012";
9857 if(CheckVersion($DBversion)) {
9858     $dbh->do(q{
9859         ALTER TABLE biblioitems MODIFY COLUMN marcxml longtext
9860     });
9861
9862     $dbh->do(q{
9863         ALTER TABLE deletedbiblioitems MODIFY COLUMN marcxml longtext
9864     });
9865
9866     print "Upgrade to $DBversion done (Bug 13523 Remove NOT NULL restriction on field marcxml due to mysql STRICT_TRANS_TABLES)\n";
9867     SetVersion ($DBversion);
9868 }
9869
9870 $DBversion = "3.19.00.013";
9871 if ( CheckVersion($DBversion) ) {
9872     $dbh->do(q|
9873         INSERT INTO permissions (module_bit, code, description) VALUES
9874           (13, 'records_batchmod', 'Perform batch modification of records (biblios or authorities)')
9875     |);
9876     print "Upgrade to $DBversion done (Bug 11395: Add permission tools_records_batchmod)\n";
9877     SetVersion($DBversion);
9878 }
9879
9880 $DBversion = "3.19.00.014";
9881 if ( CheckVersion($DBversion) ) {
9882     $dbh->do(q|
9883         CREATE TABLE aqorder_users (
9884             ordernumber int(11) NOT NULL,
9885             borrowernumber int(11) NOT NULL,
9886             PRIMARY KEY (ordernumber, borrowernumber),
9887             CONSTRAINT aqorder_users_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE,
9888             CONSTRAINT aqorder_users_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
9889         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
9890     |);
9891
9892     $dbh->do(q|
9893         INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type)
9894         VALUES ('acquisition', 'ACQ_NOTIF_ON_RECEIV', '', 'Notification on receiving', 'Order received', 'Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\n The order <<aqorders.ordernumber>> (<<biblio.title>>) has been received.\n\nYour library.', 'email')
9895     |);
9896     print "Upgrade to $DBversion done (Bug 12648: Add letter ACQ_NOTIF_ON_RECEIV )\n";
9897     SetVersion ($DBversion);
9898 }
9899
9900 $DBversion = "3.19.00.015";
9901 if ( CheckVersion($DBversion) ) {
9902     $dbh->do(q|
9903         ALTER TABLE search_history ADD COLUMN id INT(11) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);
9904     |);
9905     print "Upgrade to $DBversion done (Bug 11430: Add primary key for search_history)\n";
9906     SetVersion ($DBversion);
9907 }
9908
9909 $DBversion = "3.19.00.016";
9910 if(CheckVersion($DBversion)) {
9911     my @order_cancellation_reason = $dbh->selectrow_array("SELECT count(*) FROM authorised_values WHERE category='ORDER_CANCELLATION_REASON'");
9912     if ($order_cancellation_reason[0] == 0) {
9913         $dbh->do(q{
9914             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9915              ('ORDER_CANCELLATION_REASON', 0, 'No reason provided'),
9916              ('ORDER_CANCELLATION_REASON', 1, 'Out of stock'),
9917              ('ORDER_CANCELLATION_REASON', 2, 'Restocking')
9918         });
9919
9920         my $already_existing_reasons = $dbh->selectcol_arrayref(q{
9921             SELECT DISTINCT( cancellationreason )
9922             FROM aqorders;
9923         }, { Slice => {} });
9924
9925         my $update_orders_sth = $dbh->prepare(q{
9926             UPDATE aqorders
9927             SET cancellationreason = ?
9928             WHERE cancellationreason = ?
9929         });
9930
9931         my $insert_av_sth = $dbh->prepare(q{
9932             INSERT INTO authorised_values (category, authorised_value, lib) VALUES
9933              ('ORDER_CANCELLATION_REASON', ?, ?)
9934         });
9935         my $i = 3;
9936         for my $reason ( @$already_existing_reasons ) {
9937             next unless $reason;
9938             $insert_av_sth->execute( $i, $reason );
9939             $update_orders_sth->execute( $i, $reason );
9940             $i++;
9941         }
9942         print "Upgrade to $DBversion done (Bug 13380: Add the ORDER_CANCELLATION_REASON authorised value)\n";
9943     }
9944     else {
9945         print "Upgrade to $DBversion done (Bug 13380: ORDER_CANCELLATION_REASON authorised value already existed from earlier update!)\n";
9946     }
9947
9948     SetVersion($DBversion);
9949 }
9950
9951 $DBversion = '3.19.00.017';
9952 if ( CheckVersion($DBversion) ) {
9953     # First create the column
9954     $dbh->do("ALTER TABLE issuingrules ADD onshelfholds tinyint(1) default 0 NOT NULL");
9955     # Now update the column
9956     if (C4::Context->preference("AllowOnShelfHolds")){
9957         # Pref is on, set allow for all rules
9958         $dbh->do("UPDATE issuingrules SET onshelfholds=1");
9959     } else {
9960         # If the preference is not set, leave off
9961         $dbh->do("UPDATE issuingrules SET onshelfholds=0");
9962     }
9963     # Remove from the systempreferences table
9964     $dbh->do("DELETE FROM systempreferences WHERE variable = 'AllowOnShelfHolds'");
9965
9966     # First create the column
9967     $dbh->do("ALTER TABLE issuingrules ADD opacitemholds char(1) DEFAULT 'N' NOT NULL");
9968     # Now update the column
9969     my $opacitemholds = C4::Context->preference("OPACItemHolds") || '';
9970     if (lc ($opacitemholds) eq 'force') {
9971         $opacitemholds = 'F';
9972     }
9973     else {
9974         $opacitemholds = $opacitemholds ? 'Y' : 'N';
9975     }
9976     # Set allow for all rules
9977     $dbh->do("UPDATE issuingrules SET opacitemholds='$opacitemholds'");
9978
9979     # Remove from the systempreferences table
9980     $dbh->do("DELETE FROM systempreferences WHERE variable = 'OPACItemHolds'");
9981
9982     print "Upgrade to $DBversion done (Bug 5786: Move AllowOnShelfHolds to circulation matrix; Move OPACItemHolds system preference to circulation matrix)\n";
9983     SetVersion ($DBversion);
9984 }
9985
9986
9987 $DBversion = "3.19.00.018";
9988 if ( CheckVersion($DBversion) ) {
9989     $dbh->do(q|
9990         UPDATE systempreferences set variable="OpacAdditionalStylesheet" WHERE variable="opaccolorstylesheet"
9991     |);
9992     print "Upgrade to $DBversion done (Bug 10328: Rename opaccolorstylesheet to OpacAdditionalStylesheet\n";
9993     SetVersion ($DBversion);
9994 }
9995
9996 $DBversion = "3.19.00.019";
9997 if ( CheckVersion($DBversion) ) {
9998     $dbh->do(q{
9999         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10000         VALUES('Coce','0', 'If on, enables cover retrieval from the configured Coce server', NULL, 'YesNo')
10001     });
10002     $dbh->do(q{
10003         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10004         VALUES('CoceHost', NULL, 'Coce server URL', NULL,'Free')
10005     });
10006     $dbh->do(q{
10007         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
10008         VALUES('CoceProviders', NULL, 'Coce providers', 'aws,gb,ol', 'multiple')
10009     });
10010     print "Upgrade to $DBversion done (Bug 9580: Cover image from Coce, a remote image URL cache)\n";
10011     SetVersion($DBversion);
10012 }
10013
10014 $DBversion = "3.19.00.020";
10015 if ( CheckVersion($DBversion) ) {
10016     $dbh->do(q|
10017         ALTER TABLE aqorders DROP COLUMN supplierreference;
10018     |);
10019
10020     print "Upgrade to $DBversion done (Bug 11008: DROP column aqorders.supplierreference)\n";
10021     SetVersion($DBversion);
10022 }
10023
10024 $DBversion = "3.19.00.021";
10025 if ( CheckVersion($DBversion) ) {
10026     $dbh->do(q|
10027         ALTER TABLE issues DROP COLUMN issuingbranch
10028     |);
10029     $dbh->do(q|
10030         ALTER TABLE old_issues DROP COLUMN issuingbranch
10031     |);
10032     print "Upgrade to $DBversion done (Bug 2806: Remove issuingbranch columns)\n";
10033     SetVersion ($DBversion);
10034 }
10035
10036 $DBversion = '3.19.00.022';
10037 if ( CheckVersion($DBversion) ) {
10038     $dbh->do(q{
10039         ALTER TABLE suggestions DROP COLUMN mailoverseeing;
10040     });
10041     print "Upgrade to $DBversion done (Bug 13006: Drop column suggestion.mailoverseeing)\n";
10042     SetVersion($DBversion);
10043 }
10044
10045 $DBversion = "3.19.00.023";
10046 if ( CheckVersion($DBversion) ) {
10047     $dbh->do(q|
10048         DELETE FROM systempreferences where variable = 'AddPatronLists'
10049     |);
10050     print "Upgrade to $DBversion done (Bug 13497: Remove the AddPatronLists system preferences)\n";
10051     SetVersion ($DBversion);
10052 }
10053
10054 $DBversion = "3.19.00.024";
10055 if ( CheckVersion($DBversion) ) {
10056     $dbh->do(qq|DROP table patroncards;|);
10057     print "Upgrade to $DBversion done (Bug 13539: Remove table patroncards from database as it's no longer in use)\n";
10058     SetVersion ($DBversion);
10059 }
10060
10061 $DBversion = "3.19.00.025";
10062 if ( CheckVersion($DBversion) ) {
10063     $dbh->do(q|
10064         INSERT INTO systempreferences ( variable, value, options, explanation, type ) VALUES
10065         ('SearchWithISBNVariations','0',NULL,'If enabled, search on all variations of the ISBN','YesNo')
10066     |);
10067     print "Upgrade to $DBversion done (Bug 13528: Add the SearchWithISBNVariations syspref)\n";
10068     SetVersion ($DBversion);
10069 }
10070
10071 $DBversion = "3.19.00.026";
10072 if( CheckVersion($DBversion) ) {
10073     if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
10074     $dbh->do(q{
10075         INSERT IGNORE INTO auth_tag_structure (authtypecode, tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value) VALUES
10076         ('', '388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL);
10077     });
10078
10079     $dbh->do(q{
10080         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10081         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10082         ('', '388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10083         ('', '388', '2', 'Source of term', 'Source of term', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10084         ('', '388', '3', 'Materials specified', 'Materials specified', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10085         ('', '388', '6', 'Linkage', 'Linkage', 0, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10086         ('', '388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', ''),
10087         ('', '388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, 3, NULL, NULL, NULL, 0, 0, '', '', '');
10088     });
10089
10090     $dbh->do(q{
10091         UPDATE IGNORE auth_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND tagfield IN
10092         ('100','110','111','130','400','410','411','430','500','510','511','530','700','710','730');
10093     });
10094
10095     $dbh->do(q{
10096         INSERT IGNORE INTO auth_subfield_structure (authtypecode, tagfield, tagsubfield, liblibrarian, libopac, repeatable,
10097         mandatory, tab, authorised_value, value_builder, seealso, isurl, hidden, linkid, kohafield, frameworkcode) VALUES
10098         ('', '150', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10099         ('', '151', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 1, NULL, NULL, NULL, 0, 0, '', '', ''),
10100         ('', '450', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10101         ('', '451', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 4, NULL, NULL, NULL, 0, 0, '', '', ''),
10102         ('', '550', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10103         ('', '551', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 5, NULL, NULL, NULL, 0, 0, '', '', ''),
10104         ('', '750', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10105         ('', '751', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10106         ('', '748', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10107         ('', '755', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10108         ('', '780', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10109         ('', '781', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10110         ('', '782', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10111         ('', '785', 'i', 'Relationship information', 'Relationship information', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10112         ('', '710', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10113         ('', '730', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10114         ('', '748', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10115         ('', '750', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10116         ('', '751', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10117         ('', '755', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10118         ('', '762', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10119         ('', '780', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10120         ('', '781', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10121         ('', '782', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10122         ('', '785', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', ''),
10123         ('', '788', '4', 'Relationship code', 'Relationship code', 1, 0, 7, NULL, NULL, NULL, 0, 0, '', '', '');
10124     });
10125
10126     $dbh->do(q{
10127         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship information', libopac = 'Relationship information'
10128         WHERE tagsubfield = 'i' AND tagfield IN ('700','710','730','750','751','762');
10129     });
10130
10131     $dbh->do(q{
10132         UPDATE IGNORE auth_subfield_structure SET liblibrarian = 'Relationship code', libopac = 'Relationship code'
10133         WHERE tagsubfield = '4' AND tagfield IN ('700','710');
10134     });
10135
10136     $dbh->do(q{
10137         INSERT IGNORE INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, frameworkcode) VALUES
10138         ('370', 'ASSOCIATED PLACE', 'ASSOCIATED PLACE', 1, 0, NULL, ''),
10139         ('388', 'TIME PERIOD OF CREATION', 'TIME PERIOD OF CREATION', 1, 0, NULL, '');
10140     });
10141
10142     $dbh->do(q{
10143         INSERT IGNORE INTO marc_subfield_structure (tagfield, tagsubfield, liblibrarian, libopac, repeatable, mandatory,
10144         kohafield, tab, authorised_value, authtypecode, value_builder, isurl, hidden, frameworkcode, seealso, link, defaultvalue) VALUES
10145         ('370', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10146         ('370', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10147         ('370', '6', 'Linkage', 'Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10148         ('370', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10149         ('370', 'c', 'Associated country', 'Associated country', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10150         ('370', 'f', 'Other associated place', 'Other associated place', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10151         ('370', 'g', 'Place of origin of work', 'Place of origin of work', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10152         ('370', 's', 'Start period', 'Start period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10153         ('370', 't', 'End period', 'End period', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10154         ('370', 'u', 'Uniform Resource Identifier', 'Uniform Resource Identifier', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10155         ('370', 'v', 'Source of information', 'Source of information', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10156         ('377', 'l', 'Language term', 'Language term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10157         ('382', 's', 'Total number of performers', 'Total number of performers', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10158         ('388', '0', 'Authority record control number or standard number', 'Authority record control number or standard number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10159         ('388', '2', 'Source of term', 'Source of term', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10160         ('388', '3', ' Materials specified', ' Materials specified', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10161         ('388', '6', ' Linkage', ' Linkage', 0, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10162         ('388', '8', 'Field link and sequence number', 'Field link and sequence number', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10163         ('388', 'a', 'Time period of creation term', 'Time period of creation term', 1, 0, '', 3, '', '', '', NULL, -6, '', '', '', NULL),
10164         ('650', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL),
10165         ('651', 'g', 'Miscellaneous information', 'Miscellaneous information', 1, 0, '', 6, '', '', '', 0, -1, '', '', '', NULL);
10166     });
10167
10168     $dbh->do(q{
10169         UPDATE IGNORE marc_subfield_structure SET repeatable = 1 WHERE tagsubfield = 'g' AND
10170         tagfield IN ('100','110','111','130','240','243','246','247','600','610','611','630','700','710','711','730','800','810','811','830');
10171     });
10172     }
10173
10174     print "Upgrade to $DBversion done (Bug 13322: Update MARC21 frameworks to Update No. 19 - October 2014)\n";
10175     SetVersion($DBversion);
10176 }
10177
10178 $DBversion = '3.19.00.027';
10179 if ( CheckVersion($DBversion) ) {
10180     $dbh->do("ALTER TABLE items ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10181     $dbh->do("ALTER TABLE deleteditems ADD COLUMN itemnotes_nonpublic MEDIUMTEXT AFTER itemnotes");
10182     print "Upgrade to $DBversion done (Bug 4222: Nonpublic note not appearing in the staff client) <b>Please check each of your frameworks to ensure your non-public item notes are mapped to items.itemnotes_nonpublic. After doing so please have your administrator run misc/batchRebuildItemsTables.pl </b>)\n";
10183     SetVersion($DBversion);
10184 }
10185
10186 $DBversion = "3.19.00.028";
10187 if( CheckVersion($DBversion) ) {
10188     eval {
10189         local $dbh->{PrintError} = 0;
10190         $dbh->do(q{
10191             ALTER TABLE issues DROP PRIMARY KEY
10192         });
10193     };
10194
10195     $dbh->do(q{
10196         ALTER TABLE old_issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10197     });
10198
10199     $dbh->do(q{
10200         ALTER TABLE old_issues CHANGE issue_id issue_id INT( 11 ) NOT NULL
10201     });
10202
10203     $dbh->do(q{
10204         ALTER TABLE issues ADD issue_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10205     });
10206
10207     $dbh->do(q{
10208         UPDATE issues SET issue_id = issue_id + ( SELECT COUNT(*) FROM old_issues ) ORDER BY issue_id DESC
10209     });
10210
10211     my $max_issue_id = $schema->resultset('Issue')->get_column('issue_id')->max();
10212     if ($max_issue_id) {
10213         $max_issue_id++;
10214         $dbh->do(qq{
10215             ALTER TABLE issues AUTO_INCREMENT = $max_issue_id
10216         });
10217     }
10218
10219     print "Upgrade to $DBversion done (Bug 13790: Add unique id issue_id to issues and oldissues tables)\n";
10220     SetVersion($DBversion);
10221 }
10222
10223 $DBversion = "3.19.00.029";
10224 if ( CheckVersion($DBversion) ) {
10225     $dbh->do(q|
10226          ALTER TABLE sessions CHANGE COLUMN a_session a_session MEDIUMTEXT
10227     |);
10228     print "Upgrade to $DBversion done (Bug 13606: Upgrade sessions.a_session to MEDIUMTEXT)\n";
10229     SetVersion($DBversion);
10230 }
10231
10232 $DBversion = "3.19.00.030";
10233 if ( CheckVersion($DBversion) ) {
10234     $dbh->do(q|
10235 UPDATE language_subtag_registry SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10236     |);
10237     $dbh->do(q|
10238 UPDATE language_rfc4646_to_iso639 SET rfc4646_subtag = 'kn' WHERE rfc4646_subtag = 'ka' AND iso639_2_code = 'kan';
10239     |);
10240     $dbh->do(q|
10241 UPDATE language_descriptions SET subtag = 'kn', lang = 'kn' WHERE subtag = 'ka' AND lang = 'ka' AND description = 'ಕನ್ನಡ';
10242     |);
10243     $dbh->do(q|
10244 UPDATE language_descriptions SET subtag = 'kn' WHERE subtag = 'ka' AND description = 'Kannada';
10245     |);
10246     $dbh->do(q|
10247 INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added) VALUES ( 'ka', 'language', 'Georgian','2015-04-20');
10248     |);
10249     $dbh->do(q|
10250 DELETE FROM language_subtag_registry
10251        WHERE NOT id IN
10252          (SELECT id FROM
10253            (SELECT MIN(id) as id,subtag,type,description,added
10254             FROM language_subtag_registry
10255             GROUP BY subtag,type,description,added)
10256            AS subtable);
10257     |);
10258     $dbh->do(q|
10259 INSERT IGNORE INTO language_rfc4646_to_iso639(rfc4646_subtag,iso639_2_code) VALUES ( 'ka', 'geo');
10260     |);
10261     $dbh->do(q|
10262 DELETE FROM language_rfc4646_to_iso639
10263        WHERE NOT id IN
10264          (SELECT id FROM
10265            (SELECT MIN(id) as id,rfc4646_subtag,iso639_2_code
10266             FROM language_rfc4646_to_iso639
10267             GROUP BY rfc4646_subtag,iso639_2_code)
10268            AS subtable);
10269     |);
10270     $dbh->do(q|
10271 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'ka', 'ქართული');
10272     |);
10273     $dbh->do(q|
10274 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'en', 'Georgian');
10275     |);
10276     $dbh->do(q|
10277 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'fr', 'Géorgien');
10278     |);
10279     $dbh->do(q|
10280 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'de', 'Georgisch');
10281     |);
10282     $dbh->do(q|
10283 INSERT IGNORE INTO language_descriptions(subtag, type, lang, description) VALUES ( 'ka', 'language', 'es', 'Georgiano');
10284     |);
10285     $dbh->do(q|
10286 DELETE FROM language_descriptions
10287        WHERE NOT id IN
10288          (SELECT id FROM
10289            (SELECT MIN(id) as id,subtag,type,lang,description
10290             FROM language_descriptions GROUP BY subtag,type,lang,description)
10291            AS subtable);
10292     |);
10293     print "Upgrade to $DBversion done (Bug 14030: Add Georgian language and fix Kannada language code)\n";
10294     SetVersion($DBversion);
10295 }
10296
10297 $DBversion = "3.19.00.031";
10298 if ( CheckVersion($DBversion) ) {
10299     $dbh->do(q{
10300         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10301         VALUES('IdRef','0','Disable/enable the IdRef webservice from the OPAC detail page.',NULL,'YesNo')
10302     });
10303     print "Upgrade to $DBversion done (Bug 8992: Add system preference IdRef))\n";
10304     SetVersion($DBversion);
10305 }
10306
10307 $DBversion = "3.19.00.032";
10308 if ( CheckVersion($DBversion) ) {
10309     $dbh->do(q|
10310         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10311         VALUES('AddressFormat','us','Choose format to display postal addresses','','Choice')
10312     |);
10313     print "Upgrade to $DBversion done (Bug 4041: Address Format as a I18N/L10N system preference\n";
10314     SetVersion ($DBversion);
10315 }
10316
10317 $DBversion = "3.19.00.033";
10318 if ( CheckVersion($DBversion) ) {
10319     $dbh->do(q|
10320         ALTER TABLE auth_header
10321         CHANGE COLUMN datemodified modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP
10322     |);
10323     $dbh->do(q|
10324         ALTER TABLE auth_header
10325         CHANGE COLUMN modification_time modification_time TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
10326     |);
10327     print "Upgrade to $DBversion done (Bug 11165: Update auth_header.datemodified when updated)\n";
10328     SetVersion ($DBversion);
10329 }
10330
10331 $DBversion = "3.19.00.034";
10332 if ( CheckVersion($DBversion) ) {
10333     $dbh->do(q|
10334         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10335         VALUES('CardnumberLength', '', '', 'Set a length for card numbers.', 'Free')
10336     |);
10337     print "Upgrade to $DBversion done (Bug 13984: CardnumberLength syspref missing on some setups\n";
10338     SetVersion ($DBversion);
10339 }
10340
10341 $DBversion = "3.19.00.035";
10342 if ( CheckVersion($DBversion) ) {
10343     $dbh->do(q|
10344         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('useDischarge','','Allows librarians to discharge borrowers and borrowers to request a discharge','','YesNo')
10345     |);
10346     $dbh->do(q|
10347         INSERT IGNORE INTO letter (module, code, name, title, content) VALUES('members', 'DISCHARGE', 'Discharge', 'Discharge for <<borrowers.firstname>> <<borrowers.surname>>', '<h1>Discharge</h1>\r\n\r\nThe library <<borrowers.branchcode>> certifies that the following borrower :\r\n\r\n    <<borrowers.firstname>> <<borrowers.surname>>\r\n   Cardnumber : <<borrowers.cardnumber>>\r\n\r\nreturned all his documents.')
10348     |);
10349
10350     $dbh->do(q|
10351         ALTER TABLE borrower_debarments CHANGE type type ENUM('SUSPENSION','OVERDUES','MANUAL','DISCHARGE') NOT NULL DEFAULT 'MANUAL'
10352     |);
10353
10354     $dbh->do(q|
10355         CREATE TABLE discharges (
10356           borrower int(11) DEFAULT NULL,
10357           needed timestamp NULL DEFAULT NULL,
10358           validated timestamp NULL DEFAULT NULL,
10359           KEY borrower_discharges_ibfk1 (borrower),
10360           CONSTRAINT borrower_discharges_ibfk1 FOREIGN KEY (borrower) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
10361         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
10362     |);
10363
10364     print "Upgrade to $DBversion done (Bug 8007: Add System Preferences useDischarge, the discharge notice and the new table discharges)\n";
10365     SetVersion($DBversion);
10366 }
10367
10368 $DBversion = "3.19.00.036";
10369 if ( CheckVersion($DBversion) ) {
10370     $dbh->do(q|
10371         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10372         VALUES ('CronjobLog','0',NULL,'If ON, log information from cron jobs.','YesNo')
10373     |);
10374     print "Upgrade to $DBversion done (Bug 13889: Add cron jobs information to system log)\n";
10375     SetVersion ($DBversion);
10376 }
10377
10378 $DBversion = "3.19.00.037";
10379 if ( CheckVersion($DBversion) ) {
10380     $dbh->do(q|
10381         ALTER TABLE marc_subfield_structure
10382         MODIFY COLUMN tagsubfield varchar(1) COLLATE utf8_bin NOT NULL DEFAULT ''
10383     |);
10384     print "Upgrade to $DBversion done (Bug 13810: Change collate for tagsubfield (utf8_bin))\n";
10385     SetVersion ($DBversion);
10386 }
10387
10388 $DBversion = "3.19.00.038";
10389 if ( CheckVersion($DBversion) ) {
10390     $dbh->do(q|
10391         ALTER TABLE virtualshelves
10392         ADD COLUMN created_on DATETIME NOT NULL AFTER lastmodified
10393     |);
10394     # Set created_on = lastmodified
10395     # I would say it's better than 0000-00-00
10396     # Set modified to the existing value (do not get the current ts!)
10397     $dbh->do(q|
10398         UPDATE virtualshelves
10399         SET created_on = lastmodified, lastmodified = lastmodified
10400     |);
10401     print "Upgrade to $DBversion done (Bug 13421: Add DB field virtualshelves.created_on)\n";
10402     SetVersion ($DBversion);
10403 }
10404
10405 $DBversion = "3.19.00.039";
10406 if ( CheckVersion($DBversion) ) {
10407     print "Upgrade to $DBversion done (Koha 3.20 beta)\n";
10408     SetVersion ($DBversion);
10409 }
10410
10411 $DBversion = "3.19.00.040";
10412 if ( CheckVersion($DBversion) ) {
10413     $dbh->do(q|
10414         ALTER TABLE aqorders DROP COLUMN totalamount
10415     |);
10416     print "Upgrade to $DBversion done (Bug 11006: Drop column aqorders.totalamount)\n";
10417     SetVersion ($DBversion);
10418 }
10419
10420 $DBversion = "3.19.00.041";
10421 if ( CheckVersion($DBversion) ) {
10422     unless ( index_exists( 'suggestions', 'status' ) ) {
10423         $dbh->do(q|
10424             ALTER TABLE suggestions ADD KEY status (STATUS)
10425         |);
10426     }
10427     unless ( index_exists( 'suggestions', 'biblionumber' ) ) {
10428         $dbh->do(q|
10429             ALTER TABLE suggestions ADD KEY biblionumber (biblionumber)
10430         |);
10431     }
10432     unless ( index_exists( 'suggestions', 'branchcode' ) ) {
10433         $dbh->do(q|
10434             ALTER TABLE suggestions ADD KEY branchcode (branchcode)
10435         |);
10436     }
10437     print "Upgrade to $DBversion done (Bug 14132: suggestions table is missing indexes)\n";
10438     SetVersion ($DBversion);
10439 }
10440
10441 $DBversion = "3.19.00.042";
10442 if ( CheckVersion($DBversion) ) {
10443     $dbh->do(q{
10444         DELETE ass.*
10445         FROM auth_subfield_structure AS ass
10446         LEFT JOIN auth_types USING(authtypecode)
10447         WHERE auth_types.authtypecode IS NULL
10448     });
10449
10450     unless ( foreign_key_exists( 'auth_subfield_structure', 'auth_subfield_structure_ibfk_1' ) ) {
10451         $dbh->do(q{
10452             ALTER TABLE auth_subfield_structure
10453             ADD CONSTRAINT auth_subfield_structure_ibfk_1
10454             FOREIGN KEY (authtypecode) REFERENCES auth_types(authtypecode)
10455             ON DELETE CASCADE ON UPDATE CASCADE
10456         });
10457     }
10458
10459     print "Upgrade to $DBversion done (Bug 8480: Add foreign key on auth_subfield_structure.authtypecode)\n";
10460     SetVersion($DBversion);
10461 }
10462
10463 $DBversion = "3.19.00.043";
10464 if ( CheckVersion($DBversion) ) {
10465     $dbh->do(q|
10466         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
10467         ('REPORT_GROUP', 'SER', 'Serials')
10468     |);
10469
10470     print "Upgrade to $DBversion done (Bug 5338: Add Serial to the report groups if does not exist)\n";
10471     SetVersion ($DBversion);
10472 }
10473
10474 $DBversion = "3.20.00.000";
10475 if ( CheckVersion($DBversion) ) {
10476     print "Upgrade to $DBversion done (Koha 3.20)\n";
10477     SetVersion ($DBversion);
10478 }
10479
10480 $DBversion = "3.21.00.000";
10481 if ( CheckVersion($DBversion) ) {
10482     print "Upgrade to $DBversion done (El tiempo vuela, un nuevo ciclo comienza.)\n";
10483     SetVersion ($DBversion);
10484 }
10485
10486 $DBversion = "3.21.00.001";
10487 if ( CheckVersion($DBversion) ) {
10488     $dbh->do(q|
10489         UPDATE systempreferences SET variable='IntranetUserJS' where variable='intranetuserjs'
10490     |);
10491     print "Upgrade to $DBversion done (Bug 12160: Rename intranetuserjs to IntranetUserJS)\n";
10492     SetVersion ($DBversion);
10493 }
10494
10495 $DBversion = "3.21.00.002";
10496 if ( CheckVersion($DBversion) ) {
10497     $dbh->do(q|
10498         UPDATE systempreferences SET variable='OPACUserJS' where variable='opacuserjs'
10499     |);
10500     print "Upgrade to $DBversion done (Bug 12160: Rename opacuserjs to OPACUserJS)\n";
10501     SetVersion ($DBversion);
10502 }
10503
10504 $DBversion = "3.21.00.003";
10505 if ( CheckVersion($DBversion) ) {
10506     $dbh->do(q|
10507         INSERT IGNORE INTO language_subtag_registry( subtag, type, description, added)
10508         VALUES ( 'IN', 'region', 'India','2015-05-28');
10509     |);
10510     $dbh->do(q|
10511         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10512         VALUES ( 'IN', 'region', 'en', 'India');
10513     |);
10514     $dbh->do(q|
10515         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
10516         VALUES ( 'IN', 'region', 'bn', 'ভারত');
10517     |);
10518     print "Upgrade to $DBversion done (Bug 14285: Add new region India)\n";
10519     SetVersion ($DBversion);
10520 }
10521
10522 $DBversion = '3.21.00.004';
10523 if ( CheckVersion($DBversion) ) {
10524     my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
10525     if (defined($OPACBaseURL) && substr($OPACBaseURL,0,4) ne "http") {
10526         my $explanation = q{Specify the Base URL of the OPAC, e.g., http://opac.mylibrary.com, including the protocol (http:// or https://). Otherwise, the http:// will be added automatically by Koha upon saving.};
10527         $OPACBaseURL = 'http://' . $OPACBaseURL;
10528         my $sth_OPACBaseURL = $dbh->prepare( q{
10529             UPDATE systempreferences SET value=?,explanation=?
10530             WHERE variable='OPACBaseURL'; } );
10531         $sth_OPACBaseURL->execute($OPACBaseURL,$explanation);
10532     }
10533     if (defined($OPACBaseURL)) {
10534         $dbh->do( q{ UPDATE letter
10535                      SET content=replace(content,
10536                                          'http://<<OPACBaseURL>>',
10537                                          '<<OPACBaseURL>>')
10538                      WHERE content LIKE "%http://<<OPACBaseURL>>%"; } );
10539     }
10540
10541     print "Upgrade to $DBversion done (Bug 5010: Fix OPACBaseURL to include protocol)\n";
10542     SetVersion($DBversion);
10543 }
10544
10545 $DBversion = "3.21.00.005";
10546 if ( CheckVersion($DBversion) ) {
10547     $dbh->do(q|
10548         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10549         VALUES ('ReportsLog','0',NULL,'If ON, log information about reports.','YesNo')
10550     |);
10551     print "Upgrade to $DBversion done (Bug 14024: Add reports to action logs)\n";
10552     SetVersion ($DBversion);
10553 }
10554
10555 $DBversion = "3.21.00.006";
10556 if ( CheckVersion($DBversion) ) {
10557     # Remove the borrow permission flag (bit 7)
10558     $dbh->do(q|
10559         UPDATE borrowers
10560         SET flags = flags - ( flags & (1<<7) )
10561         WHERE flags IS NOT NULL
10562             AND flags > 0
10563     |);
10564     $dbh->do(q|
10565         DELETE FROM userflags WHERE bit=7;
10566     |);
10567     print "Upgrade to $DBversion done (Bug 7976: Remove the 'borrow' permission)\n";
10568     SetVersion($DBversion);
10569 }
10570
10571 $DBversion = "3.21.00.007";
10572 if ( CheckVersion($DBversion) ) {
10573     unless ( index_exists( 'aqbasket', 'authorisedby' ) ) {
10574         $dbh->do(q|
10575             ALTER TABLE aqbasket
10576                 ADD KEY authorisedby (authorisedby)
10577         |);
10578     }
10579     unless ( index_exists( 'aqbooksellers', 'name' ) ) {
10580         $dbh->do(q|
10581             ALTER TABLE aqbooksellers
10582                 ADD KEY name (name(255))
10583         |);
10584     }
10585     unless ( index_exists( 'aqbudgets', 'budget_parent_id' ) ) {
10586         $dbh->do(q|
10587             ALTER TABLE aqbudgets
10588                 ADD KEY budget_parent_id (budget_parent_id)|);
10589         }
10590     unless ( index_exists( 'aqbudgets', 'budget_code' ) ) {
10591         $dbh->do(q|
10592             ALTER TABLE aqbudgets
10593                 ADD KEY budget_code (budget_code)|);
10594     }
10595     unless ( index_exists( 'aqbudgets', 'budget_branchcode' ) ) {
10596         $dbh->do(q|
10597             ALTER TABLE aqbudgets
10598                 ADD KEY budget_branchcode (budget_branchcode)|);
10599     }
10600     unless ( index_exists( 'aqbudgets', 'budget_period_id' ) ) {
10601         $dbh->do(q|
10602             ALTER TABLE aqbudgets
10603                 ADD KEY budget_period_id (budget_period_id)|);
10604     }
10605     unless ( index_exists( 'aqbudgets', 'budget_owner_id' ) ) {
10606         $dbh->do(q|
10607             ALTER TABLE aqbudgets
10608                 ADD KEY budget_owner_id (budget_owner_id)|);
10609     }
10610     unless ( index_exists( 'aqbudgets_planning', 'budget_period_id' ) ) {
10611         $dbh->do(q|
10612             ALTER TABLE aqbudgets_planning
10613                 ADD KEY budget_period_id (budget_period_id)|);
10614     }
10615     unless ( index_exists( 'aqorders', 'parent_ordernumber' ) ) {
10616         $dbh->do(q|
10617             ALTER TABLE aqorders
10618                 ADD KEY parent_ordernumber (parent_ordernumber)|);
10619     }
10620     unless ( index_exists( 'aqorders', 'orderstatus' ) ) {
10621         $dbh->do(q|
10622             ALTER TABLE aqorders
10623                 ADD KEY orderstatus (orderstatus)|);
10624     }
10625     print "Upgrade to $DBversion done (Bug 14053: Acquisition db tables are missing indexes)\n";
10626     SetVersion ($DBversion);
10627 }
10628
10629 $DBversion = "3.21.00.008";
10630 if ( CheckVersion($DBversion) ) {
10631     $dbh->do(q{
10632         DELETE IGNORE FROM systempreferences
10633         WHERE variable = 'HomeOrHoldingBranchReturn';
10634     });
10635     print "Upgrade to $DBversion done (Bug 7981: Transfer message on return. HomeOrHoldingBranchReturn syspref removed in favour of circulation rules.)\n";
10636     SetVersion($DBversion);
10637 }
10638
10639 $DBversion = "3.21.00.009";
10640 if ( CheckVersion($DBversion) ) {
10641
10642     sanitize_zero_date('aqorders', 'datecancellationprinted');
10643
10644     $dbh->do(q|
10645         UPDATE aqorders SET orderstatus='cancelled'
10646         WHERE (datecancellationprinted IS NOT NULL)
10647     |);
10648
10649     print "Upgrade to $DBversion done (Bug 13993: Correct orderstatus for transferred orders)\n";
10650     SetVersion($DBversion);
10651 }
10652
10653 $DBversion = "3.21.00.010";
10654 if ( CheckVersion($DBversion) ) {
10655     $dbh->do(q|
10656         ALTER TABLE message_queue
10657             DROP message_id
10658     |);
10659     $dbh->do(q|
10660         ALTER TABLE message_queue
10661             ADD message_id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10662     |);
10663     print "Upgrade to $DBversion done (Bug 7793: redefine the field message_id as PRIMARY KEY of message_queue)\n";
10664     SetVersion ($DBversion);
10665 }
10666
10667 $DBversion = "3.21.00.011";
10668 if ( CheckVersion($DBversion) ) {
10669     $dbh->do(q{
10670         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10671         VALUES ('OpacLangSelectorMode','footer','top|both|footer','Select the location to display the language selector','Choice')
10672     });
10673     print "Upgrade to $DBversion done (Bug 14252: Make the OPAC language switcher available in the masthead navbar, footer, or both)\n";
10674     SetVersion ($DBversion);
10675 }
10676
10677 $DBversion = "3.21.00.012";
10678 if ( CheckVersion($DBversion) ) {
10679     $dbh->do(q|
10680         INSERT INTO letter (module, code, name, title, content, message_transport_type)
10681         VALUES
10682         ('suggestions','TO_PROCESS','Notify fund owner', 'A suggestion is ready to be processed','Dear <<borrowers.firstname>> <<borrowers.surname>>,\n\nA new suggestion is ready to be processed: <<suggestions.title>> by <<suggestions.autho    r>>.\n\nThank you,\n\n<<branches.branchname>>', 'email')
10683     |);
10684     print "Upgrade to $DBversion done (Bug 13014: Add the TO_PROCESS letter code)\n";
10685     SetVersion($DBversion);
10686 }
10687
10688 $DBversion = "3.21.00.013";
10689 if ( CheckVersion($DBversion) ) {
10690     my $msg;
10691     if ( C4::Context->preference('OPACPrivacy') ) {
10692         if ( my $anonymous_patron = C4::Context->preference('AnonymousPatron') ) {
10693             my $anonymous_patron_exists = $dbh->selectcol_arrayref(q|
10694                 SELECT COUNT(*)
10695                 FROM borrowers
10696                 WHERE borrowernumber=?
10697             |, {}, $anonymous_patron);
10698             unless ( $anonymous_patron_exists->[0] ) {
10699                 $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not linked to an existing patron";
10700             }
10701         }
10702         else {
10703             $msg = "Configuration WARNING: OPACPrivacy is set but AnonymousPatron is not";
10704         }
10705     }
10706     else {
10707         my $patrons_have_required_anonymity = $dbh->selectcol_arrayref(q|
10708             SELECT COUNT(*)
10709             FROM borrowers
10710             WHERE privacy = 2
10711         |, {} );
10712         if ( $patrons_have_required_anonymity->[0] ) {
10713             $msg = "Configuration WARNING: OPACPrivacy is not set but $patrons_have_required_anonymity->[0] patrons have required anonymity (perhaps in a previous configuration). You should fix that asap.";
10714         }
10715     }
10716
10717     $msg //= "Privacy is correctly set";
10718     print "Upgrade to $DBversion done (Bug 9942: $msg)\n";
10719     SetVersion ($DBversion);
10720 }
10721
10722 $DBversion = "3.21.00.014";
10723 if ( CheckVersion($DBversion) ) {
10724     $dbh->do(q{
10725         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10726         VALUES ('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent) or might be deleted (transient)','transient|persistent','Choice')
10727     });
10728
10729     if ( foreign_key_exists( 'oai_sets_biblios', 'oai_sets_biblios_ibfk_1' ) ) {
10730         $dbh->do(q|
10731             ALTER TABLE oai_sets_biblios DROP FOREIGN KEY oai_sets_biblios_ibfk_1
10732         |);
10733     }
10734     print "Upgrade to $DBversion done (Bug 3206: OAI repository deleted record support)\n";
10735     SetVersion ($DBversion);
10736 }
10737
10738 $DBversion = "3.21.00.015";
10739 if ( CheckVersion($DBversion) ) {
10740     $dbh->do(q{
10741         UPDATE systempreferences SET value='0' WHERE variable='CalendarFirstDayOfWeek' AND value='Sunday';
10742     });
10743     $dbh->do(q{
10744         UPDATE systempreferences SET value='1' WHERE variable='CalendarFirstDayOfWeek' AND value='Monday';
10745     });
10746     $dbh->do(q{
10747         UPDATE systempreferences SET options='0|1|2|3|4|5|6' WHERE variable='CalendarFirstDayOfWeek';
10748     });
10749
10750     print "Upgrade to $DBversion done (Bug 12137: Extend functionality of CalendarFirstDayOfWeek to be any day)\n";
10751     SetVersion($DBversion);
10752 }
10753
10754 $DBversion = "3.21.00.016";
10755 if ( CheckVersion($DBversion) ) {
10756     my $rs = $schema->resultset('Systempreference');
10757     $rs->find_or_create(
10758         {
10759             variable => 'DumpTemplateVarsIntranet',
10760             value    => 0,
10761             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the staff intranet.',
10762             type => 'YesNo',
10763         }
10764     );
10765     $rs->find_or_create(
10766         {
10767             variable => 'DumpTemplateVarsOpac',
10768             value    => 0,
10769             explanation => 'If enabled, dump all Template Toolkit variable to a comment in the html source for the opac.',
10770             type => 'YesNo',
10771         }
10772     );
10773     print "Upgrade to $DBversion done (Bug 13948: Add ability to dump template toolkit variables to html comment)\n";
10774     SetVersion($DBversion);
10775 }
10776
10777 $DBversion = "3.21.00.017";
10778 if ( CheckVersion($DBversion) ) {
10779     $dbh->do("
10780         CREATE TABLE uploaded_files (
10781             id int(11) NOT NULL AUTO_INCREMENT,
10782             hashvalue CHAR(40) NOT NULL,
10783             filename TEXT NOT NULL,
10784             dir TEXT NOT NULL,
10785             filesize int(11),
10786             dtcreated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10787             categorycode tinytext,
10788             owner int(11),
10789             PRIMARY KEY (id)
10790         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
10791     ");
10792
10793     print "Upgrade to $DBversion done (Bug 6874: New cataloging plugin upload.pl)\n";
10794     print "This plugin comes with a new config variable (upload_path) and a new table (uploaded_files)\n";
10795     print "To use it, set 'upload_path' config variable and 'OPACBaseURL' system preference and link this plugin to a subfield (856\$u for instance)\n";
10796     SetVersion($DBversion);
10797 }
10798
10799 $DBversion = "3.21.00.018";
10800 if ( CheckVersion($DBversion) ) {
10801     $dbh->do(q{
10802         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10803         VALUES
10804             ('RestrictedPageLocalIPs','',NULL,'Beginning of IP addresses considered as local (comma separated ex: \"127.0.0,127.0.2\")','Free'),
10805             ('RestrictedPageContent','',NULL,'HTML content of the restricted page','TextArea'),
10806             ('RestrictedPageTitle','',NULL,'Title of the restricted page (breadcrumb and header)','Free')
10807     });
10808     print "Upgrade to $DBversion done (Bug 13485: Add a page to display links to restricted sites)\n";
10809     SetVersion ($DBversion);
10810 }
10811
10812 $DBversion = "3.21.00.019";
10813 if ( CheckVersion($DBversion) ) {
10814     if ( column_exists( 'reserves', 'constrainttype' ) ) {
10815         $dbh->do(q{
10816             ALTER TABLE reserves DROP constrainttype
10817         });
10818         $dbh->do(q{
10819             ALTER TABLE old_reserves DROP constrainttype
10820         });
10821     }
10822     $dbh->do(q{
10823         DROP TABLE IF EXISTS reserveconstraints
10824     });
10825     print "Upgrade to $DBversion done (Bug 9809: Get rid of reserveconstraints)\n";
10826     SetVersion ($DBversion);
10827 }
10828
10829 $DBversion = "3.21.00.020";
10830 if ( CheckVersion($DBversion) ) {
10831     $dbh->do(q{
10832         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
10833         VALUES ('FeeOnChangePatronCategory','1','','If set, when a patron changes to a category with enrolment fee, a fee is charged','YesNo')
10834     });
10835     print "Upgrade to $DBversion done (Bug 13697: Option to don't charge a fee, if the patron changes to a category with enrolment fee)\n";
10836     SetVersion($DBversion);
10837 }
10838
10839 $DBversion = "3.21.00.021";
10840 if ( CheckVersion($DBversion) ) {
10841     $dbh->do(q{
10842         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
10843         VALUES ('UseWYSIWYGinSystemPreferences','0','','Show WYSIWYG editor when editing certain HTML system preferences.','YesNo')
10844     });
10845     print "Upgrade to $DBversion done (Bug 11584: Add wysiwyg editor to system preferences dealing with HTML)\n";
10846     SetVersion($DBversion);
10847 }
10848
10849 $DBversion = "3.21.00.022";
10850 if ( CheckVersion($DBversion) ) {
10851     $dbh->do(q{
10852         DELETE cr.*
10853         FROM course_reserves AS cr
10854         LEFT JOIN course_items USING(ci_id)
10855         WHERE course_items.ci_id IS NULL
10856     });
10857
10858     my ($print_error) = $dbh->{PrintError};
10859     $dbh->{RaiseError} = 0;
10860     $dbh->{PrintError} = 0;
10861     if ( foreign_key_exists('course_reserves', 'course_reserves_ibfk_2') ) {
10862         $dbh->do(q{ALTER TABLE course_reserves DROP FOREIGN KEY course_reserves_ibfk_2});
10863         $dbh->do(q{ALTER TABLE course_reserves DROP INDEX course_reserves_ibfk_2});
10864     }
10865     $dbh->{PrintError} = $print_error;
10866
10867     $dbh->do(q{
10868         ALTER TABLE course_reserves
10869             ADD CONSTRAINT course_reserves_ibfk_2
10870                 FOREIGN KEY (ci_id) REFERENCES course_items (ci_id)
10871                 ON DELETE CASCADE ON UPDATE CASCADE
10872     });
10873     print "Upgrade to $DBversion done (Bug 14205: Deleting an Item/Record does not remove link to course reserve)\n";
10874     SetVersion($DBversion);
10875 }
10876
10877 $DBversion = "3.21.00.023";
10878 if ( CheckVersion($DBversion) ) {
10879
10880     sanitize_zero_date('borrowers', 'debarred');
10881     sanitize_zero_date('borrowers', 'dateexpiry');
10882     sanitize_zero_date('borrowers', 'dateofbirth');
10883     sanitize_zero_date('borrowers', 'dateenrolled');
10884
10885     print "Upgrade to $DBversion done (Bug 14717: Prevent 0000-00-00 dates in patron data)\n";
10886     SetVersion($DBversion);
10887 }
10888
10889 $DBversion = "3.21.00.024";
10890 if ( CheckVersion($DBversion) ) {
10891     $dbh->do(q{
10892         ALTER TABLE marc_modification_template_actions
10893         MODIFY COLUMN action
10894             ENUM('delete_field','update_field','move_field','copy_field','copy_and_replace_field')
10895             NOT NULL
10896     });
10897     print "Upgrade to $DBversion done (Bug 14098: Regression in Marc Modification Templates)\n";
10898     SetVersion($DBversion);
10899 }
10900
10901 $DBversion = "3.21.00.025";
10902 if ( CheckVersion($DBversion) ) {
10903     $dbh->do(q{
10904         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10905         VALUES ('RisExportAdditionalFields',  '', NULL ,  'Define additional RIS tags to export from MARC records in YAML format as an associative array with either a marc tag/subfield combination as the value, or a list of tag/subfield combinations.',  'textarea')
10906     });
10907     $dbh->do(q{
10908         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
10909         VALUES ('BibtexExportAdditionalFields',  '', NULL ,  'Define additional BibTex tags to export from MARC records in YAML format as an associative array with either a marc tag/subfield combination as the value, or a list of tag/subfield combinations.',  'textarea')
10910     });
10911     print "Upgrade to $DBversion done (Bug 12357: Enhancements to RIS and BibTeX exporting)\n";
10912     SetVersion($DBversion);
10913 }
10914
10915 $DBversion = "3.21.00.026";
10916 if ( CheckVersion($DBversion) ) {
10917     $dbh->do(q{
10918         UPDATE matchpoints
10919         SET search_index='issn'
10920         WHERE matcher_id IN (SELECT matcher_id FROM marc_matchers WHERE code = 'ISSN')
10921     });
10922     print "Upgrade to $DBversion done (Bug 14472: Wrong ISSN search index in record matching rules)\n";
10923     SetVersion($DBversion);
10924 }
10925
10926 $DBversion = "3.21.00.027";
10927 if ( CheckVersion($DBversion) ) {
10928     $dbh->do(q|
10929         INSERT IGNORE INTO permissions (module_bit, code, description)
10930         VALUES (1, 'self_checkout', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID')
10931     |);
10932
10933     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
10934
10935     $dbh->do(q|
10936         UPDATE borrowers
10937         SET flags=0
10938         WHERE userid=?
10939     |, undef, $AutoSelfCheckID);
10940
10941     $dbh->do(q|
10942         DELETE FROM user_permissions
10943         WHERE borrowernumber=(SELECT borrowernumber FROM borrowers WHERE userid=?)
10944     |, undef, $AutoSelfCheckID);
10945
10946     $dbh->do(q|
10947         INSERT INTO user_permissions(borrowernumber, module_bit, code)
10948         SELECT borrowernumber, 1, 'self_checkout' FROM borrowers WHERE userid=?
10949     |, undef, $AutoSelfCheckID);
10950     print "Upgrade to $DBversion done (Bug 14298: AutoSelfCheckID user should only be able to access SCO)\n";
10951     SetVersion($DBversion);
10952 }
10953
10954 $DBversion = "3.21.00.028";
10955 if ( CheckVersion($DBversion) ) {
10956     unless ( column_exists('uploaded_files', 'public') ) {
10957         $dbh->do(q{
10958             ALTER TABLE uploaded_files
10959                 ADD COLUMN public tinyint,
10960                 ADD COLUMN permanent tinyint
10961         });
10962         $dbh->do(q{
10963             UPDATE uploaded_files SET public=1, permanent=1
10964         });
10965         $dbh->do(q{
10966             ALTER TABLE uploaded_files
10967                 CHANGE COLUMN categorycode uploadcategorycode tinytext
10968         });
10969     }
10970     print "Upgrade to $DBversion done (Bug 14321: Merge UploadedFile and UploadedFiles into Koha::Upload)\n";
10971     SetVersion($DBversion);
10972 }
10973
10974 $DBversion = "3.21.00.029";
10975 if ( CheckVersion($DBversion) ) {
10976     unless ( column_exists('discharges', 'discharge_id') ) {
10977         $dbh->do(q{
10978             ALTER TABLE discharges
10979                 ADD COLUMN discharge_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
10980         });
10981     }
10982     print "Upgrade to $DBversion done (Bug 14368: Add discharges history)\n";
10983     SetVersion($DBversion);
10984 }
10985
10986 $DBversion = "3.21.00.030";
10987 if ( CheckVersion($DBversion) ) {
10988     $dbh->do(q{
10989         UPDATE marc_subfield_structure
10990         SET value_builder='marc21_leader.pl'
10991         WHERE value_builder='marc21_leader_book.pl'
10992     });
10993     $dbh->do(q{
10994         UPDATE marc_subfield_structure
10995         SET value_builder='marc21_leader.pl'
10996         WHERE value_builder='marc21_leader_computerfile.pl'
10997     });
10998     $dbh->do(q{
10999         UPDATE marc_subfield_structure
11000         SET value_builder='marc21_leader.pl'
11001         WHERE value_builder='marc21_leader_video.pl'
11002     });
11003     print "Upgrade to $DBversion done (Bug 14201: Remove unused code or template from some MARC21 leader plugins )\n";
11004     SetVersion($DBversion);
11005 }
11006
11007 $DBversion = "3.21.00.031";
11008 if ( CheckVersion($DBversion) ) {
11009     $dbh->do(q{
11010         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11011         VALUES
11012             ('SMSSendPassword', '', '', 'Password used to send SMS messages', 'free'),
11013             ('SMSSendUsername', '', '', 'Username/Login used to send SMS messages', 'free')
11014     });
11015     print "Upgrade to $DBversion done (Bug 14820: SMSSendUsername and SMSSendPassword are not listed in the system preferences)\n";
11016     SetVersion($DBversion);
11017 }
11018
11019 $DBversion = "3.21.00.032";
11020 if ( CheckVersion($DBversion) ) {
11021     $dbh->do(q{
11022         CREATE TABLE additional_fields (
11023             id int(11) NOT NULL AUTO_INCREMENT,
11024             tablename varchar(255) NOT NULL DEFAULT '',
11025             name varchar(255) NOT NULL DEFAULT '',
11026             authorised_value_category varchar(16) NOT NULL DEFAULT '',
11027             marcfield varchar(16) NOT NULL DEFAULT '',
11028             searchable tinyint(1) NOT NULL DEFAULT '0',
11029             PRIMARY KEY (id),
11030             UNIQUE KEY fields_uniq (tablename,name)
11031         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11032     });
11033     $dbh->do(q{
11034         CREATE TABLE additional_field_values (
11035             id int(11) NOT NULL AUTO_INCREMENT,
11036             field_id int(11) NOT NULL,
11037             record_id int(11) NOT NULL,
11038             value varchar(255) NOT NULL DEFAULT '',
11039             PRIMARY KEY (id),
11040             UNIQUE KEY field_record (field_id,record_id),
11041             CONSTRAINT afv_fk FOREIGN KEY (field_id) REFERENCES additional_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
11042         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11043     });
11044     print "Upgrade to $DBversion done (Bug 10855: Additional fields for subscriptions)\n";
11045     SetVersion($DBversion);
11046 }
11047
11048 $DBversion = "3.21.00.033";
11049 if ( CheckVersion($DBversion) ) {
11050
11051     my $done = 0;
11052     my $count_ethnicity = $dbh->selectrow_arrayref(q|
11053         SELECT COUNT(*) FROM ethnicity
11054     |);
11055     my $count_borrower_modifications = $dbh->selectrow_arrayref(q|
11056         SELECT COUNT(*)
11057         FROM borrower_modifications
11058         WHERE ethnicity IS NOT NULL
11059             OR ethnotes IS NOT NULL
11060     |);
11061     my $count_borrowers = $dbh->selectrow_arrayref(q|
11062         SELECT COUNT(*)
11063         FROM borrowers
11064         WHERE ethnicity IS NOT NULL
11065             OR ethnotes IS NOT NULL
11066     |);
11067     # We don't care about the ethnicity of the deleted borrowers, right?
11068     if ( $count_ethnicity->[0] == 0
11069             and $count_borrower_modifications->[0] == 0
11070             and $count_borrowers->[0] == 0
11071     ) {
11072         $dbh->do(q|
11073             DROP TABLE ethnicity
11074         |);
11075         $dbh->do(q|
11076             ALTER TABLE borrower_modifications
11077             DROP COLUMN ethnicity,
11078             DROP COLUMN ethnotes
11079         |);
11080         $dbh->do(q|
11081             ALTER TABLE borrowers
11082             DROP COLUMN ethnicity,
11083             DROP COLUMN ethnotes
11084         |);
11085         $dbh->do(q|
11086             ALTER TABLE deletedborrowers
11087             DROP COLUMN ethnicity,
11088             DROP COLUMN ethnotes
11089         |);
11090         $done = 1;
11091     }
11092     if ( $done ) {
11093         print "Upgrade to $DBversion done (Bug 10020: Drop table ethnicity and columns ethnicity and ethnotes)\n";
11094     }
11095     else {
11096         print "Upgrade to $DBversion done (Bug 10020: This database contains data related to 'ethnicity'. No change will be done on the DB structure but note that the Koha codebase does not use it)\n";
11097     }
11098
11099     SetVersion ($DBversion);
11100 }
11101
11102 $DBversion = "3.21.00.034";
11103 if ( CheckVersion($DBversion) ) {
11104     $dbh->do(q{
11105         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11106         VALUES('MembershipExpiryDaysNotice',NULL,'Send an account expiration notice that a patron''s card is about to expire after',NULL,'Integer')
11107     });
11108     $dbh->do(q{
11109         INSERT IGNORE INTO letter (module, code, branchcode, name, title, content, message_transport_type)
11110         VALUES('members','MEMBERSHIP_EXPIRY','','Account expiration','Account expiration','Dear <<borrowers.title>> <<borrowers.firstname>> <<borrowers.surname>>,\r\n\r\nYour library card will expire soon, on:\r\n\r\n<<borrowers.dateexpiry>>\r\n\r\nThank you,\r\n\r\nLibrarian\r\n\r\n<<branches.branchname>>', 'email')
11111     });
11112     print "Upgrade to $DBversion done (Bug 6810: Send membership expiry reminder notices)\n";
11113     SetVersion($DBversion);
11114 }
11115
11116 $DBversion = "3.21.00.035";
11117 if ( CheckVersion($DBversion) ) {
11118     $dbh->do(q|
11119         ALTER TABLE branch_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11120     |);
11121     $dbh->do(q|
11122         UPDATE branch_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11123     |);
11124     $dbh->do(q|
11125         ALTER TABLE default_borrower_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11126     |);
11127     $dbh->do(q|
11128         UPDATE default_borrower_circ_rules SET maxonsiteissueqty = maxissueqty;
11129     |);
11130     $dbh->do(q|
11131         ALTER TABLE default_branch_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11132     |);
11133     $dbh->do(q|
11134         UPDATE default_branch_circ_rules SET maxonsiteissueqty = maxissueqty;
11135     |);
11136     $dbh->do(q|
11137         ALTER TABLE default_circ_rules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11138     |);
11139     $dbh->do(q|
11140         UPDATE default_circ_rules SET maxonsiteissueqty = maxissueqty;
11141     |);
11142     $dbh->do(q|
11143         ALTER TABLE issuingrules ADD COLUMN maxonsiteissueqty int(4) DEFAULT NULL AFTER maxissueqty;
11144     |);
11145     $dbh->do(q|
11146         UPDATE issuingrules SET maxonsiteissueqty = maxissueqty;
11147     |);
11148     $dbh->do(q|
11149         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11150         VALUES ('ConsiderOnSiteCheckoutsAsNormalCheckouts','1',NULL,'Consider on-site checkouts as normal checkouts','YesNo');
11151     |);
11152
11153     print "Upgrade to $DBversion done (Bug 14045: Add DB fields maxonsiteissueqty and pref ConsiderOnSiteCheckoutsAsNormalCheckouts)\n";
11154     SetVersion ($DBversion);
11155 }
11156
11157 $DBversion = "3.21.00.036";
11158 if ( CheckVersion($DBversion) ) {
11159    $dbh->do(q{
11160         ALTER TABLE authorised_values_branches
11161         DROP FOREIGN KEY authorised_values_branches_ibfk_1,
11162         DROP FOREIGN KEY authorised_values_branches_ibfk_2
11163     });
11164     $dbh->do(q{
11165         ALTER TABLE authorised_values_branches
11166         MODIFY av_id INT( 11 ) NOT NULL,
11167         MODIFY branchcode VARCHAR( 10 ) NOT NULL,
11168         ADD FOREIGN KEY (`av_id`) REFERENCES `authorised_values` (`id`) ON DELETE CASCADE,
11169         ADD FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE
11170    });
11171    print "Upgrade to $DBversion done (Bug 10363: There is no package for authorised values)\n";
11172    SetVersion($DBversion);
11173 }
11174
11175 $DBversion = "3.21.00.037";
11176 if ( CheckVersion($DBversion) ) {
11177    $dbh->do(q{
11178        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11179        VALUES ('OverduesBlockRenewing','allow','If any of a patron checked out documents is late, should renewal be allowed, blocked only on overdue items or blocked on whatever checked out document','allow|blockitem|block','Choice')
11180    });
11181    $dbh->do(q{
11182        INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11183        VALUES ('RestrictionBlockRenewing','0','If patron is restricted, should renewal be allowed or blocked',NULL,'YesNo')
11184     });
11185    print "Upgrade to $DBversion done (Bug 8236: Prevent renewing if overdue or restriction)\n";
11186    SetVersion($DBversion);
11187 }
11188
11189 $DBversion = "3.21.00.038";
11190 if ( CheckVersion($DBversion) ) {
11191     $dbh->do(q|
11192         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11193         VALUES ('BatchCheckouts','0','','Enable or disable batch checkouts','YesNo')
11194     |);
11195     $dbh->do(q|
11196         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11197         VALUES ('BatchCheckoutsValidCategories','',NULL,'Patron categories allowed to checkout in a batch','Free')
11198     |);
11199     print "Upgrade to $DBversion done (Bug 11759: Add the batch checkout feature)\n";
11200     SetVersion($DBversion);
11201 }
11202
11203 $DBversion = "3.21.00.039";
11204 if ( CheckVersion($DBversion) ) {
11205     $dbh->do(q|
11206         ALTER TABLE creator_layouts ADD COLUMN oblique_title INT(1) NULL DEFAULT 1 AFTER guidebox
11207     |);
11208     print "Upgrade to $DBversion done (Bug 12194: Add column oblique_title to layouts)\n";
11209     SetVersion($DBversion);
11210 }
11211
11212 $DBversion = "3.21.00.040";
11213 if ( CheckVersion($DBversion) ) {
11214     $dbh->do(q{
11215         ALTER TABLE itemtypes
11216             ADD hideinopac TINYINT(1) NOT NULL DEFAULT 0
11217               AFTER sip_media_type,
11218             ADD searchcategory VARCHAR(80) DEFAULT NULL
11219               AFTER hideinopac;
11220     });
11221     print "Upgrade to $DBversion done (Bug 10937: Option to hide and group itemtypes from advanced search)\n";
11222     SetVersion($DBversion);
11223 }
11224
11225 $DBversion = "3.21.00.041";
11226 if ( CheckVersion($DBversion) ) {
11227     $dbh->do(q|
11228         ALTER TABLE issuingrules
11229             ADD chargeperiod_charge_at BOOLEAN NOT NULL DEFAULT  '0' AFTER chargeperiod
11230     |);
11231     print "Upgrade to $DBversion done (Bug 13590: Add ability to charge fines at start of charge period)\n";
11232     SetVersion($DBversion);
11233 }
11234
11235 $DBversion = "3.21.00.042";
11236 if ( CheckVersion($DBversion) ) {
11237     $dbh->do(q|
11238         ALTER TABLE items_search_fields
11239             MODIFY COLUMN authorised_values_category VARCHAR(32) DEFAULT NULL
11240     |);
11241     print "Upgrade to $DBversion done (Bug 15069: items_search_fields.authorised_values_category is still a varchar(32))\n";
11242     SetVersion($DBversion);
11243 }
11244
11245 $DBversion = "3.21.00.043";
11246 if ( CheckVersion($DBversion) ) {
11247     $dbh->do(q|
11248         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11249         VALUES ('EnableAdvancedCatalogingEditor','0','','Enable the Rancor advanced cataloging editor','YesNo')
11250     |);
11251     print "Upgrade to $DBversion done (Bug 11559: Professional cataloger's interface)\n";
11252     SetVersion($DBversion);
11253 }
11254
11255 $DBversion = "3.21.00.044";
11256 if ( CheckVersion($DBversion) ) {
11257     $dbh->do(q|
11258         CREATE TABLE localization (
11259             localization_id int(11) NOT NULL AUTO_INCREMENT,
11260             entity varchar(16) COLLATE utf8_unicode_ci NOT NULL,
11261             code varchar(64) COLLATE utf8_unicode_ci NOT NULL,
11262             lang varchar(25) COLLATE utf8_unicode_ci NOT NULL,
11263             translation text COLLATE utf8_unicode_ci,
11264             PRIMARY KEY (localization_id),
11265             UNIQUE KEY entity_code_lang (entity,code,lang)
11266         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11267     |);
11268     print "Upgrade to $DBversion done (Bug 14100: Generic solution for language overlay)\n";
11269     SetVersion($DBversion);
11270 }
11271
11272 $DBversion = "3.21.00.045";
11273 if ( CheckVersion($DBversion) ) {
11274     $dbh->do(q|
11275         ALTER TABLE opac_news
11276             ADD borrowernumber int(11) default NULL
11277                 AFTER number
11278     |);
11279     $dbh->do(q|
11280         ALTER TABLE opac_news
11281             ADD CONSTRAINT borrowernumber_fk
11282                 FOREIGN KEY (borrowernumber)
11283                 REFERENCES borrowers (borrowernumber)
11284                 ON DELETE SET NULL ON UPDATE CASCADE
11285     |);
11286     print "Upgrade to $DBversion done (Bug 14246: (newsauthor) Add borrowernumber to koha_news)\n";
11287     SetVersion($DBversion);
11288 }
11289
11290 $DBversion = "3.21.00.046";
11291 if ( CheckVersion($DBversion) ) {
11292     $dbh->do(q{
11293         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11294         VALUES ('NewsAuthorDisplay','none','none|opac|staff|both','Display the author name for news items.','Choice')
11295     });
11296     print "Upgrade to $DBversion done (Bug 14247: (newsauthor) System preference for news author display)\n";
11297     SetVersion($DBversion);
11298 }
11299
11300 $DBversion = "3.21.00.047";
11301 if(CheckVersion($DBversion)) {
11302     $dbh->do(q{
11303         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11304         VALUES ('IndependentBranchesPatronModifications','0','Show only modification request for the logged in branch','','YesNo')
11305     });
11306     print "Upgrade to $DBversion done (Bug 10904: Limit patron update request management by branch)\n";
11307     SetVersion($DBversion);
11308 }
11309
11310 $DBversion = '3.21.00.048';
11311 if ( CheckVersion($DBversion) ) {
11312     my $create_table_issues = @{ $dbh->selectall_arrayref(q|SHOW CREATE TABLE issues|) }[0]->[1];
11313     if ($create_table_issues !~ m|UNIQUE KEY.*itemnumber| ) {
11314         $dbh->do(q|ALTER TABLE issues ADD CONSTRAINT UNIQUE KEY (itemnumber)|);
11315     }
11316     print "Upgrade to $DBversion done (Bug 14978: Make sure issues.itemnumber is a unique key)\n";
11317     SetVersion($DBversion);
11318 }
11319
11320 $DBversion = "3.21.00.049";
11321 if ( CheckVersion($DBversion) ) {
11322     $dbh->do(q{UPDATE systempreferences SET variable = 'AudioAlerts' WHERE variable = 'soundon'});
11323
11324     $dbh->do(q{
11325         CREATE TABLE audio_alerts (
11326             id int(11) NOT NULL AUTO_INCREMENT,
11327             precedence smallint(5) unsigned NOT NULL,
11328             selector varchar(255) NOT NULL,
11329             sound varchar(255) NOT NULL,
11330             PRIMARY KEY (id),
11331             KEY precedence (precedence)
11332         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11333     });
11334
11335     $dbh->do(q{
11336         INSERT IGNORE INTO audio_alerts VALUES
11337         (1, 1, '.audio-alert-action', 'opening.ogg'),
11338         (2, 2, '.audio-alert-warning', 'critical.ogg'),
11339         (3, 3, '.audio-alert-success', 'beep.ogg');
11340     });
11341
11342     print "Upgrade to $DBversion done (Bug 11431: Add additional sound options for warnings)\n";
11343     SetVersion($DBversion);
11344 }
11345
11346 $DBversion = "3.21.00.050";
11347 if(CheckVersion($DBversion)) {
11348     $dbh->do(q{
11349         INSERT INTO letter ( module, code, branchcode, name, is_html, title, content, message_transport_type )
11350         VALUES ( 'circulation', 'OVERDUES_SLIP', '', 'Overdues Slip', '0', 'OVERDUES_SLIP', 'The following item(s) is/are currently overdue:
11351
11352 <item>"<<biblio.title>>" by <<biblio.author>>, <<items.itemcallnumber>>, Barcode: <<items.barcode>> Fine: <<items.fine>></item>
11353 ', 'print' )
11354     });
11355     print "Upgrade to $DBversion done (Bug 12933: Add ability to print overdue slip from staff intranet)\n";
11356     SetVersion($DBversion);
11357 }
11358
11359 $DBversion = "3.21.00.051";
11360 if ( CheckVersion($DBversion) ) {
11361     $dbh->do(q{
11362         ALTER TABLE virtualshelves
11363             CHANGE COLUMN sortfield sortfield VARCHAR(16) DEFAULT 'title'
11364     });
11365     $dbh->do(q{
11366         UPDATE virtualshelves
11367         SET sortfield='title'
11368             WHERE sortfield IS NULL;
11369     });
11370     print "Upgrade to $DBversion done (Bug 14544: Move the list related code to Koha::Virtualshelves)\n";
11371     SetVersion($DBversion);
11372 }
11373
11374 $DBversion = "3.21.00.052";
11375 if ( CheckVersion($DBversion) ) {
11376     $dbh->do(q{
11377         ALTER TABLE serial
11378             ADD COLUMN publisheddatetext VARCHAR(100) DEFAULT NULL AFTER publisheddate
11379     });
11380     print "Upgrade to $DBversion done (Bug 8296: Add descriptive (text) published date field for serials)\n";
11381     SetVersion($DBversion);
11382 }
11383
11384 $DBversion = "3.21.00.053";
11385 if ( CheckVersion($DBversion) ) {
11386     my $query = q{ SELECT * FROM itemtypes ORDER BY description };
11387     my $sth   = C4::Context->dbh->prepare($query);
11388     $sth->execute;
11389     my $suggestion_formats = $sth->fetchall_arrayref( {} );
11390
11391     foreach my $format (@$suggestion_formats) {
11392         $dbh->do(
11393             q|
11394             INSERT IGNORE INTO authorised_values (category, authorised_value, lib, lib_opac, imageurl)
11395             VALUES (?, ?, ?, ?, ?)
11396         |, {},
11397             'SUGGEST_FORMAT', $format->{itemtype}, $format->{description}, $format->{description},
11398             $format->{imageurl}
11399         );
11400     }
11401     print "Upgrade to $DBversion done (Bug 9468: create new SUGGEST_FORMAT authorised_value list)\n";
11402     SetVersion($DBversion);
11403 }
11404
11405 $DBversion = "3.21.00.054";
11406 if(CheckVersion($DBversion)) {
11407     $dbh->do(q{
11408         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11409         VALUES('MergeReportFields','','Displayed fields for deleted MARC records after merge',NULL,'Free')
11410     });
11411     print "Upgrade to $DBversion done (Bug 8064: Merge several biblio records)\n";
11412     SetVersion($DBversion);
11413 }
11414
11415 $DBversion = "3.21.00.055";
11416 if ( CheckVersion($DBversion) ) {
11417     print "Upgrade to $DBversion done (Koha 3.22 beta)\n";
11418     SetVersion($DBversion);
11419 }
11420
11421 $DBversion = "3.21.00.056";
11422 if(CheckVersion($DBversion)) {
11423     $dbh->do(q{
11424         UPDATE systempreferences
11425         SET
11426             options='metric|us|iso|dmydot',
11427             explanation='Define global date format (us mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy-mm-dd, DMY separated by dots dd.mm.yyyy)'
11428         WHERE variable='dateformat'
11429     });
11430     print "Upgrade to $DBversion done (Bug 12072: New dateformat dd.mm.yyyy)\n";
11431     SetVersion($DBversion);
11432 }
11433
11434 $DBversion = "3.22.00.000";
11435 if ( CheckVersion($DBversion) ) {
11436     print "Upgrade to $DBversion done (Koha 3.22)\n";
11437     SetVersion($DBversion);
11438 }
11439
11440 $DBversion = "3.23.00.000";
11441 if ( CheckVersion($DBversion) ) {
11442     print "Upgrade to $DBversion done (The year of the monkey will be here soon.)\n";
11443     SetVersion ($DBversion);
11444 }
11445
11446 $DBversion = "3.23.00.001";
11447 if(CheckVersion($DBversion)) {
11448     $dbh->do(q{
11449         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11450         VALUES (
11451             'DefaultToLoggedInLibraryCircRules',  '0', NULL ,  'If enabled, circ rules editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11452         ), (
11453             'DefaultToLoggedInLibraryNoticesSlips',  '0', NULL ,  'If enabled,slips and notices editor will default to the logged in library''s rules, rather than the ''all libraries'' rules.',  'YesNo'
11454         )
11455     });
11456
11457     print "Upgrade to $DBversion done (Bug 11625 - Add pref DefaultToLoggedInLibraryCircRules and DefaultToLoggedInLibraryNoticesSlips)\n";
11458     SetVersion($DBversion);
11459 }
11460
11461 $DBversion = "3.23.00.002";
11462 if(CheckVersion($DBversion)) {
11463     $dbh->do(q{
11464         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
11465         VALUES ('DefaultToLoggedInLibraryOverdueTriggers',  '0', NULL,  'If enabled, overdue status triggers editor will default to the logged in library''s rules, rather than the ''default'' rules.',  'YesNo')
11466     });
11467
11468     print "Upgrade to $DBversion done (Bug 11747 - add pref DefaultToLoggedInLibraryOverdueTriggers)\n";
11469     SetVersion($DBversion);
11470 }
11471
11472 $DBversion = "3.23.00.003";
11473 if(CheckVersion($DBversion)) {
11474     $dbh->do(q{
11475         UPDATE letter SET name = "Hold Slip" WHERE name = "Reserve Slip"
11476     });
11477     $dbh->do(q{
11478         UPDATE letter SET title = "Hold Slip" WHERE title = "Reserve Slip";
11479     });
11480
11481     print "Upgrade to $DBversion done (Bug 8085 - Rename 'Reserve slip' to 'Hold slip')\n";
11482     SetVersion($DBversion);
11483 }
11484
11485 $DBversion = "3.23.00.004";
11486 if ( CheckVersion($DBversion) ) {
11487     $dbh->do(q{
11488         DROP TABLE IF EXISTS `stopwords`;
11489     });
11490     print "Upgrade to $DBversion done (Bug 9819 - stopwords related code should be removed)\n";
11491     SetVersion($DBversion);
11492 }
11493
11494 $DBversion = "3.23.00.005";
11495 if ( CheckVersion($DBversion) ) {
11496     $dbh->do(q{
11497         UPDATE permissions SET description = 'Manage circulation rules' WHERE description = 'manage circulation rules'
11498     });
11499     $dbh->do(q{
11500         UPDATE permissions SET description = 'Manage staged MARC records, including completing and reversing imports' WHERE description = 'Managed staged MARC records, including completing and reversing imports'
11501     });
11502     print "Upgrade to $DBversion done (Bug 11569 - Typo in userpermissions.sql)\n";
11503     SetVersion($DBversion);
11504 }
11505 $DBversion = "3.23.00.006";
11506 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
11507    $dbh->do("
11508        ALTER TABLE serial
11509         ADD serialseq_x VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq,
11510         ADD serialseq_y VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_x,
11511         ADD serialseq_z VARCHAR( 100 ) NULL DEFAULT NULL AFTER serialseq_y
11512    ");
11513
11514     my $sth = $dbh->prepare("SELECT * FROM subscription");
11515     $sth->execute();
11516
11517     my $sth2 = $dbh->prepare("SELECT * FROM subscription_numberpatterns WHERE id = ?");
11518
11519     my $sth3 = $dbh->prepare("UPDATE serial SET serialseq_x = ?, serialseq_y = ?, serialseq_z = ? WHERE serialid = ?");
11520
11521     foreach my $subscription ( $sth->fetchrow_hashref() ) {
11522         next if !defined($subscription);
11523         $sth2->execute( $subscription->{numberpattern} );
11524         my $number_pattern = $sth2->fetchrow_hashref();
11525
11526         my $numbering_method = $number_pattern->{numberingmethod};
11527         # Get all the data between the enumeration values, we need
11528         # to split each enumeration string based on these values.
11529         my @splits = split( /\{[XYZ]\}/, $numbering_method );
11530         # Get the order in which the X Y and Z values are used
11531         my %indexes;
11532         foreach my $i (qw(X Y Z)) {
11533             $indexes{$i} = index( $numbering_method, "{$i}" );
11534             delete $indexes{$i} if $indexes{$i} == -1;
11535         }
11536         my @indexes = sort { $indexes{$a} <=> $indexes{$b} } keys(%indexes);
11537
11538         my @serials = @{
11539             $dbh->selectall_arrayref(
11540                 "SELECT * FROM serial WHERE subscriptionid = $subscription->{subscriptionid}",
11541                 { Slice => {} }
11542             )
11543         };
11544
11545         foreach my $serial (@serials) {
11546             my $serialseq = $serial->{serialseq};
11547             my %enumeration_data;
11548
11549             ## We cannot split on multiple values at once,
11550             ## so let's replace each of those values with __SPLIT__
11551             if (@splits) {
11552                 for my $split_item (@splits) {
11553                     my $quoted_split = quotemeta($split_item);
11554                     $serialseq =~ s/$quoted_split/__SPLIT__/;
11555                 }
11556                 (
11557                     undef,
11558                     $enumeration_data{ $indexes[0] // q{} },
11559                     $enumeration_data{ $indexes[1] // q{} },
11560                     $enumeration_data{ $indexes[2] // q{} }
11561                 ) = split( /__SPLIT__/, $serialseq );
11562             }
11563             else
11564             {    ## Nothing to split on means the only thing in serialseq is a single placeholder e.g. {X}
11565                 $enumeration_data{ $indexes[0] } = $serialseq;
11566             }
11567
11568             $sth3->execute(
11569                     $enumeration_data{'X'},
11570                     $enumeration_data{'Y'},
11571                     $enumeration_data{'Z'},
11572                     $serial->{serialid},
11573             );
11574         }
11575     }
11576
11577     print "Upgrade to $DBversion done ( Bug 8956 - Split serials enumeration data into separate fields )\n";
11578     SetVersion($DBversion);
11579 }
11580
11581 $DBversion = "3.23.00.007";
11582 if ( CheckVersion($DBversion) ) {
11583     $dbh->do("SET FOREIGN_KEY_CHECKS=0");
11584     $dbh->do("ALTER TABLE overduerules RENAME old_overduerules");
11585     $dbh->do("CREATE TABLE overduerules (
11586         `overduerules_id` int(11) NOT NULL AUTO_INCREMENT,
11587         `branchcode` varchar(10) NOT NULL DEFAULT '',
11588         `categorycode` varchar(10) NOT NULL DEFAULT '',
11589         `delay1` int(4) DEFAULT NULL,
11590         `letter1` varchar(20) DEFAULT NULL,
11591         `debarred1` varchar(1) DEFAULT '0',
11592         `delay2` int(4) DEFAULT NULL,
11593         `debarred2` varchar(1) DEFAULT '0',
11594         `letter2` varchar(20) DEFAULT NULL,
11595         `delay3` int(4) DEFAULT NULL,
11596         `letter3` varchar(20) DEFAULT NULL,
11597         `debarred3` int(1) DEFAULT '0',
11598         PRIMARY KEY (`overduerules_id`),
11599         UNIQUE KEY `overduerules_branch_cat` (`branchcode`,`categorycode`)
11600         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
11601     $dbh->do("INSERT INTO overduerules(branchcode, categorycode, delay1, letter1, debarred1, delay2, debarred2, letter2, delay3, letter3, debarred3) SELECT * FROM old_overduerules");
11602     $dbh->do("DROP TABLE old_overduerules");
11603     $dbh->do("ALTER TABLE overduerules_transport_types
11604               ADD COLUMN overduerules_id int(11) NOT NULL");
11605     my $mtts = $dbh->selectall_arrayref("SELECT * FROM overduerules_transport_types", { Slice => {} });
11606     $dbh->do("DELETE FROM overduerules_transport_types");
11607     $dbh->do("ALTER TABLE overduerules_transport_types
11608               DROP FOREIGN KEY overduerules_fk,
11609               ADD FOREIGN KEY overduerules_transport_types_fk (overduerules_id) REFERENCES overduerules (overduerules_id) ON DELETE CASCADE ON UPDATE CASCADE,
11610               DROP COLUMN branchcode,
11611               DROP COLUMN categorycode");
11612     my $s = $dbh->prepare("INSERT INTO overduerules_transport_types (overduerules_id, id, letternumber, message_transport_type) "
11613                          ." VALUES((SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?),?,?,?)");
11614     foreach my $mtt(@$mtts){
11615         $s->execute($mtt->{branchcode}, $mtt->{categorycode}, $mtt->{id}, $mtt->{letternumber}, $mtt->{message_transport_type} );
11616     }
11617     $dbh->do("SET FOREIGN_KEY_CHECKS=1");
11618
11619     print "Upgrade to $DBversion done (Bug 13624 - Remove columns branchcode, categorytype from table overduerules_transport_types)\n";
11620     SetVersion($DBversion);
11621 }
11622
11623 $DBversion = "3.23.00.008";
11624 if ( CheckVersion($DBversion) ) {
11625
11626     $dbh->do(q{ALTER TABLE borrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11627
11628     $dbh->do(q{ALTER TABLE deletedborrowers ADD privacy_guarantor_checkouts BOOLEAN NOT NULL DEFAULT '0' AFTER privacy});
11629
11630     $dbh->do(q{
11631         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
11632         VALUES (
11633             'AllowStaffToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11634             'If enabled, library staff can set a patron''s checkouts to be visible to linked patrons from the opac.',  'YesNo'
11635         ), (
11636             'AllowPatronToSetCheckoutsVisibilityForGuarantor',  '0', NULL,
11637             'If enabled, the patron can set checkouts to be visible to  his or her guarantor',  'YesNo'
11638         )
11639     });
11640
11641     print "Upgrade to $DBversion done (Bug 9303 - relative's checkouts in the opac)\n";
11642     SetVersion($DBversion);
11643 }
11644
11645 $DBversion = "3.23.00.009";
11646 if ( CheckVersion($DBversion) ) {
11647     $dbh->do(q{
11648         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES
11649         ( 'EnablePayPalOpacPayments',  '0', NULL ,  'Enables the ability to pay fees and fines from  the OPAC via PayPal',  'YesNo' ),
11650         ( 'PayPalChargeDescription',  'Koha fee payment', NULL ,  'This preference defines what the user will see the charge listed as in PayPal',  'Free' ),
11651         ( 'PayPalPwd',  '', NULL ,  'Your PayPal API password',  'Free' ),
11652         ( 'PayPalSandboxMode',  '1', NULL ,  'If enabled, the system will use PayPal''s sandbox server for testing, rather than the production server.',  'YesNo' ),
11653         ( 'PayPalSignature',  '', NULL ,  'Your PayPal API signature',  'Free' ),
11654         ( 'PayPalUser',  '', NULL ,  'Your PayPal API username ( email address )',  'Free' )
11655     });
11656
11657     print "Upgrade to $DBversion done (Bug 11622 - Add ability to pay fees and fines from OPAC via PayPal)\n";
11658     SetVersion($DBversion);
11659 }
11660
11661 $DBversion = "3.23.00.010";
11662 if ( CheckVersion($DBversion) ) {
11663     $dbh->do(q{
11664         ALTER TABLE issuingrules ADD cap_fine_to_replacement_price BOOLEAN NOT NULL DEFAULT '0' AFTER overduefinescap
11665     });
11666
11667     print "Upgrade to $DBversion done (Bug 9129 - Add the ability to set the maximum fine for an item to its replacement price)\n";
11668     SetVersion($DBversion);
11669 }
11670
11671 $DBversion = "3.23.00.011";
11672 if ( CheckVersion($DBversion) ) {
11673     $dbh->do(q{
11674         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('HoldFeeMode','not_always','always|not_always','Set the hold fee mode','Choice')
11675     });
11676
11677     print "Upgrade to $DBversion done (Bug 13592 - Hold fee not being applied on placing a hold)\n";
11678     SetVersion($DBversion);
11679 }
11680
11681 $DBversion = "3.23.00.012";
11682 if ( CheckVersion($DBversion) ) {
11683     $dbh->do(q{
11684         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `explanation`, `options`, `type` ) VALUES('MaxSearchResultsItemsPerRecordStatusCheck','20','Max number of items per record for which to check transit and hold status','','Integer')
11685     });
11686
11687     print "Upgrade to $DBversion done (Bug 15380 - Move the authority types related code to Koha::Authority::Type[s] - part 1)\n";
11688     SetVersion($DBversion);
11689 }
11690
11691 $DBversion = "3.23.00.013";
11692 if ( CheckVersion($DBversion) ) {
11693     $dbh->do(q{
11694         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('StoreLastBorrower','0','','If ON, the last borrower to return an item will be stored in items.last_returned_by','YesNo')
11695     });
11696     $dbh->do(q{
11697         CREATE TABLE IF NOT EXISTS `items_last_borrower` (
11698   `id` int(11) NOT NULL AUTO_INCREMENT,
11699   `itemnumber` int(11) NOT NULL,
11700   `borrowernumber` int(11) NOT NULL,
11701   `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
11702   PRIMARY KEY (`id`),
11703   UNIQUE KEY `itemnumber` (`itemnumber`),
11704   KEY `borrowernumber` (`borrowernumber`),
11705   CONSTRAINT `items_last_borrower_ibfk_2` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
11706   CONSTRAINT `items_last_borrower_ibfk_1` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
11707 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
11708     });
11709
11710     print "Upgrade to $DBversion done (Bug 14945 - Add the ability to store the last patron to return an item)\n";
11711     SetVersion($DBversion);
11712
11713 }
11714
11715 $DBversion = "3.23.00.014";
11716 if ( CheckVersion($DBversion) ) {
11717     $dbh->do(q{
11718         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
11719 VALUES ('ClaimsBccCopy','0','','Bcc the ClaimAcquisition and ClaimIssues alerts','YesNo')
11720     });
11721
11722     print "Upgrade to $DBversion done (Bug 10076 - Add Bcc syspref for claimacquisition and clamissues)\n";
11723     SetVersion($DBversion);
11724 }
11725
11726 $DBversion = "3.23.00.015";
11727 if ( CheckVersion($DBversion) ) {
11728     $dbh->do(q{
11729         UPDATE letter SET code = "HOLD_SLIP" WHERE code = "RESERVESLIP";
11730     });
11731
11732     print "Upgrade to $DBversion done (Bug 15443 - Re-code RESERVESLIP as HOLD_SLIP)\n";
11733     SetVersion($DBversion);
11734 }
11735
11736 $DBversion = "3.23.00.016";
11737 if ( CheckVersion($DBversion) ) {
11738     $dbh->do(q{
11739     INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11740     VALUES ('OpacResetPassword',  '0','','Shows the ''Forgot your password?'' link in the OPAC','YesNo');
11741 });
11742     $dbh->do(q{
11743     CREATE TABLE IF NOT EXISTS borrower_password_recovery (
11744       borrowernumber int(11) NOT NULL,
11745       uuid varchar(128) NOT NULL,
11746       valid_until timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11747       PRIMARY KEY (borrowernumber),
11748       KEY borrowernumber (borrowernumber)
11749     ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11750 });
11751     $dbh->do(q{
11752     INSERT IGNORE INTO `letter` (module, code, branchcode, name, is_html, title, content, message_transport_type)
11753     VALUES ('members','PASSWORD_RESET','','Online password reset',1,'Koha password recovery','<html>\r\n<p>This email has been sent in response to your password recovery request for the account <strong><<user>></strong>.\r\n</p>\r\n<p>\r\nYou can now create your new password using the following link:\r\n<br/><a href=\"<<passwordreseturl>>\"><<passwordreseturl>></a>\r\n</p>\r\n<p>This link will be valid for 2 days from this email\'s reception, then you must reapply if you do not change your password.</p>\r\n<p>Thank you.</p>\r\n</html>\r\n','email');
11754
11755     });
11756
11757     print "Upgrade to $DBversion done (Bug 8753 - Add forgot password link to OPAC)\n";
11758     SetVersion($DBversion);
11759 }
11760
11761 $DBversion = "3.23.00.017";
11762 if ( CheckVersion($DBversion) ) {
11763
11764 $dbh->do(q{
11765     DELETE FROM uploaded_files
11766     WHERE COALESCE(permanent,0)=0 AND dir='koha_upload'
11767 });
11768
11769 my $tmp = C4::Context->temporary_directory . '/koha_upload';
11770 remove_tree( $tmp ) if -d $tmp;
11771
11772     print "Upgrade to $DBversion done (Bug 14893 - Separate temporary storage per instance in Upload.pm)\n";
11773     SetVersion($DBversion);
11774
11775 }
11776
11777 $DBversion = "3.23.00.018";
11778 if ( CheckVersion($DBversion) ) {
11779     $dbh->do(q{
11780         UPDATE systempreferences SET value="0" where type="YesNo" and value="";
11781     });
11782
11783     print "Upgrade to $DBversion done (Bug 15446 - Fix systempreferences rows where type=YesNo and value='')\n";
11784     SetVersion($DBversion);
11785 }
11786
11787 $DBversion = "3.23.00.019";
11788 if ( CheckVersion($DBversion) ) {
11789     $dbh->do(q{
11790         UPDATE `authorised_values` SET `lib`='Non-fiction' WHERE `lib`='Non Fiction';
11791     });
11792
11793     print "Upgrade to $DBversion done (Bug 15411 - Change Non Fiction to Non-fiction in authorised_values)\n";
11794     SetVersion($DBversion);
11795 }
11796
11797 $DBversion = "3.23.00.020";
11798 if ( CheckVersion($DBversion) ) {
11799     $dbh->do(q{
11800         CREATE TABLE  sms_providers (
11801            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
11802            name VARCHAR( 255 ) NOT NULL ,
11803            domain VARCHAR( 255 ) NOT NULL ,
11804            UNIQUE (
11805                name
11806            )
11807         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
11808     });
11809
11810     $dbh->do(q{
11811         ALTER TABLE borrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11812     });
11813     $dbh->do(q{
11814         ALTER TABLE borrowers ADD FOREIGN KEY ( sms_provider_id ) REFERENCES sms_providers ( id ) ON UPDATE CASCADE ON DELETE SET NULL;
11815     });
11816     $dbh->do(q{
11817         ALTER TABLE deletedborrowers ADD sms_provider_id INT( 11 ) NULL DEFAULT NULL AFTER smsalertnumber;
11818     });
11819
11820     print "Upgrade to $DBversion done (Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers)\n";
11821     SetVersion($DBversion);
11822 }
11823
11824 $DBversion = "3.23.00.021";
11825 if ( CheckVersion($DBversion) ) {
11826     $dbh->do(q{
11827         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('ShowAllCheckins', '0', '', 'Show all checkins', 'YesNo');
11828     });
11829
11830     print "Upgrade to $DBversion done (Bug 15736 - Add a preference to control whether all items should be shown in checked-in items list)\n";
11831     SetVersion($DBversion);
11832 }
11833
11834 $DBversion = "3.23.00.022";
11835 if ( CheckVersion($DBversion) ) {
11836     $dbh->do(q{ ALTER TABLE tags_all MODIFY COLUMN borrowernumber INT(11) });
11837     $dbh->do(q{ ALTER TABLE tags_all drop FOREIGN KEY tags_borrowers_fk_1 });
11838     $dbh->do(q{ ALTER TABLE tags_all ADD CONSTRAINT `tags_borrowers_fk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE });
11839     $dbh->do(q{ ALTER TABLE tags_approval DROP FOREIGN KEY tags_approval_borrowers_fk_1 });
11840     $dbh->do(q{ ALTER TABLE tags_approval ADD CONSTRAINT `tags_approval_borrowers_fk_1` FOREIGN KEY (`approved_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE });
11841
11842     print "Upgrade to $DBversion done (Bug 13534 - Deleting staff patron will delete tags approved by this patron)\n";
11843     SetVersion($DBversion);
11844 }
11845
11846 $DBversion = "3.23.00.023";
11847 if ( CheckVersion($DBversion) ) {
11848     $dbh->do(q{
11849         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11850         VALUES('OpenLibrarySearch','0','If Yes Open Library search results will show in OPAC',NULL,'YesNo');
11851     });
11852
11853     print "Upgrade to $DBversion done (Bug 6624 - Allow Koha to use the new read API from OpenLibrary)\n";
11854     SetVersion($DBversion);
11855 }
11856
11857 $DBversion = "3.23.00.024";
11858 if ( CheckVersion($DBversion) ) {
11859     $dbh->do(q{
11860         ALTER TABLE deletedborrowers MODIFY COLUMN userid VARCHAR(75) DEFAULT NULL;
11861     });
11862
11863     $dbh->do(q{
11864         ALTER TABLE deletedborrowers MODIFY COLUMN password VARCHAR(60) DEFAULT NULL;
11865     });
11866
11867     print "Upgrade to $DBversion done (Bug 15517 - Tables borrowers and deletedborrowers differ again)\n";
11868     SetVersion($DBversion);
11869 }
11870
11871 $DBversion = "3.23.00.025";
11872 if ( CheckVersion($DBversion) ) {
11873     $dbh->do(q{
11874         DROP TABLE IF EXISTS nozebra;
11875     });
11876
11877     print "Upgrade to $DBversion done (Bug 15526 - Drop nozebra database table)\n";
11878     SetVersion($DBversion);
11879 }
11880
11881 $DBversion = "3.23.00.026";
11882 if ( CheckVersion($DBversion) ) {
11883     $dbh->do(q{
11884         UPDATE systempreferences SET value = CONCAT_WS('|', IF(value='', NULL, value), "password") WHERE variable="PatronSelfRegistrationBorrowerUnwantedField" AND value NOT LIKE "%password%";
11885     });
11886
11887     print "Upgrade to $DBversion done (Bug 15343 - Allow patrons to choose their own password on self registration)\n";
11888     SetVersion($DBversion);
11889 }
11890
11891 $DBversion = "3.23.00.027";
11892 if ( CheckVersion($DBversion) ) {
11893     my ( $db_value ) = $dbh->selectrow_array(q|SELECT count(*) FROM branches|);
11894     my $pref_value = C4::Context->preference("singleBranchMode") || 0;
11895     if ( $db_value > 1 and $pref_value == 1 ) {
11896         warn "WARNING: You have more than 1 libraries in your branches tables but the singleBranchMode system preference is on.\n";
11897         warn "This configuration does not make sense. The system preference is going to be deleted,\n";
11898         warn "and this parameter will be based on the number of libraries defined.\n";
11899     }
11900     $dbh->do(q|DELETE FROM systempreferences WHERE variable="singleBranchMode"|);
11901
11902     print "Upgrade to $DBversion done (Bug 4941 - Can't set branch in staff client when singleBranchMode is enabled)\n";
11903     SetVersion($DBversion);
11904 }
11905
11906 $DBversion = "3.23.00.028";
11907 if ( CheckVersion($DBversion) ) {
11908     $dbh->do(q{
11909         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) SELECT 'PatronSelfModificationBorrowerUnwantedField',value,NULL,'Name the fields you don\'t want to display when a patron is editing their information via the OPAC.','free' FROM systempreferences WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField';
11910     });
11911
11912     print "Upgrade to $DBversion done (Bug 14658 - Split PatronSelfRegistrationBorrowerUnwantedField into two preferences for creating and editing)\n";
11913     SetVersion($DBversion);
11914 }
11915
11916 $DBversion = "3.23.00.029";
11917 if ( CheckVersion($DBversion) ) {
11918
11919     # move marc21_field_003.pl 040c and 040d to marc21_orgcode.pl
11920     $dbh->do(q{
11921         update marc_subfield_structure set value_builder='marc21_orgcode.pl' where value_builder IN ( 'marc21_field_003.pl', 'marc21_field_040c.pl', 'marc21_field_040d.pl' );
11922     });
11923     $dbh->do(q{
11924         update auth_subfield_structure set value_builder='marc21_orgcode.pl' where value_builder IN ( 'marc21_field_003.pl', 'marc21_field_040c.pl', 'marc21_field_040d.pl' );
11925     });
11926
11927     print "Upgrade to $DBversion done (Bug 14199 - Unify all organization code plugins)\n";
11928     SetVersion($DBversion);
11929 }
11930
11931 $DBversion = "3.23.00.030";
11932 if(CheckVersion($DBversion)) {
11933     $dbh->do(q{
11934         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
11935         VALUES ('OpacMaintenanceNotice','','','A user-defined block of HTML to appear on screen when OpacMaintenace is enabled','Textarea')
11936     });
11937
11938     print "Upgrade to $DBversion done (Bug 15311: Let libraries set text to display when OpacMaintenance = on)\n";
11939     SetVersion($DBversion);
11940 }
11941
11942 $DBversion = "3.23.00.031";
11943 if(CheckVersion($DBversion)) {
11944     $dbh->do(q{
11945         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
11946         VALUES ('NoRenewalBeforePrecision', 'date', 'Calculate "No renewal before" based on date or exact time. Only relevant for loans calculated in days, hourly loans are not affected.', 'date|exact_time', 'Choice')
11947     });
11948
11949     print "Upgrade to $DBversion done (Bug 14395 - Two different ways to calculate 'No renewal before')\n";
11950     SetVersion($DBversion);
11951 }
11952
11953 $DBversion = "3.23.00.032";
11954 if ( CheckVersion($DBversion) ) {
11955     $dbh->do(q{
11956    -- Add issue_id to accountlines table
11957     ALTER TABLE accountlines ADD issue_id INT(11) NULL DEFAULT NULL AFTER accountlines_id;
11958     });
11959
11960 ## Close out any accruing fines with no current issue
11961     $dbh->do(q{
11962     UPDATE accountlines LEFT JOIN issues USING ( itemnumber, borrowernumber ) SET accounttype = 'F' WHERE accounttype = 'FU' and issues.issue_id IS NULL;
11963     });
11964
11965 ## Close out any extra not really accruing fines, keep only the latest accring fine
11966     $dbh->do(q{
11967     UPDATE accountlines a1
11968     LEFT JOIN (SELECT MAX(accountlines_id) AS keeper,
11969                       borrowernumber,
11970                       itemnumber
11971                FROM   accountlines
11972                WHERE  accounttype = 'FU'
11973                GROUP BY borrowernumber, itemnumber
11974               ) a2 USING ( borrowernumber, itemnumber )
11975     SET    a1.accounttype = 'F'
11976     WHERE  a1.accounttype = 'FU'
11977     AND  a1.accountlines_id != a2.keeper;
11978     });
11979
11980 ## Update the unclosed fines to add the current issue_id to them
11981     $dbh->do(q{
11982     UPDATE accountlines LEFT JOIN issues USING ( itemnumber ) SET accountlines.issue_id = issues.issue_id WHERE accounttype = 'FU'; 
11983     });
11984
11985     print "Upgrade to $DBversion done (Bug 15675 - Add issue_id column to accountlines and use it for updating fines)\n";
11986     SetVersion($DBversion);
11987 }
11988
11989 $DBversion = "3.23.00.033";
11990 if ( CheckVersion($DBversion) ) {
11991     $dbh->do(q{
11992     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'cardnumber') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%cardnumber%';
11993     });
11994
11995     $dbh->do(q{
11996     UPDATE systempreferences SET value = CONCAT_WS('|', IF(value = '', NULL, value), 'categorycode') WHERE variable = 'PatronSelfRegistrationBorrowerUnwantedField' AND value NOT LIKE '%categorycode%';
11997     });
11998
11999     print "Upgrade to $DBversion done (Bug 14659 - Allow patrons to enter card number and patron category on OPAC registration page)\n";
12000     SetVersion($DBversion);
12001 }
12002
12003 $DBversion = "3.23.00.034";
12004 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12005     $dbh->do(q{
12006         ALTER TABLE `items` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12007     });
12008     $dbh->do(q{
12009         ALTER TABLE `deleteditems` ADD `new` VARCHAR(32) NULL AFTER `stocknumber`;
12010     });
12011     print "Upgrade to $DBversion done (Bug 11023: Adds field 'new' in items and deleteditems tables)\n";
12012     SetVersion($DBversion);
12013 }
12014
12015 $DBversion = "3.23.00.035";
12016 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12017     $dbh->do(q{
12018         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('HTML5MediaYouTube',0,'Embed|Don\'t embed','YouTube links as videos','YesNo');
12019     });
12020     print "Upgrade to $DBversion done (Bug 14168 - enhance streaming cataloging to include youtube)\n";
12021
12022     SetVersion($DBversion);
12023     }
12024
12025 $DBversion = "3.23.00.036";
12026 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12027     $dbh->do(q{
12028     INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('HoldsQueueSkipClosed', '0', 'If enabled, any libraries that are closed when the holds queue is built will be ignored for the purpose of filling holds.', 'YesNo');
12029     });
12030     print "Upgrade to $DBversion done (Bug 12803 - Add ability to skip closed libraries when generating the holds queue)\n";
12031     SetVersion($DBversion);
12032     }
12033
12034 $DBversion = "3.23.00.037";
12035 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12036 ## Add the new currency.archived column
12037     $dbh->do(q{
12038     ALTER TABLE currency ADD column archived tinyint(1) DEFAULT 0;
12039     });
12040 ## Set currency=NULL if empty (just in case)
12041     $dbh->do(q{
12042     UPDATE aqorders SET currency=NULL WHERE currency="";
12043     });
12044 ## Insert the missing currency and mark them as archived before adding the FK
12045     $dbh->do(q{
12046     INSERT INTO currency(currency, archived) SELECT distinct currency, 1 FROM aqorders WHERE currency NOT IN (SELECT currency FROM currency);
12047     });
12048 ## Correct the field length in aqorders before adding FK too
12049     $dbh->do(q{ ALTER TABLE aqorders MODIFY COLUMN currency varchar(10) default NULL; });
12050 ## And finally add the FK
12051     $dbh->do(q{
12052     ALTER TABLE aqorders ADD FOREIGN KEY (currency) REFERENCES currency(currency) ON DELETE SET NULL ON UPDATE SET null;
12053     });
12054
12055     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12056     SetVersion($DBversion);
12057 }
12058
12059 $DBversion = "3.23.00.038";
12060 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12061     $dbh->do(q{
12062     INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('decreaseLoanHighHoldsControl', 'static', 'static|dynamic', "Chooses between static and dynamic high holds checking", 'Choice'), ('decreaseLoanHighHoldsIgnoreStatuses', '', 'damaged|itemlost|notforloan|withdrawn', "Ignore items with these statuses for dynamic high holds checking", 'Choice');
12063     });
12064     print "Upgrade to $DBversion done (Bug 14694 - Make decreaseloanHighHolds more flexible)\n";
12065     SetVersion($DBversion);
12066 }
12067
12068 $DBversion = "3.23.00.039";
12069 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12070
12071     $dbh->do(q{
12072     ALTER TABLE suggestions
12073     MODIFY COLUMN currency varchar(10) default NULL;
12074     });
12075     $dbh->do(q{
12076     ALTER TABLE aqbooksellers
12077     MODIFY COLUMN currency varchar(10) default NULL;
12078     });
12079     print "Upgrade to $DBversion done (Bug 15084 - Move the currency related code to Koha::Acquisition::Currenc[y|ies])\n";
12080     SetVersion($DBversion);
12081 }
12082
12083
12084 $DBversion = "3.23.00.040";
12085 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12086
12087     my $c = $dbh->selectrow_array('SELECT COUNT(*) FROM systempreferences WHERE variable="intranetcolorstylesheet" AND value="blue.css"');
12088
12089     if ( $c ) {
12090         print "WARNING: You are using a stylesheeet which has been removed from the Koha codebase.\n";
12091         print "Update your intranetcolorstylesheet.\n";
12092     }
12093     print "Upgrade to $DBversion done (Bug 16019 - Check intranetcolorstylesheet for blue.css)\n";
12094     SetVersion($DBversion);
12095 }
12096
12097 $DBversion = "3.23.00.041";
12098 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12099
12100     my $dbh = C4::Context->dbh;
12101     my ($print_error) = $dbh->{PrintError};
12102     $dbh->{RaiseError} = 0;
12103     $dbh->{PrintError} = 0;
12104     $dbh->do("ALTER TABLE overduerules_transport_types ADD COLUMN letternumber INT(1) NOT NULL DEFAULT 1 AFTER id");
12105     $dbh->{PrintError} = $print_error;
12106
12107     print "Upgrade to $DBversion done (Bug 16007: Make sure overduerules_transport_types.letternumber exists)\n";
12108     SetVersion($DBversion);
12109 }
12110
12111 $DBversion = "3.23.00.042";
12112 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12113
12114     $dbh->do(q{
12115             ALTER TABLE items CHANGE new new_status VARCHAR(32) NULL;
12116             });
12117     $dbh->do(q{
12118             ALTER TABLE deleteditems CHANGE new new_status VARCHAR(32) NULL;
12119             });
12120     $dbh->do(q{
12121             UPDATE systempreferences SET value=REPLACE(value, '"items.new"', '"items.new_status"') WHERE variable="automatic_item_modification_by_age_configuration";
12122             });
12123
12124     print "Upgrade to $DBversion done (Bug 16004 - Replace items.new with items.new_status)\n";
12125     SetVersion($DBversion);
12126 }
12127
12128 $DBversion = "3.23.00.043";
12129 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12130     $dbh->do(q{
12131             UPDATE systempreferences SET value="" WHERE value IS NULL;
12132             });
12133
12134     print "Upgrade to $DBversion done (Bug 16070 - Empty (undef) system preferences may cause some issues in combination with memcache)\n";
12135     SetVersion($DBversion);
12136 }
12137
12138 $DBversion = "3.23.00.044";
12139 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12140     $dbh->do(q{
12141             INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
12142             ('GoogleOpenIDConnect', '0', NULL, 'if ON, allows the use of Google OpenID Connect for login', 'YesNo'),
12143             ('GoogleOAuth2ClientID', '', NULL, 'Client ID for the web app registered with Google', 'Free'),
12144             ('GoogleOAuth2ClientSecret', '', NULL, 'Client Secret for the web app registered with Google', 'Free'),
12145             ('GoogleOpenIDConnectDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all Google domains', 'Free');
12146             });
12147
12148     print "Upgrade to $DBversion done (Bug 10988 - Allow login via Google OAuth2 (OpenID Connect))\n";
12149     SetVersion($DBversion);
12150 }
12151
12152 $DBversion = "3.23.00.045";
12153 if ( CheckVersion($DBversion) ) {
12154 ## Holds details for vendors supplying goods by EDI
12155    $dbh->do(q{
12156            CREATE TABLE IF NOT EXISTS vendor_edi_accounts (
12157                    id INT(11) NOT NULL auto_increment,
12158                    description TEXT NOT NULL,
12159                    host VARCHAR(40),
12160                    username VARCHAR(40),
12161                    password VARCHAR(40),
12162                    last_activity DATE,
12163                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12164                    download_directory TEXT,
12165                    upload_directory TEXT,
12166                    san VARCHAR(20),
12167                    id_code_qualifier VARCHAR(3) default '14',
12168                    transport VARCHAR(6) default 'FTP',
12169                    quotes_enabled TINYINT(1) not null default 0,
12170                    invoices_enabled TINYINT(1) not null default 0,
12171                    orders_enabled TINYINT(1) not null default 0,
12172                    responses_enabled TINYINT(1) not null default 0,
12173                    auto_orders TINYINT(1) not null default 0,
12174                    shipment_budget INTEGER(11) REFERENCES aqbudgets( budget_id ),
12175                    PRIMARY KEY  (id),
12176                    KEY vendorid (vendor_id),
12177                    KEY shipmentbudget (shipment_budget),
12178                    CONSTRAINT vfk_vendor_id FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12179                    CONSTRAINT vfk_shipment_budget FOREIGN KEY ( shipment_budget ) REFERENCES aqbudgets ( budget_id )
12180                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12181    });
12182
12183 ## Hold the actual edifact messages with links to associated baskets
12184    $dbh->do(q{
12185            CREATE TABLE IF NOT EXISTS edifact_messages (
12186                    id INT(11) NOT NULL auto_increment,
12187                    message_type VARCHAR(10) NOT NULL,
12188                    transfer_date DATE,
12189                    vendor_id INT(11) REFERENCES aqbooksellers( id ),
12190                    edi_acct  INTEGER REFERENCES vendor_edi_accounts( id ),
12191                    status TEXT,
12192                    basketno INT(11) REFERENCES aqbasket( basketno),
12193                    raw_msg MEDIUMTEXT,
12194                    filename TEXT,
12195                    deleted BOOLEAN NOT NULL DEFAULT 0,
12196                    PRIMARY KEY  (id),
12197                    KEY vendorid ( vendor_id),
12198                    KEY ediacct (edi_acct),
12199                    KEY basketno ( basketno),
12200                    CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ),
12201                    CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ),
12202                    CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno )
12203                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12204             });
12205
12206 ## invoices link back to the edifact message it was generated from
12207    $dbh->do(q{
12208            ALTER TABLE aqinvoices ADD COLUMN message_id INT(11) REFERENCES edifact_messages( id );
12209            });
12210
12211 ## clean up link on deletes
12212    $dbh->do(q{
12213            ALTER TABLE aqinvoices ADD CONSTRAINT edifact_msg_fk FOREIGN KEY ( message_id ) REFERENCES edifact_messages ( id ) ON DELETE SET NULL;
12214            });
12215
12216 ## Hold the supplier ids from quotes for ordering
12217 ## although this is an EAN-13 article number the standard says 35 characters ???
12218    $dbh->do(q{
12219            ALTER TABLE aqorders ADD COLUMN line_item_id VARCHAR(35);
12220            });
12221
12222 ## The suppliers unique reference usually a quotation line number ('QLI')
12223 ## Otherwise Suppliers unique orderline reference ('SLI')
12224    $dbh->do(q{
12225            ALTER TABLE aqorders ADD COLUMN suppliers_reference_number VARCHAR(35);
12226            });
12227    $dbh->do(q{
12228            ALTER TABLE aqorders ADD COLUMN suppliers_reference_qualifier VARCHAR(3);
12229            });
12230    $dbh->do(q{
12231            ALTER TABLE aqorders ADD COLUMN suppliers_report text;
12232            });
12233
12234 ## hold the EAN/SAN used in ordering
12235    $dbh->do(q{
12236            CREATE TABLE IF NOT EXISTS edifact_ean (
12237                    ee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
12238                    description VARCHAR(128) NULL DEFAULT NULL,
12239                    branchcode VARCHAR(10) NOT NULL REFERENCES branches (branchcode),
12240                    ean VARCHAR(15) NOT NULL,
12241                    id_code_qualifier VARCHAR(3) NOT NULL DEFAULT '14',
12242                    CONSTRAINT efk_branchcode FOREIGN KEY ( branchcode ) REFERENCES branches ( branchcode )
12243                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12244            });
12245
12246 ## Add a permission for managing EDI
12247    $dbh->do(q{
12248            INSERT INTO permissions (module_bit, code, description) values (11, 'edi_manage', 'Manage EDIFACT transmissions');
12249            });
12250
12251    print "Upgrade to $DBversion done (Bug 7736 - Edifact QUOTE and ORDER functionality))\n";
12252    SetVersion($DBversion);
12253 }
12254
12255 $DBversion = "3.23.00.046";
12256 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12257
12258     $dbh->do(q{
12259     ALTER TABLE vendor_edi_accounts ADD COLUMN plugin VARCHAR(256) NOT NULL DEFAULT "";
12260     });
12261
12262     print "Upgrade to $DBversion done (Bug 15630 - Make Edifact module pluggable))\n";
12263     SetVersion($DBversion);
12264 }
12265
12266 $DBversion = "3.23.00.047";
12267 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12268
12269     $dbh->do(q{
12270          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('IntranetReportsHomeHTML', '', 'Show the following HTML in a div on the bottom of the reports home page', NULL, 'Free');
12271          });
12272     $dbh->do(q{
12273          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('IntranetCirculationHomeHTML', '', 'Show the following HTML in a div on the bottom of the reports home page', NULL, 'Free');
12274          });
12275
12276     print "Upgrade to $DBversion done (Bug 15008 - Add custom HTML areas to circulation and reports home pages)\n";
12277     SetVersion($DBversion);
12278 }
12279
12280 $DBversion = "3.23.00.048";
12281 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12282     $dbh->do(q{
12283     INSERT IGNORE INTO `systempreferences` (variable,value,options,explanation,type)  SELECT 'OPACISBD', value, '70|10', 'Allows to define ISBD view in OPAC', 'Textarea' FROM `systempreferences` WHERE variable = 'ISBD';
12284     });
12285
12286     print "Upgrade to $DBversion done (Bug 5979 - Add separate OPACISBD system preference)\n";
12287     SetVersion($DBversion);
12288 }
12289
12290
12291
12292 $DBversion = "3.23.00.049";
12293 if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
12294 my $dbh = C4::Context->dbh;
12295 my ( $column_has_been_used ) = $dbh->selectrow_array(q|
12296             SELECT COUNT(*)
12297                 FROM borrower_attributes
12298                     WHERE password IS NOT NULL
12299                     |);
12300
12301 if ( $column_has_been_used ) {
12302         print q|WARNING: The columns borrower_attribute_types.password_allowed and borrower_attributes.password have been removed from the Koha codebase. They were not used. However your installation has at least one borrower_attributes.password defined. In order not to alter your data, the columns have been kept, please save the information elsewhere and remove these columns manually.|;
12303 } else {
12304         $dbh->do(q|
12305         ALTER TABLE borrower_attribute_types DROP column password_allowed
12306         |);
12307         $dbh->do(q|
12308         ALTER TABLE borrower_attributes DROP column password;
12309         |);
12310     }
12311     print "Upgrade to $DBversion done (Bug 12267 - Allow password option in Patron Attribute non functional)\n";
12312         SetVersion($DBversion);
12313 }
12314
12315
12316 $DBversion = "3.23.00.050";
12317 if ( CheckVersion($DBversion) ) {
12318
12319     $dbh->do(q|INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12320                     VALUES('SearchEngine','Zebra','Choose Search Engine','','Choice')|);
12321
12322
12323     $dbh->do(q|DROP TABLE IF EXISTS search_marc_to_field|);
12324     $dbh->do(q|DROP TABLE IF EXISTS search_marc_map|);
12325     $dbh->do(q|DROP TABLE IF EXISTS search_field|);
12326
12327 # This specifies the fields that will be stored in the search engine.
12328  $dbh->do(q|
12329          CREATE TABLE `search_field` (
12330              `id` int(11) NOT NULL AUTO_INCREMENT, 
12331              `name` varchar(255) NOT NULL COMMENT 'the name of the field as it will be stored in the search engine',
12332              `label` varchar(255) NOT NULL COMMENT 'the human readable name of the field, for display', 
12333              `type` ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine',
12334              PRIMARY KEY (`id`),
12335              UNIQUE KEY (`name`)
12336              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12337          |);
12338 # This contains a MARC field specifier for a given index, marc type, and marc
12339 # field.
12340 $dbh->do(q|
12341         CREATE TABLE `search_marc_map` (
12342             id int(11) NOT NULL AUTO_INCREMENT,
12343             index_name ENUM('biblios','authorities') NOT NULL COMMENT 'what storage index this map is for',
12344             marc_type ENUM('marc21', 'unimarc', 'normarc') NOT NULL COMMENT 'what MARC type this map is for',
12345             marc_field VARCHAR(255) NOT NULL COMMENT 'the MARC specifier for this field',
12346             PRIMARY KEY(`id`),
12347             unique key( index_name, marc_field, marc_type),
12348             INDEX (`index_name`)
12349             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12350         |);
12351
12352 # This joins the two search tables together. We can have any combination:
12353 # one marc field could have many search fields (maybe you want one value
12354 # to go to 'author' and 'corporate-author) and many marc fields could go
12355 # to one search field (e.g. all the various author fields going into
12356 # 'author'.)
12357 #
12358 # a note about the sort field:
12359 # * if all the entries for a mapping are 'null', nothing special is done with that mapping.
12360 # * if any of the entries are not null, then a __sort field is created in ES for this mapping. In this case:
12361 #   * any mapping with sort == false WILL NOT get copied into a __sort field
12362 #   * any mapping with sort == true or is null WILL get copied into a __sort field
12363 #   * any sorts on the field name will be applied to $fieldname.'__sort' instead.
12364 # this means that we can have search for author that includes 1xx, 245$c, and 7xx, but the sort only applies to 1xx.
12365
12366 $dbh->do(q|
12367         CREATE TABLE `search_marc_to_field` (
12368             search_marc_map_id int(11) NOT NULL,
12369             search_field_id int(11) NOT NULL,
12370             facet boolean DEFAULT FALSE COMMENT 'true if a facet field should be generated for this',
12371             suggestible boolean DEFAULT FALSE COMMENT 'true if this field can be used to generate suggestions for browse',
12372             sort boolean DEFAULT NULL COMMENT 'true/false creates special sort handling, null doesn''t',
12373             PRIMARY KEY(search_marc_map_id, search_field_id),
12374             FOREIGN KEY(search_marc_map_id) REFERENCES search_marc_map(id) ON DELETE CASCADE ON UPDATE CASCADE,
12375             FOREIGN KEY(search_field_id) REFERENCES search_field(id) ON DELETE CASCADE ON UPDATE CASCADE
12376             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
12377         |);
12378
12379     print "WARNING: If you plan to use Elasticsearch you should go to 'Home › Administration › Search engine configuration' and reset the mappings\n";
12380     print "Upgrade to $DBversion done (Bug 12478 - Elasticsearch support for Koha)\n";
12381     SetVersion($DBversion);
12382 }
12383
12384
12385 $DBversion = "3.23.00.051";
12386 if ( CheckVersion($DBversion) ) {
12387 $dbh->do(q{
12388         ALTER TABLE edifact_messages
12389         DROP FOREIGN KEY emfk_vendor,
12390         DROP FOREIGN KEY emfk_edi_acct,
12391         DROP FOREIGN KEY emfk_basketno;
12392         });
12393
12394 $dbh->do(q{
12395         ALTER TABLE edifact_messages
12396         ADD CONSTRAINT emfk_vendor FOREIGN KEY ( vendor_id ) REFERENCES aqbooksellers ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12397         ADD CONSTRAINT emfk_edi_acct FOREIGN KEY ( edi_acct ) REFERENCES vendor_edi_accounts ( id ) ON DELETE CASCADE ON UPDATE CASCADE,
12398         ADD CONSTRAINT emfk_basketno FOREIGN KEY ( basketno ) REFERENCES aqbasket ( basketno ) ON DELETE CASCADE ON UPDATE CASCADE;
12399         });
12400
12401     print "Upgrade to $DBversion done (Bug 16354 - Fix FK constraints for edifact_messages table)\n";
12402     SetVersion($DBversion);
12403 }
12404
12405
12406 $DBversion = "3.23.00.052";
12407 if ( CheckVersion($DBversion) ) {
12408 ## Insert permission
12409
12410     $dbh->do(q{
12411         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
12412         (13, 'upload_general_files', 'Upload any file'),
12413         (13, 'upload_manage', 'Manage uploaded files');
12414         });
12415 ## Update user_permissions for current users (check count in uploaded_files)
12416 ## Note 9 == edit_catalogue and 13 == tools
12417 ## We do not insert if someone is superlibrarian, does not have edit_catalogue,
12418 ## or already has all tools
12419
12420         $dbh->do(q{
12421                 INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
12422                 SELECT borrowernumber, 13, 'upload_general_files'
12423                 FROM borrowers bo
12424                 WHERE flags<>1 AND flags & POW(2,13) = 0 AND
12425                 ( flags & POW(2,9) > 0 OR 
12426                   (SELECT COUNT(*) FROM user_permissions
12427                    WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
12428                 AND ( SELECT COUNT(*) FROM uploaded_files ) > 0
12429                 });
12430
12431     print "Upgrade to $DBversion done (Bug 14686 - New menu option and permission for file uploading)\n";
12432     SetVersion($DBversion);
12433 }
12434
12435 $DBversion = "3.23.00.053";
12436 if ( CheckVersion($DBversion) ) {
12437     my $letters = $dbh->selectall_arrayref(
12438         q|
12439         SELECT code, name
12440         FROM letter
12441         WHERE message_transport_type="email"
12442         |, { Slice => {} }
12443     );
12444     for my $letter (@$letters) {
12445         $dbh->do(
12446             q|
12447                 UPDATE letter
12448                 SET name = ?
12449                 WHERE code = ?
12450                 AND message_transport_type <> "email"
12451                 |, undef, $letter->{name}, $letter->{code}
12452         );
12453     }
12454
12455     print "Upgrade to $DBversion done (Bug 16217 - Notice' names may have diverged)\n";
12456     SetVersion($DBversion);
12457 }
12458
12459 $DBversion = "3.23.00.054";
12460 if ( CheckVersion($DBversion) ) {
12461     $dbh->do(q{
12462         ALTER TABLE branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12463     });
12464     $dbh->do(q{
12465         ALTER TABLE default_branch_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12466     });
12467     $dbh->do(q{
12468         ALTER TABLE default_branch_item_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12469     });
12470     $dbh->do(q{
12471         ALTER TABLE default_circ_rules ADD COLUMN hold_fulfillment_policy ENUM('any', 'homebranch', 'holdingbranch') NOT NULL DEFAULT 'any' AFTER holdallowed;
12472     });
12473
12474     print "Upgrade to $DBversion done (Bug 15532 - Add ability to allow only items whose home/holding branch matches the hold's pickup branch to fill a given hold)\n";
12475     SetVersion($DBversion);
12476 }
12477
12478 $DBversion = "3.23.00.055";
12479 if ( CheckVersion($DBversion) ) {
12480     $dbh->do(q{
12481         ALTER TABLE reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12482     });
12483     $dbh->do(q{
12484         ALTER TABLE reserves ADD KEY `itemtype` (`itemtype`);
12485     });
12486     $dbh->do(q{
12487         ALTER TABLE reserves ADD CONSTRAINT `reserves_ibfk_5` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12488     });
12489     $dbh->do(q{
12490         ALTER TABLE old_reserves ADD COLUMN itemtype VARCHAR(10) NULL DEFAULT NULL AFTER suspend_until;
12491     });
12492     $dbh->do(q{
12493         ALTER TABLE old_reserves ADD KEY `itemtype` (`itemtype`);
12494     });
12495     $dbh->do(q{
12496         ALTER TABLE old_reserves ADD CONSTRAINT `old_reserves_ibfk_4` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE;
12497     });
12498
12499     $dbh->do(q{
12500         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12501         ('AllowHoldItemTypeSelection','0','','If enabled, patrons and staff will be able to select the itemtype when placing a hold','YesNo');
12502     });
12503
12504     print "Upgrade to $DBversion done (Bug 15533 - Allow patrons and librarians to select itemtype when placing hold)\n";
12505     SetVersion($DBversion);
12506 }
12507
12508 $DBversion = "3.23.00.056";
12509 if ( CheckVersion($DBversion) ) {
12510     $dbh->do(q{
12511         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
12512         ('NoIssuesChargeGuarantees','','','Define maximum amount withstanding before check outs are blocked','Integer');
12513     });
12514
12515     print "Upgrade to $DBversion done (Bug 14577 - Allow restriction of checkouts based on fines of guarantor/guarantee)\n";
12516     SetVersion($DBversion);
12517 }
12518
12519 $DBversion = "3.23.00.057";
12520 if ( CheckVersion($DBversion) ) {
12521     $dbh->do(q{
12522         ALTER TABLE aqbasket ADD COLUMN is_standing TINYINT(1) NOT NULL DEFAULT 0 AFTER branch;
12523     });
12524
12525     print "Upgrade to $DBversion done (Bug 15531 - Add support for standing orders)\n";
12526     SetVersion($DBversion);
12527 }
12528
12529 $DBversion = "3.23.00.058";
12530 if ( CheckVersion($DBversion) ) {
12531
12532     my ($count_imageurl) = $dbh->selectrow_array(q|
12533         SELECT COUNT(*)
12534         FROM authorised_values
12535         WHERE imageurl IS NOT NULL
12536             AND imageurl <> ""
12537     |);
12538
12539     unless ($count_imageurl) {
12540         if (   C4::Context->preference('AuthorisedValueImages')
12541             or C4::Context->preference('StaffAuthorisedValueImages') )
12542         {
12543             $dbh->do(q|
12544                 UPDATE systempreferences
12545                 SET value = 0
12546                 WHERE variable = "AuthorisedValueImages"
12547                    or variable = "StaffAuthorisedValueImages"
12548             |);
12549             warn "The system preferences AuthorisedValueImages and StaffAuthorisedValueImages have been turned off\n";
12550             warn "authorised_values.imageurl is not populated, that means you are not using this feature\n";
12551         }
12552     }
12553     else {
12554         warn "At least one authorised value has an icon defined (imageurl)\n";
12555         warn "The system preference AuthorisedValueImages or StaffAuthorisedValueImages could be turned off if you are not aware of this feature\n";
12556     }
12557
12558     print "Upgrade to $DBversion done (Bug 16041 - StaffAuthorisedValueImages & AuthorisedValueImages preferences - impact on search performance)\n";
12559     SetVersion($DBversion);
12560 }
12561
12562 $DBversion = "3.23.00.059";
12563 if ( CheckVersion($DBversion) ) {
12564     $dbh->do(q{
12565         DELETE FROM systempreferences WHERE variable="AuthorisedValueImages" OR variable="StaffAuthorisedValueImages";
12566     });
12567
12568     print "Upgrade to $DBversion done (Bug 16167 - Remove prefs to drive authorised value images)\n";
12569     SetVersion($DBversion);
12570 }
12571
12572 $DBversion = "3.23.00.060";
12573 if ( CheckVersion($DBversion) ) {
12574     $dbh->do(q{
12575         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation,type )
12576         SELECT value ,'EnhancedMessagingPreferencesOPAC', NULL, 'If ON, allows patrons to select to receive additional messages about items due or nearly due.', 'YesNo' FROM systempreferences WHERE variable = 'EnhancedMessagingPreferences';
12577     });
12578
12579     print "Upgrade to $DBversion done (Bug 12528 - Enable staff to deny message setting access to patrons on the OPAC)\n";
12580     SetVersion($DBversion);
12581 }
12582
12583 $DBversion = "3.23.00.061";
12584 if ( CheckVersion($DBversion) ) {
12585     my ( $cnt ) = $dbh->selectrow_array( q|
12586         SELECT COUNT(*) FROM items it
12587         LEFT JOIN biblio bi ON bi.biblionumber=it.biblionumber
12588         LEFT JOIN biblioitems bii USING (biblioitemnumber)
12589         WHERE bi.biblionumber IS NULL
12590     |);
12591     if( $cnt ) {
12592         print "WARNING: You have corrupted data in your items table!! The table contains $cnt references to biblio records that do not exist.\nPlease correct your data IMMEDIATELY after this upgrade and manually add the foreign key constraint for biblionumber in the items table.\n";
12593     } else {
12594         # now add FK
12595         $dbh->do( q|
12596             ALTER TABLE items
12597             ADD FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE
12598         |);
12599         print "Upgrade to $DBversion done (Bug 16170 - Add FK for biblionumber in items)\n";
12600     }
12601     SetVersion($DBversion);
12602 }
12603
12604 $DBversion = "3.23.00.062";
12605 if ( CheckVersion($DBversion) ) {
12606     $dbh->do( q|
12607             ALTER TABLE aqorders DROP COLUMN budgetgroup_id;
12608             |);
12609     print "Upgrade to $DBversion done (Bug 16414 - aqorders.budgetgroup_id has never been used and can be removed)\n";
12610 SetVersion($DBversion);
12611 }
12612
12613 $DBversion = "3.23.00.063";
12614 if ( CheckVersion($DBversion) ) {
12615     $dbh->do(q{
12616         UPDATE letter SET branchcode='' WHERE branchcode IS NULL;
12617     });
12618     $dbh->do(q{
12619         ALTER TABLE letter MODIFY COLUMN branchcode varchar(10) NOT NULL DEFAULT ''
12620     });
12621     $dbh->do(q{
12622         ALTER TABLE permissions MODIFY COLUMN code varchar(64) NOT NULL DEFAULT '';
12623     });
12624     print "Upgrade to $DBversion done (Bug 16402: Fix DB structure to work on MySQL 5.7)\n";
12625     SetVersion($DBversion);
12626 }
12627
12628 $DBversion = "3.23.00.064";
12629 if ( CheckVersion($DBversion) ) {
12630     $dbh->do(q{
12631         ALTER TABLE creator_layouts MODIFY layout_name char(25) NOT NULL DEFAULT 'DEFAULT';
12632     });
12633     print "Upgrade to $DBversion done (Bug 15086 - Creators layout and template sql has warnings)\n";
12634     SetVersion($DBversion);
12635 }
12636
12637 $DBversion = "16.05.00.000";
12638 if ( CheckVersion($DBversion) ) {
12639     print "Upgrade to $DBversion done (Koha 16.05)\n";
12640     SetVersion($DBversion);
12641 }
12642
12643 $DBversion = "16.06.00.000";
12644 if ( CheckVersion($DBversion) ) {
12645     print "Upgrade to $DBversion done (Koha 16.06 - starting a new dev line at KohaCon16 in Thessaloniki, Greece! Koha is great!)\n";
12646     SetVersion($DBversion);
12647 }
12648
12649 $DBversion = "16.06.00.001";
12650 if ( CheckVersion($DBversion) ) {
12651     $dbh->do(q{
12652         UPDATE accountlines SET accounttype='HE', description=itemnumber WHERE (description REGEXP '^Hold waiting too long [0-9]+') AND accounttype='F';
12653     });
12654
12655     print "Upgrade to $DBversion done (Bug 16200 - 'Hold waiting too long' fee has a translation problem)\n";
12656     SetVersion($DBversion);
12657 }
12658
12659 $DBversion = "16.06.00.002";
12660 if ( CheckVersion($DBversion) ) {
12661     unless ( column_exists('borrowers', 'updated_on') ) {
12662         $dbh->do(q{
12663             ALTER TABLE borrowers
12664                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12665                 ON UPDATE CURRENT_TIMESTAMP
12666                 AFTER privacy_guarantor_checkouts;
12667         });
12668         $dbh->do(q{
12669             ALTER TABLE deletedborrowers
12670                 ADD COLUMN updated_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
12671                 ON UPDATE CURRENT_TIMESTAMP
12672                 AFTER privacy_guarantor_checkouts;
12673         });
12674     }
12675
12676     print "Upgrade to $DBversion done (Bug 10459 - borrowers should have a timestamp)\n";
12677     SetVersion($DBversion);
12678 }
12679
12680 $DBversion = "16.06.00.003";
12681 if ( CheckVersion($DBversion) ) {
12682     $dbh->do(q{
12683         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12684         SELECT 'MaxItemsToProcessForBatchMod', value, NULL, 'Process up to a given number of items in a single item modification batch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12685     });
12686     $dbh->do(q{
12687         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12688         SELECT 'MaxItemsToDisplayForBatchDel', value, NULL, 'Display up to a given number of items in a single item deletionbatch.', 'Integer' FROM systempreferences WHERE variable='MaxItemsForBatch';
12689     });
12690     $dbh->do(q{
12691         DELETE FROM systempreferences WHERE variable="MaxItemsForBatch";
12692     });
12693
12694     print "Upgrade to $DBversion done (Bug 11490 - MaxItemsForBatch should be split into two new prefs)\n";
12695     SetVersion($DBversion);
12696 }
12697
12698 $DBversion = '16.06.00.004';
12699 if ( CheckVersion($DBversion) ) {
12700     $dbh->do(q{
12701         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12702          SELECT 'OPACXSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on OPAC', 'Free'
12703          FROM systempreferences WHERE variable='OPACXSLTResultsDisplay';
12704     });
12705
12706     $dbh->do(q{
12707         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
12708          SELECT 'XSLTListsDisplay', COALESCE(value,''), '', 'Enable XSLT stylesheet control over lists pages display on intranet', 'Free'
12709          FROM systempreferences WHERE variable='XSLTResultsDisplay';
12710     });
12711
12712     print "Upgrade to $DBversion done (Bug 15485: Allow choosing different XSLTs for lists)\n";
12713     SetVersion($DBversion);
12714 }
12715
12716 $DBversion = '16.06.00.005';
12717 if ( CheckVersion($DBversion) ) {
12718     $dbh->do(q{
12719         UPDATE `systempreferences` set options = 'US|FR|CH' where variable = 'CurrencyFormat';
12720     });
12721
12722     print "Upgrade to $DBversion done (Bug 16768 - Add official number format for Switzerland: 1'234'567.89)\n";
12723     SetVersion($DBversion);
12724 }
12725
12726 $DBversion = "16.06.00.006";
12727 if ( CheckVersion($DBversion) ) {
12728     $dbh->do(q{
12729         CREATE TABLE `refund_lost_item_fee_rules` (
12730           `branchcode` varchar(10) NOT NULL default '',
12731           `refund` tinyint(1) NOT NULL default 0,
12732           PRIMARY KEY  (`branchcode`)
12733         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
12734     });
12735     $dbh->do(q{
12736         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12737         VALUES( 'RefundLostOnReturnControl',
12738                 'CheckinLibrary',
12739                 'If a lost item is returned, choose which branch to pick rules for refunding.',
12740                 'CheckinLibrary|PatronLibrary|ItemHomeBranch|ItemHoldingbranch',
12741                 'Choice')
12742     });
12743     # Pick the old syspref as the default rule
12744     $dbh->do(q{
12745         INSERT INTO refund_lost_item_fee_rules (branchcode,refund)
12746             SELECT '*', COALESCE(value,'1') FROM systempreferences WHERE variable='RefundLostItemFeeOnReturn'
12747     });
12748     # Delete the old syspref
12749     $dbh->do(q{
12750         DELETE IGNORE FROM systempreferences
12751         WHERE variable='RefundLostItemFeeOnReturn'
12752     });
12753
12754     print "Upgrade to $DBversion done (Bug 14048: Change RefundLostItemFeeOnReturn to be branch specific)\n";
12755     SetVersion($DBversion);
12756 }
12757
12758 $DBversion = '16.06.00.007';
12759 if ( CheckVersion($DBversion) ) {
12760     $dbh->do(q{
12761         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
12762         VALUES ('PatronQuickAddFields', '', 'A list of fields separated by "|" to be displayed along with mandatory fields in the patron quick add form if chosen at patron entry', NULL, 'Free');
12763     });
12764
12765     print "Upgrade to $DBversion done (Bug 3534 - Patron quick add form)\n";
12766     SetVersion($DBversion);
12767 }
12768
12769 $DBversion = '16.06.00.008';
12770 if ( CheckVersion($DBversion) ) {
12771     $dbh->do(q{
12772         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12773         VALUES('CheckPrevCheckout','hardno','hardyes|softyes|softno|hardno','By default, for every item checked out, should we warn if the patron has checked out that item in the past?','Choice');
12774     });
12775     $dbh->do(q{
12776         ALTER TABLE categories
12777         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12778         AFTER `default_privacy`;
12779     });
12780     $dbh->do(q{
12781         ALTER TABLE borrowers
12782         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12783         AFTER `privacy_guarantor_checkouts`;
12784     });
12785     $dbh->do(q{
12786         ALTER TABLE deletedborrowers
12787         ADD COLUMN `checkprevcheckout` varchar(7) NOT NULL default 'inherit'
12788         AFTER `privacy_guarantor_checkouts`;
12789     });
12790
12791     print "Upgrade to $DBversion done (Bug 6906 - show 'Borrower has previously issued \$ITEM' alert on checkout)\n";
12792     SetVersion($DBversion);
12793 }
12794
12795 $DBversion = '16.06.00.009';
12796 if ( CheckVersion($DBversion) ) {
12797     $dbh->do(q{
12798         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
12799         VALUES ('IntranetCatalogSearchPulldown','0',NULL,'Show a search field pulldown for \"Search the catalog\" boxes. ','YesNo');
12800     });
12801
12802     print "Upgrade to $DBversion done (Bug 14902 - Add qualifier menu to staff side 'Search the Catalog')\n";
12803     SetVersion($DBversion);
12804 }
12805
12806 $DBversion = '16.06.00.010';
12807 if ( CheckVersion($DBversion) ) {
12808     $dbh->do(q{
12809         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
12810         VALUES ('MaxOpenSuggestions','',NULL,'Limit the number of open suggestions a patron can have at once, unlimited if blank','Integer')
12811     });
12812
12813     print "Upgrade to $DBversion done (Bug 15128 - Add ability to limit the number of open purchase suggestions a patron can make)\n";
12814     SetVersion($DBversion);
12815 }
12816
12817 $DBversion = '16.06.00.011';
12818 if ( CheckVersion($DBversion) ) {
12819     $dbh->do(q{
12820         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
12821         ('NovelistSelectStaffEnabled','0',NULL,'Enable  Novelist Select content to the Staff Interface (requires that you have entered in a user profile and password, which can be seen in image links)','YesNo'),
12822         ('NovelistSelectStaffView','tab','tab|above|below','Where to display Novelist Select content','Choice');
12823     });
12824
12825     print "Upgrade to $DBversion done (Bug 11606 - Novelist Select in Staff Client)\n";
12826     SetVersion($DBversion);
12827 }
12828
12829 $DBversion = '16.06.00.012';
12830 if ( CheckVersion($DBversion) ) {
12831     $dbh->do(q{
12832         ALTER TABLE virtualshelves MODIFY COLUMN created_on DATETIME not NULL;
12833     });
12834
12835     print "Upgrade to $DBversion done (Bug 16573 - Web installer fails to load structure and sample data on MySQL 5.7)\n";
12836     SetVersion($DBversion);
12837 }
12838
12839 $DBversion = '16.06.00.013';
12840 if ( CheckVersion($DBversion) ) {
12841     $dbh->do(q{
12842         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
12843         ('OPACResultsLibrary', 'homebranch', 'homebranch|holdingbranch', 'Defines whether the OPAC displays the holding or home branch in search results when using XSLT', 'Choice');
12844     });
12845
12846     print "Upgrade to $DBversion done (Bug 7441 - Search results showing wrong branch)\n";
12847     SetVersion($DBversion);
12848 }
12849
12850 $DBversion = "16.06.00.014";
12851 if ( CheckVersion($DBversion) ) {
12852     $dbh->do(q{
12853         ALTER TABLE `action_logs` ADD COLUMN `interface` VARCHAR(30) DEFAULT NULL AFTER `info`;
12854     });
12855
12856     $dbh->do(q{
12857         ALTER TABLE `action_logs` ADD KEY `interface` (`interface`);
12858     });
12859
12860     print "Upgrade to $DBversion done (Bug 16829: action_logs should have an 'interface' column)\n";
12861     SetVersion($DBversion);
12862 }
12863
12864 $DBversion = "16.06.00.015";
12865 if ( CheckVersion($DBversion) ) {
12866     $dbh->do(q{
12867         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES
12868         ('HoldsLog','0',NULL,'If ON, log create/cancel/suspend/resume actions on holds.','YesNo');
12869     });
12870
12871     print "Upgrade to $DBversion done (Bug 14642: Add logging of hold modifications)\n";
12872     SetVersion($DBversion);
12873 }
12874
12875 $DBversion = "16.06.00.016";
12876 if ( CheckVersion($DBversion) ) {
12877     $dbh->do(q{
12878         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'YYYY', '<<YYYY>>') where defaultvalue like "%YYYY%" and defaultvalue not like "%<<YYYY>>%";
12879     });
12880     $dbh->do(q{
12881         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'MM', '<<MM>>') where defaultvalue like "%MM%" and defaultvalue not like "%<<MM>>%";
12882     });
12883     $dbh->do(q{
12884         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'DD', '<<DD>>') where defaultvalue like "%DD%" and defaultvalue not like "%<<DD>>%";
12885     });
12886     $dbh->do(q{
12887         update marc_subfield_structure set defaultvalue=REPLACE(defaultvalue, 'user', '<<USER>>') where defaultvalue like "%user%" and defaultvalue not like "%<<USER>>%";
12888     });
12889
12890     print "Upgrade to $DBversion done (Bug 7045 - Default-value substitution inconsistent)\n";
12891     SetVersion($DBversion);
12892 }
12893
12894 $DBversion = "16.06.00.017";
12895 if ( CheckVersion($DBversion) ) {
12896     $dbh->do(q{
12897         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('OPACSuggestionMandatoryFields','title','','Define the mandatory fields for a patron purchase suggestions made via OPAC.','multiple');
12898     });
12899
12900     print "Upgrade to $DBversion done (Bug 10848 - Allow configuration of mandatory/required fields on the suggestion form in OPAC)\n";
12901     SetVersion($DBversion);
12902 }
12903
12904 $DBversion = "16.06.00.018";
12905 if ( CheckVersion($DBversion) ) {
12906     $dbh->do(q{
12907         ALTER TABLE issuingrules ADD COLUMN holds_per_record SMALLINT(6) NOT NULL DEFAULT 1 AFTER reservesallowed;
12908     });
12909
12910     print "Upgrade to $DBversion done (Bug 14695 - Add ability to place multiple item holds on a given record per patron)\n";
12911     SetVersion($DBversion);
12912 }
12913
12914 $DBversion = "16.06.00.019";
12915 if ( CheckVersion($DBversion) ) {
12916     $dbh->do(q{
12917         ALTER TABLE reviews CHANGE COLUMN approved approved tinyint(4) DEFAULT 0;
12918     });
12919     $dbh->do(q{
12920         UPDATE reviews SET approved=0 WHERE approved IS NULL;
12921     });
12922
12923     print "Upgrade to $DBversion done (Bug 15839 - Move the reviews related code to Koha::Reviews)\n";
12924     SetVersion($DBversion);
12925 }
12926
12927 $DBversion = "16.06.00.020";
12928 if ( CheckVersion($DBversion) ) {
12929     $dbh->do(q{
12930         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('SwitchOnSiteCheckouts', '0', 'Automatically switch an on-site checkout to a normal checkout', NULL, 'YesNo');
12931     });
12932
12933     print "Upgrade to $DBversion done (Bug 16272 - Transform checkout from on-site checkout to regular checkout)\n";
12934     SetVersion($DBversion);
12935 }
12936
12937 $DBversion = "16.06.00.021";
12938 if ( CheckVersion($DBversion) ) {
12939     $dbh->do(q{
12940         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationEmailMustBeUnique', '0', 'If set, the field borrowers.email will be considered as a unique field on self registering', NULL, 'YesNo');
12941     });
12942
12943     print "Upgrade to $DBversion done (Bug 16275 - Prevent patron self registration if the email already filled in borrowers.email)\n";
12944     SetVersion($DBversion);
12945 }
12946
12947 $DBversion = "16.06.00.022";
12948 if ( CheckVersion($DBversion) ) {
12949     $dbh->do(q{
12950         INSERT IGNORE INTO `permissions`
12951         (module_bit, code,             description) VALUES
12952         (16,         'delete_reports', 'Delete SQL reports');
12953     });
12954     $dbh->do(q{
12955         INSERT IGNORE INTO user_permissions
12956         (borrowernumber,      module_bit,code)
12957         SELECT borrowernumber,module_bit,'delete_reports'
12958             FROM user_permissions
12959             WHERE module_bit=16 AND code='create_reports';
12960     });
12961
12962     print "Upgrade to $DBversion done (Bug 16978 - Add delete reports user permission)\n";
12963     SetVersion($DBversion);
12964 }
12965
12966 $DBversion = "16.06.00.023";
12967 if ( CheckVersion($DBversion) ) {
12968     my $pref = C4::Context->preference('timeout');
12969     if( !$pref || $pref eq '12000000' ) {
12970         # update if pref is null or equals old default value
12971         $dbh->do(q|
12972             UPDATE systempreferences SET value = '1d', type = 'Free'
12973             WHERE variable = 'timeout'
12974         |);
12975         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has been adjusted.\n";
12976     } else {
12977         # only update pref type
12978         $dbh->do(q|
12979             UPDATE systempreferences SET type = 'Free'
12980             WHERE variable = 'timeout'
12981         |);
12982         print "Upgrade to $DBversion done (Bug 17187)\nNote: Pref value for timeout has not been adjusted.\n";
12983     }
12984     SetVersion($DBversion);
12985 }
12986
12987 $DBversion = "16.06.00.024";
12988 if ( CheckVersion($DBversion) ) {
12989     $dbh->do(q{
12990         UPDATE language_descriptions SET description = 'Română' WHERE subtag = 'ro' AND type = 'language' AND lang = 'ro';
12991     });
12992
12993     print "Upgrade to $DBversion done (Bug 16311 - Advanced search language limit typo for Romanian)\n";
12994     SetVersion($DBversion);
12995 }
12996
12997 $DBversion = "16.06.00.025";
12998 if ( CheckVersion($DBversion) ) {
12999     $dbh->do(q{
13000         ALTER TABLE `subscription` ADD `itemtype` VARCHAR( 10 ) NULL AFTER reneweddate, ADD `previousitemtype` VARCHAR( 10 ) NULL AFTER itemtype;
13001     });
13002     $dbh->do(q{
13003         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13004         ('makePreviousSerialAvailable','0','make previous serial automatically available when collecting a new serial. Please note that the item-level_itypes syspref must be set to specific item.','','YesNo');
13005     });
13006
13007     print "Upgrade to $DBversion done (Bug 7677 - Subscriptions: Ability to define default itemtype and automatically change itemtype of older issues on receive of next issue)\n";
13008     SetVersion($DBversion);
13009 }
13010
13011 $DBversion = "16.06.00.026";
13012 if ( CheckVersion($DBversion) ) {
13013     $dbh->do(q{
13014         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationLibraryList', '', 'Only display libraries listed. If empty, all libraries are displayed.', NULL, 'Free');
13015     });
13016
13017     print "Upgrade to $DBversion done (Bug 16274 - Make the selfregistration branchcode selection configurable)\n";
13018     SetVersion($DBversion);
13019 }
13020
13021 $DBversion = "16.06.00.027";
13022 if ( CheckVersion($DBversion) ) {
13023     unless ( column_exists('borrowers', 'lastseen') ) {
13024         $dbh->do(q{
13025             ALTER TABLE borrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13026         });
13027         $dbh->do(q{
13028             ALTER TABLE deletedborrowers ADD COLUMN lastseen datetime default NULL AFTER updated_on;
13029         });
13030     }
13031     $dbh->do(q{
13032         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('TrackLastPatronActivity', '0', 'If set, the field borrowers.lastseen will be updated everytime a patron is seen', NULL, 'YesNo');
13033     });
13034
13035     print "Upgrade to $DBversion done (Bug 16276: Add a new pref TrackLastPatronActivity and new column borrowers.lastseen)\n";
13036     SetVersion($DBversion);
13037 }
13038
13039 $DBversion = '16.06.00.028';
13040 if (C4::Context->preference("Version") < TransformToNum($DBversion)) {
13041     {
13042         print "Attempting upgrade to $DBversion (Bug 17135) ...\n";
13043         my $maintenance_script = C4::Context->config("intranetdir") . "/installer/data/mysql/fix_unclosed_nonaccruing_fines_bug17135.pl";
13044         system("perl $maintenance_script --confirm");
13045
13046         print "Upgrade to $DBversion done (Bug 17135 - Fine for the previous overdue may get overwritten by the next one)\n";
13047
13048         unless ($original_version < TransformToNum("3.23.00.032")) { ## Bug 15675
13049             print "WARNING: There is a possibility (= just a possibility, it's configuration dependent etc.) that - due to regression introduced by Bug 15675 - some old fine records for overdued items (items which got renewed 1+ time while being overdue) may have been overwritten in your production 16.05+ database. See Bugzilla reports for Bug 14390 and Bug 17135 for more details.\n";
13050             print "WARNING: Please note that this upgrade does not try to recover such overwitten old fine records (if any) - it's just an follow-up for Bug 14390, its sole purpose is preventing eventual further-on overwrites from happening in the future. Optional recovery of the overwritten fines (again, if any) is like, totally outside of the scope of this particular upgrade!\n";
13051         }
13052         SetVersion ($DBversion);
13053     }
13054 }
13055
13056 $DBversion = "16.06.00.029";
13057 if ( CheckVersion($DBversion) ) {
13058     $dbh->do(q{
13059         UPDATE systempreferences SET type="Choice" WHERE variable="UsageStatsLibraryType";
13060     });
13061     $dbh->do(q{
13062         UPDATE systempreferences SET value="Canada" WHERE variable="UsageStatsCountry" AND value="CANADA";
13063     });
13064     $dbh->do(q{
13065         UPDATE systempreferences SET value="Czech Republic" WHERE variable="UsageStatsCountry" AND value="CZ";
13066     });
13067     $dbh->do(q{
13068         UPDATE systempreferences SET value="United Kingdom" WHERE variable="UsageStatsCountry" AND (value="England" OR value="UK");
13069     });
13070     $dbh->do(q{
13071         UPDATE systempreferences SET value="Spain" WHERE variable="UsageStatsCountry" AND value="España";
13072     });
13073     $dbh->do(q{
13074         UPDATE systempreferences SET value="Greece" WHERE variable="UsageStatsCountry" AND value="GR";
13075     });
13076     $dbh->do(q{
13077         UPDATE systempreferences SET value="Ireland" WHERE variable="UsageStatsCountry" AND value="Irelanbd";
13078     });
13079     $dbh->do(q{
13080         UPDATE systempreferences SET value="Mexico" WHERE variable="UsageStatsCountry" AND value="México";
13081     });
13082     $dbh->do(q{
13083         UPDATE systempreferences SET value="Peru" WHERE variable="UsageStatsCountry" AND value="Perú";
13084     });
13085     $dbh->do(q{
13086         UPDATE systempreferences SET value="Dominican Rep." WHERE variable="UsageStatsCountry" AND value="República Dominicana";
13087     });
13088     $dbh->do(q{
13089         UPDATE systempreferences SET value="Trinidad & Tob." WHERE variable="UsageStatsCountry" AND value="Trinidad";
13090     });
13091     $dbh->do(q{
13092         UPDATE systempreferences SET value="Turkey" WHERE variable="UsageStatsCountry" AND value="Türkiye";
13093     });
13094     $dbh->do(q{
13095         UPDATE systempreferences SET value="USA" WHERE variable="UsageStatsCountry" AND (value="United States" OR value="United States of America" OR value="US");
13096     });
13097     $dbh->do(q{
13098         UPDATE systempreferences SET value="Zimbabwe" WHERE variable="UsageStatsCountry" AND value="Zimbabbwe";
13099     });
13100
13101     print "Upgrade to $DBversion done (Bug 14707 - Change UsageStatsCountry from free text to a dropdown list)\n";
13102     SetVersion($DBversion);
13103 }
13104
13105 $DBversion = "16.06.00.030";
13106 if ( CheckVersion($DBversion) ) {
13107     $dbh->do(q{
13108         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13109         ('OPACHoldingsDefaultSortField','first_column','first_column|homebranch|holdingbranch','Default sort field for the holdings table at the OPAC','choice');
13110     });
13111
13112     print "Upgrade to $DBversion done (Bug 16552 - Add the ability to change the default holdings sort)\n";
13113     SetVersion($DBversion);
13114 }
13115
13116 $DBversion = "16.06.00.031";
13117 if ( CheckVersion($DBversion) ) {
13118     $dbh->do(q{
13119         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('PatronSelfRegistrationPrefillForm', '1', 'Display password and prefill login form after a patron has self registered', NULL, 'YesNo');
13120     });
13121
13122     print "Upgrade to $DBversion done (Bug 16273 - Prevent selfregistration from printing the borrower password and filling the logging form)\n";
13123     SetVersion($DBversion);
13124 }
13125
13126 $DBversion = "16.06.00.032";
13127 if ( CheckVersion($DBversion) ) {
13128     $dbh->do(q{
13129         UPDATE marc_subfield_structure SET authorised_value="WITHDRAWN" WHERE authorised_value="WTHDRAWN";
13130     });
13131
13132     print "Upgrade to $DBversion done (Bug 17357 - WTHDRAWN is still used in installer files)\n";
13133     SetVersion($DBversion);
13134 }
13135
13136
13137 $DBversion = "16.06.00.033";
13138 if ( CheckVersion($DBversion) ) {
13139     $dbh->do(q{
13140         CREATE TABLE authorised_value_categories (
13141         category_name VARCHAR(32) NOT NULL,
13142         primary key (category_name)
13143         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13144         });
13145 ## Add authorised value categories
13146     $dbh->do(q{
13147     INSERT INTO authorised_value_categories (category_name )
13148     SELECT DISTINCT category FROM authorised_values;
13149     });
13150     
13151 ## Add special categories
13152     $dbh->do(q{
13153     INSERT IGNORE INTO authorised_value_categories( category_name )
13154     VALUES
13155     ('Asort1'),
13156     ('Asort2'),
13157     ('Bsort1'),
13158     ('Bsort2'),
13159     ('SUGGEST'),
13160     ('DAMAGED'),
13161     ('LOST'),
13162     ('REPORT_GROUP'),
13163     ('REPORT_SUBGROUP'),
13164     ('DEPARTMENT'),
13165     ('TERM'),
13166     ('SUGGEST_STATUS'),
13167     ('ITEMTYPECAT');
13168     });
13169
13170 ## Add very special categories
13171     $dbh->do(q{
13172     INSERT IGNORE INTO authorised_value_categories( category_name )
13173     VALUES
13174     ('branches'),
13175     ('itemtypes'),
13176     ('cn_source');
13177     });
13178
13179     $dbh->do(q{
13180     INSERT IGNORE INTO authorised_value_categories( category_name )
13181     VALUES
13182     ('WITHDRAWN'),
13183     ('RESTRICTED'),
13184     ('NOT_LOAN'),
13185     ('CCODE'),
13186     ('LOC'),
13187     ('STACK');
13188     });
13189
13190 ## Update the FK
13191     $dbh->do(q{
13192     ALTER TABLE items_search_fields
13193     DROP FOREIGN KEY items_search_fields_authorised_values_category;
13194     });
13195
13196     $dbh->do(q{
13197     ALTER TABLE items_search_fields
13198     ADD CONSTRAINT `items_search_fields_authorised_values_category` FOREIGN KEY (`authorised_values_category`) REFERENCES `authorised_value_categories` (`category_name`) ON DELETE SET NULL ON UPDATE CASCADE;
13199     });
13200
13201     $dbh->do(q{
13202     ALTER TABLE authorised_values
13203     ADD CONSTRAINT `authorised_values_authorised_values_category` FOREIGN KEY (`category`) REFERENCES `authorised_value_categories` (`category_name`) ON DELETE CASCADE ON UPDATE CASCADE;
13204     });
13205
13206     $dbh->do(q{
13207             INSERT IGNORE INTO authorised_value_categories( category_name ) SELECT DISTINCT(authorised_value) FROM marc_subfield_structure;
13208             });
13209
13210     $dbh->do(q{
13211             UPDATE marc_subfield_structure SET authorised_value = NULL WHERE authorised_value = '';
13212             });
13213
13214     # If the DB has been created before 3.19.00.006, the default collate for marc_subfield_structure if not set to utf8_unicode_ci and the new FK will not be create (MariaDB or MySQL will raise err 150)
13215     my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE marc_subfield_structure|);
13216     $table_sth->execute;
13217     my @table = $table_sth->fetchrow_array;
13218     if ( $table[1] !~ /COLLATE=utf8_unicode_ci/ and $table[1] !~ /COLLATE=utf8mb4_unicode_ci/ ) { #catches utf8mb4 collated tables
13219         $dbh->do(qq|ALTER TABLE marc_subfield_structure CHARACTER SET utf8 COLLATE utf8_unicode_ci|);
13220     }
13221     $dbh->do(q{
13222             ALTER TABLE marc_subfield_structure
13223             MODIFY COLUMN authorised_value VARCHAR(32) DEFAULT NULL,
13224             ADD CONSTRAINT marc_subfield_structure_ibfk_1 FOREIGN KEY (authorised_value) REFERENCES authorised_value_categories (category_name) ON UPDATE CASCADE ON DELETE SET NULL;
13225             });
13226
13227       print "Upgrade to $DBversion done (Bug 17216 - Add a new table to store authorized value categories)\n";
13228       SetVersion($DBversion);
13229 }
13230
13231 $DBversion = "16.06.00.034";
13232 if ( CheckVersion($DBversion) ) {
13233     $dbh->do(q{
13234         ALTER TABLE biblioitems DROP COLUMN marc;
13235     });
13236     $dbh->do(q{
13237         ALTER TABLE deletedbiblioitems DROP COLUMN marc;
13238     });
13239
13240     print "Upgrade to $DBversion done (Bug 10455 - remove redundant 'biblioitems.marc' field)\n";
13241     SetVersion($DBversion);
13242 }
13243
13244 $DBversion = '16.06.00.035';
13245 if ( CheckVersion($DBversion) ) {
13246     $dbh->do(q{
13247         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
13248          SELECT 'AllowItemsOnHoldCheckoutSCO',COALESCE(value,0),'','Do not generate RESERVE_WAITING and RESERVED warning in the SCO module when checking out items reserved to someone else. This allows self checkouts for those items.','YesNo'
13249          FROM systempreferences WHERE variable='AllowItemsOnHoldCheckout';
13250     });
13251
13252     print "Upgrade to $DBversion done (Bug 15131: Give SCO separate control for AllowItemsOnHoldCheckout)\n";
13253     SetVersion($DBversion);
13254 }
13255
13256 $DBversion = '16.06.00.036';
13257 if ( CheckVersion($DBversion) ) {
13258     $dbh->do(q{
13259         CREATE TABLE IF NOT EXISTS `housebound_profile` (
13260           `borrowernumber` int(11) NOT NULL, -- Number of the borrower associated with this profile.
13261           `day` text NOT NULL,  -- The preferred day of the week for delivery.
13262           `frequency` text NOT NULL, -- The Authorised_Value definining the pattern for delivery.
13263           `fav_itemtypes` text default NULL, -- Free text describing preferred itemtypes.
13264           `fav_subjects` text default NULL, -- Free text describing preferred subjects.
13265           `fav_authors` text default NULL, -- Free text describing preferred authors.
13266           `referral` text default NULL, -- Free text indicating how the borrower was added to the service.
13267           `notes` text default NULL, -- Free text for additional notes.
13268           PRIMARY KEY  (`borrowernumber`),
13269           CONSTRAINT `housebound_profile_bnfk`
13270             FOREIGN KEY (`borrowernumber`)
13271             REFERENCES `borrowers` (`borrowernumber`)
13272             ON UPDATE CASCADE ON DELETE CASCADE
13273         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13274     });
13275     $dbh->do(q{
13276         CREATE TABLE IF NOT EXISTS `housebound_visit` (
13277           `id` int(11) NOT NULL auto_increment, -- ID of the visit.
13278           `borrowernumber` int(11) NOT NULL, -- Number of the borrower, & the profile, linked to this visit.
13279           `appointment_date` date default NULL, -- Date of visit.
13280           `day_segment` varchar(10),  -- Rough time frame: 'morning', 'afternoon' 'evening'
13281           `chooser_brwnumber` int(11) default NULL, -- Number of the borrower to choose items  for delivery.
13282           `deliverer_brwnumber` int(11) default NULL, -- Number of the borrower to deliver items.
13283           PRIMARY KEY  (`id`),
13284           CONSTRAINT `houseboundvisit_bnfk`
13285             FOREIGN KEY (`borrowernumber`)
13286             REFERENCES `housebound_profile` (`borrowernumber`)
13287             ON UPDATE CASCADE ON DELETE CASCADE,
13288           CONSTRAINT `houseboundvisit_bnfk_1`
13289             FOREIGN KEY (`chooser_brwnumber`)
13290             REFERENCES `borrowers` (`borrowernumber`)
13291             ON UPDATE CASCADE ON DELETE CASCADE,
13292           CONSTRAINT `houseboundvisit_bnfk_2`
13293             FOREIGN KEY (`deliverer_brwnumber`)
13294             REFERENCES `borrowers` (`borrowernumber`)
13295             ON UPDATE CASCADE ON DELETE CASCADE
13296         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13297     });
13298     $dbh->do(q{
13299         CREATE TABLE IF NOT EXISTS `housebound_role` (
13300           `borrowernumber_id` int(11) NOT NULL, -- borrowernumber link
13301           `housebound_chooser` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound chooser volunteer
13302           `housebound_deliverer` tinyint(1) NOT NULL DEFAULT 0, -- set to 1 to indicate this patron is a housebound deliverer volunteer
13303           PRIMARY KEY (`borrowernumber_id`),
13304           CONSTRAINT `houseboundrole_bnfk`
13305             FOREIGN KEY (`borrowernumber_id`)
13306             REFERENCES `borrowers` (`borrowernumber`)
13307             ON UPDATE CASCADE ON DELETE CASCADE
13308         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13309     });
13310     $dbh->do(q{
13311         INSERT IGNORE INTO systempreferences
13312                (variable,value,options,explanation,type) VALUES
13313                ('HouseboundModule',0,'',
13314                'If ON, enable housebound module functionality.','YesNo');
13315     });
13316     $dbh->do(q{
13317         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES
13318             ('HSBND_FREQ');
13319     });
13320     $dbh->do(q{
13321         INSERT IGNORE INTO authorised_values (category, authorised_value, lib) VALUES
13322                ('HSBND_FREQ','EW','Every week');
13323     });
13324
13325     print "Upgrade to $DBversion done (Bug 5670 - Housebound Readers Module)\n";
13326     SetVersion($DBversion);
13327 }
13328
13329 $DBversion = "16.06.00.037";
13330 if ( CheckVersion($DBversion) ) {
13331     $dbh->do(q{
13332         ALTER TABLE `issuingrules` ADD `article_requests` ENUM( 'no', 'yes', 'bib_only', 'item_only' ) NOT NULL DEFAULT 'no' AFTER `opacitemholds`;
13333     });
13334     $dbh->do(q{
13335         INSERT INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
13336             ('ArticleRequests', '0', NULL, 'Enables the article request feature', 'YesNo'),
13337             ('ArticleRequestsMandatoryFields', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''yes''', 'multiple'),
13338             ('ArticleRequestsMandatoryFieldsItemsOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple'),
13339             ('ArticleRequestsMandatoryFieldsRecordOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''bib_only''', 'multiple');
13340     });
13341     $dbh->do(q{
13342         CREATE TABLE IF NOT EXISTS `article_requests` (
13343           `id` int(11) NOT NULL AUTO_INCREMENT,
13344           `borrowernumber` int(11) NOT NULL,
13345           `biblionumber` int(11) NOT NULL,
13346           `itemnumber` int(11) DEFAULT NULL,
13347           `branchcode` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
13348           `title` text,
13349           `author` text,
13350           `volume` text,
13351           `issue` text,
13352           `date` text,
13353           `pages` text,
13354           `chapters` text,
13355           `patron_notes` text,
13356           `status` enum('PENDING','PROCESSING','COMPLETED','CANCELED') NOT NULL DEFAULT 'PENDING',
13357           `notes` text,
13358           `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
13359           `updated_on` timestamp NULL DEFAULT NULL,
13360           PRIMARY KEY (`id`),
13361           KEY `borrowernumber` (`borrowernumber`),
13362           KEY `biblionumber` (`biblionumber`),
13363           KEY `itemnumber` (`itemnumber`),
13364           KEY `branchcode` (`branchcode`),
13365           CONSTRAINT `article_requests_ibfk_1` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13366           CONSTRAINT `article_requests_ibfk_2` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE,
13367           CONSTRAINT `article_requests_ibfk_3` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE,
13368           CONSTRAINT `article_requests_ibfk_4` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE
13369         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13370     });
13371     $dbh->do(q{
13372         INSERT INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`) VALUES
13373         ('circulation', 'AR_CANCELED', '', 'Article Request - Email - Canceled', 0, 'Article Request Canceled', '<<borrowers.firstname>> <<borrowers.surname>> (<<borrowers.cardnumber>>)\r\n\r\nYour request for an article from <<biblio.title>> (<<items.barcode>>) has been canceled for the following reason:\r\n\r\n<<article_requests.notes>>\r\n\r\nArticle requested:\r\nTitle: <<article_requests.title>>\r\nAuthor: <<article_requests.author>>\r\nVolume: <<article_requests.volume>>\r\nIssue: <<article_requests.issue>>\r\nDate: <<article_requests.date>>\r\nPages: <<article_requests.pages>>\r\nChapters: <<article_requests.chapters>>\r\nNotes: <<article_requests.patron_notes>>\r\n', 'email'),
13374         ('circulation', 'AR_COMPLETED', '', 'Article Request - Email - Completed', 0, 'Article Request Completed', '<<borrowers.firstname>> <<borrowers.surname>> (<<borrowers.cardnumber>>)\r\n\r\nWe are have completed your request for an article from <<biblio.title>> (<<items.barcode>>).\r\n\r\nArticle requested:\r\nTitle: <<article_requests.title>>\r\nAuthor: <<article_requests.author>>\r\nVolume: <<article_requests.volume>>\r\nIssue: <<article_requests.issue>>\r\nDate: <<article_requests.date>>\r\nPages: <<article_requests.pages>>\r\nChapters: <<article_requests.chapters>>\r\nNotes: <<article_requests.patron_notes>>\r\n\r\nYou may pick your article up at <<branches.branchname>>.\r\n\r\nThank you!', 'email'),
13375         ('circulation', 'AR_PENDING', '', 'Article Request - Email - Open', 0, 'Article Request Received', '<<borrowers.firstname>> <<borrowers.surname>> (<<borrowers.cardnumber>>)\r\n\r\nWe have received your request for an article from <<biblio.title>> (<<items.barcode>>).\r\n\r\nArticle requested:\r\nTitle: <<article_requests.title>>\r\nAuthor: <<article_requests.author>>\r\nVolume: <<article_requests.volume>>\r\nIssue: <<article_requests.issue>>\r\nDate: <<article_requests.date>>\r\nPages: <<article_requests.pages>>\r\nChapters: <<article_requests.chapters>>\r\nNotes: <<article_requests.patron_notes>>\r\n\r\n\r\nThank you!', 'email'),
13376         ('circulation', 'AR_SLIP', '', 'Article Request - Print Slip', 0, 'Test', 'Article Request:\r\n\r\n<<borrowers.firstname>> <<borrowers.surname>> (<<borrowers.cardnumber>>)\r\n\r\nTitle: <<biblio.title>>\r\nBarcode: <<items.barcode>>\r\n\r\nArticle requested:\r\nTitle: <<article_requests.title>>\r\nAuthor: <<article_requests.author>>\r\nVolume: <<article_requests.volume>>\r\nIssue: <<article_requests.issue>>\r\nDate: <<article_requests.date>>\r\nPages: <<article_requests.pages>>\r\nChapters: <<article_requests.chapters>>\r\nNotes: <<article_requests.patron_notes>>\r\n', 'print'),
13377         ('circulation', 'AR_PROCESSING', '', 'Article Request - Email - Processing', 0, 'Article Request Processing', '<<borrowers.firstname>> <<borrowers.surname>> (<<borrowers.cardnumber>>)\r\n\r\nWe are now processing your request for an article from <<biblio.title>> (<<items.barcode>>).\r\n\r\nArticle requested:\r\nTitle: <<article_requests.title>>\r\nAuthor: <<article_requests.author>>\r\nVolume: <<article_requests.volume>>\r\nIssue: <<article_requests.issue>>\r\nDate: <<article_requests.date>>\r\nPages: <<article_requests.pages>>\r\nChapters: <<article_requests.chapters>>\r\nNotes: <<article_requests.patron_notes>>\r\n\r\nThank you!', 'email');
13378     });
13379
13380     print "Upgrade to $DBversion done (Bug 14610 - Add ability to place article requests in Koha)\n";
13381     SetVersion($DBversion);
13382 }
13383
13384 $DBversion = '16.06.00.038';
13385 if ( CheckVersion($DBversion) ) {
13386     $dbh->do(q{
13387         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('DefaultPatronSearchFields','surname,firstname,othernames,cardnumber,userid',NULL,'Comma separated list defining the default fields to be used during a patron search','free');
13388     });
13389
13390     print "Upgrade to $DBversion done (Bug 14874 - Add ability to search for patrons by date of birth from checkout and patron quick searches)\n";
13391     SetVersion($DBversion);
13392 }
13393
13394 $DBversion = "16.06.00.039";
13395 if ( CheckVersion($DBversion) ) {
13396
13397     my $sth = $dbh->prepare(q{
13398         SELECT s.itemnumber, i.itype, b.itemtype
13399         FROM
13400          ( SELECT DISTINCT itemnumber
13401            FROM statistics
13402            WHERE ( type = "return" OR type = "localuse" ) AND
13403                  itemtype IS NULL
13404          ) s
13405         LEFT JOIN
13406          ( SELECT itemnumber,biblionumber, itype
13407              FROM items
13408            UNION
13409            SELECT itemnumber,biblionumber, itype
13410              FROM deleteditems
13411          ) i
13412         ON (s.itemnumber=i.itemnumber)
13413         LEFT JOIN
13414          ( SELECT biblionumber, itemtype
13415              FROM biblioitems
13416            UNION
13417            SELECT biblionumber, itemtype
13418              FROM deletedbiblioitems
13419          ) b
13420         ON (i.biblionumber=b.biblionumber);
13421     });
13422     $sth->execute();
13423
13424     my $update_sth = $dbh->prepare(q{
13425         UPDATE statistics
13426         SET itemtype=?
13427         WHERE itemnumber=? AND itemtype IS NULL
13428     });
13429     my $ilevel_itypes = C4::Context->preference('item-level_itypes');
13430
13431     while ( my ($itemnumber,$item_itype,$biblio_itype) = $sth->fetchrow_array ) {
13432
13433         my $effective_itemtype = $ilevel_itypes
13434                                     ? $item_itype // $biblio_itype
13435                                     : $biblio_itype;
13436         warn "item-level_itypes set but no itype defined for item ($itemnumber)"
13437             if $ilevel_itypes and !defined $item_itype;
13438         $update_sth->execute( $effective_itemtype, $itemnumber );
13439     }
13440
13441     print "Upgrade to $DBversion done (Bug 14598: itemtype is not set on statistics by C4::Circulation::AddReturn)\n";
13442     SetVersion($DBversion);
13443 }
13444
13445 $DBversion = '16.06.00.040';
13446 if ( CheckVersion($DBversion) ) {
13447     $dbh->do(q{
13448         ALTER TABLE `aqcontacts` ADD `orderacquisition` BOOLEAN NOT NULL DEFAULT 0 AFTER `notes`;
13449     });
13450     $dbh->do(q{
13451         INSERT IGNORE INTO `letter` (module, code, name, title, content, message_transport_type) VALUES
13452         ('orderacquisition','ACQORDER','Acquisition order','Order','<<aqbooksellers.name>>\r\n<<aqbooksellers.address1>>\r\n<<aqbooksellers.address2>>\r\n<<aqbooksellers.address3>>\r\n<<aqbooksellers.address4>>\r\n<<aqbooksellers.phone>>\r\n\r\nPlease order for the library:\r\n\r\n<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (quantity: <<aqorders.quantity>>) ($<<aqorders.listprice>> each).</order>\r\n\r\nThank you,\n\n<<branches.branchname>>', 'email');
13453     });
13454
13455     print "Upgrade to $DBversion done (Bug 5260 - Add option to send an order by e-mail to the acquisition module)\n";
13456     SetVersion($DBversion);
13457 }
13458
13459 $DBversion = '16.06.00.041';
13460 if ( CheckVersion($DBversion) ) {
13461     $dbh->do(q{
13462         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('AggressiveMatchOnISSN','0','If enabled, attempt to match aggressively by trying all variations of the ISSNs in the imported record as a phrase in the ISSN fields of already cataloged records when matching on ISSN with the record import tool','','YesNo')
13463     });
13464
13465     print "Upgrade to $DBversion done (Bug 14629 - Add aggressive ISSN matching feature equivalent to the aggressive ISBN matcher)\n";
13466     SetVersion($DBversion);
13467 }
13468
13469 $DBversion = '16.06.00.042';
13470 if ( CheckVersion($DBversion) ) {
13471     $dbh->do(q|
13472         ALTER TABLE aqorders
13473             ADD COLUMN unitprice_tax_excluded decimal(28,6) default NULL AFTER unitprice,
13474             ADD COLUMN unitprice_tax_included decimal(28,6) default NULL AFTER unitprice_tax_excluded,
13475             ADD COLUMN rrp_tax_excluded decimal(28,6) default NULL AFTER rrp,
13476             ADD COLUMN rrp_tax_included decimal(28,6) default NULL AFTER rrp_tax_excluded,
13477             ADD COLUMN ecost_tax_excluded decimal(28,6) default NULL AFTER ecost,
13478             ADD COLUMN ecost_tax_included decimal(28,6) default NULL AFTER ecost_tax_excluded,
13479             ADD COLUMN tax_value decimal(6,4) default NULL AFTER gstrate
13480     |);
13481
13482     # rename gstrate with tax_rate
13483     $dbh->do(q|ALTER TABLE aqorders CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13484     $dbh->do(q|ALTER TABLE aqbooksellers CHANGE COLUMN gstrate tax_rate decimal(6,4) DEFAULT NULL|);
13485
13486     # Fill the new columns
13487     my $orders = $dbh->selectall_arrayref(q|
13488         SELECT * FROM aqorders
13489     |, { Slice => {} } );
13490
13491     my $sth_update_order = $dbh->prepare(q|
13492         UPDATE aqorders
13493         SET unitprice_tax_excluded = ?,
13494             unitprice_tax_included = ?,
13495             rrp_tax_excluded = ?,
13496             rrp_tax_included = ?,
13497             ecost_tax_excluded = ?,
13498             ecost_tax_included = ?,
13499             tax_value = ?
13500         WHERE ordernumber = ?
13501     |);
13502
13503     my $sth_get_bookseller = $dbh->prepare(q|
13504         SELECT aqbooksellers.*
13505         FROM aqbooksellers
13506         LEFT JOIN aqbasket ON aqbasket.booksellerid = aqbooksellers.id
13507         LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
13508         WHERE ordernumber = ?
13509     |);
13510
13511     require Number::Format;
13512     my $format = Number::Format->new;
13513     my $precision = 2;
13514     for my $order ( @$orders ) {
13515         $sth_get_bookseller->execute( $order->{ordernumber} );
13516         my ( $bookseller ) = $sth_get_bookseller->fetchrow_hashref;
13517         $order->{rrp}   = $format->round( $order->{rrp}, $precision );
13518         $order->{ecost} = $format->round( $order->{ecost}, $precision );
13519         $order->{tax_rate} ||= 0 ; # tax_rate can be NULL in DB
13520         # Ordering
13521         if ( $bookseller->{listincgst} ) {
13522             $order->{rrp_tax_included} = $order->{rrp};
13523             $order->{rrp_tax_excluded} = $format->round(
13524                 $order->{rrp_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13525             $order->{ecost_tax_included} = $order->{ecost};
13526             $order->{ecost_tax_excluded} = $format->round(
13527                 $order->{ecost} / ( 1 + $order->{tax_rate} ), $precision );
13528         }
13529         else {
13530             $order->{rrp_tax_excluded} = $order->{rrp};
13531             $order->{rrp_tax_included} = $format->round(
13532                 $order->{rrp} * ( 1 + $order->{tax_rate} ), $precision );
13533             $order->{ecost_tax_excluded} = $order->{ecost};
13534             $order->{ecost_tax_included} = $format->round(
13535                 $order->{ecost} * ( 1 + $order->{tax_rate} ), $precision );
13536         }
13537
13538         #receiving
13539         if ( $bookseller->{listincgst} ) {
13540             $order->{unitprice_tax_included} = $format->round( $order->{unitprice}, $precision );
13541             $order->{unitprice_tax_excluded} = $format->round(
13542               $order->{unitprice_tax_included} / ( 1 + $order->{tax_rate} ), $precision );
13543         }
13544         else {
13545             $order->{unitprice_tax_excluded} = $format->round( $order->{unitprice}, $precision );
13546             $order->{unitprice_tax_included} = $format->round(
13547               $order->{unitprice_tax_excluded} * ( 1 + $order->{tax_rate} ), $precision );
13548         }
13549
13550         # If the order is received, the tax is calculated from the unit price
13551         if ( $order->{orderstatus} eq 'complete' ) {
13552             $order->{tax_value} = $format->round(
13553               ( $order->{unitprice_tax_included} - $order->{unitprice_tax_excluded} )
13554               * $order->{quantity}, $precision );
13555         } else {
13556             # otherwise the ecost is used
13557             $order->{tax_value} = $format->round(
13558                 ( $order->{ecost_tax_included} - $order->{ecost_tax_excluded} ) *
13559                   $order->{quantity}, $precision );
13560         }
13561
13562         $sth_update_order->execute(
13563             $order->{unitprice_tax_excluded},
13564             $order->{unitprice_tax_included},
13565             $order->{rrp_tax_excluded},
13566             $order->{rrp_tax_included},
13567             $order->{ecost_tax_excluded},
13568             $order->{ecost_tax_included},
13569             $order->{tax_value},
13570             $order->{ordernumber},
13571         );
13572     }
13573
13574     print "Upgrade to $DBversion done (Bug 13321 - Tax and prices calculation need to be fixed)\n";
13575     SetVersion($DBversion);
13576 }
13577
13578 $DBversion = '16.06.00.043';
13579 if ( CheckVersion($DBversion) ) {
13580     # Add the new columns
13581     $dbh->do(q|
13582         ALTER TABLE aqorders
13583             ADD COLUMN tax_rate_on_ordering   decimal(6,4) default NULL AFTER tax_rate,
13584             ADD COLUMN tax_rate_on_receiving  decimal(6,4) default NULL AFTER tax_rate_on_ordering,
13585             ADD COLUMN tax_value_on_ordering  decimal(28,6) default NULL AFTER tax_value,
13586             ADD COLUMN tax_value_on_receiving decimal(28,6) default NULL AFTER tax_value_on_ordering
13587     |);
13588
13589     my $orders = $dbh->selectall_arrayref(q|
13590         SELECT * FROM aqorders
13591     |, { Slice => {} } );
13592
13593     my $sth_update_order = $dbh->prepare(q|
13594         UPDATE aqorders
13595         SET tax_rate_on_ordering = tax_rate,
13596             tax_rate_on_receiving = tax_rate,
13597             tax_value_on_ordering = ?,
13598             tax_value_on_receiving = ?
13599         WHERE ordernumber = ?
13600     |);
13601
13602     for my $order (@$orders) {
13603         my $tax_value_on_ordering =
13604           $order->{quantity} *
13605           $order->{ecost_tax_excluded} *
13606           $order->{tax_rate};
13607
13608         my $tax_value_on_receiving =
13609           ( defined $order->{unitprice_tax_excluded} )
13610           ? $order->{quantity} * $order->{unitprice_tax_excluded} * $order->{tax_rate}
13611           : undef;
13612
13613         $sth_update_order->execute( $tax_value_on_ordering,
13614             $tax_value_on_receiving, $order->{ordernumber} );
13615     }
13616
13617     # Remove the old columns
13618     $dbh->do(q|
13619         ALTER TABLE aqorders
13620             CHANGE COLUMN tax_value tax_value_bak  decimal(28,6) default NULL,
13621             CHANGE COLUMN tax_rate tax_rate_bak decimal(6,4) default NULL
13622     |);
13623
13624     print "Upgrade to $DBversion done (Bug 13323 - Change the tax rate on receiving)\n";
13625     SetVersion($DBversion);
13626 }
13627
13628 $DBversion = '16.06.00.044';
13629 if ( CheckVersion($DBversion) ) {
13630     $dbh->do(q{
13631         ALTER TABLE `messages`
13632         ADD `manager_id` int(11) NULL,
13633         ADD FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL;
13634     });
13635
13636     print "Upgrade to $DBversion done (Bug 17397 - Show name of librarian who created circulation message)\n";
13637     SetVersion($DBversion);
13638 }
13639
13640 $DBversion = '16.06.00.045';
13641 if ( CheckVersion($DBversion) ) {
13642     $dbh->do(q{
13643         UPDATE systempreferences SET options = "now|dateexpiry|combination", explanation = "Set whether the borrower renewal date should be counted from the dateexpiry, from the current date or by combination: if the dateexpiry is in future use dateexpiry, else use current date " WHERE variable = "BorrowerRenewalPeriodBase";
13644     });
13645
13646     print "Upgrade to $DBversion done (Bug 17443 - Make possible to renew patron by later of expiry and current date)\n";
13647     SetVersion($DBversion);
13648 }
13649
13650 $DBversion = '16.06.00.046';
13651 if ( CheckVersion($DBversion) ) {
13652     $dbh->do(q{
13653         ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after INT(4) DEFAULT NULL AFTER auto_renew;
13654     });
13655
13656     print "Upgrade to $DBversion done (Bug 15581 - Add a circ rule to not allow auto-renewals after defined loan period)\n";
13657     SetVersion($DBversion);
13658 }
13659
13660 $DBversion = '16.06.00.047';
13661 if ( CheckVersion($DBversion) ) {
13662     $dbh->do(q{
13663         UPDATE language_descriptions SET description = 'Čeština' WHERE subtag = 'cs' AND type = 'language' AND lang = 'cs'
13664     });
13665
13666     print "Upgrade to $DBversion done (Bug 17518: Displayed language name for Czech is wrong)\n";
13667     SetVersion($DBversion);
13668 }
13669
13670 $DBversion = '16.06.00.048';
13671 if( CheckVersion( $DBversion ) ) {
13672     $dbh->do(q|
13673         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
13674         (13, 'upload_general_files', 'Upload any file'),
13675         (13, 'upload_manage', 'Manage uploaded files');
13676     |);
13677
13678     # Update user_permissions for current users (check count in uploaded_files)
13679     # Note 9 == edit_catalogue and 13 == tools
13680     # We do not insert if someone is superlibrarian, does not have edit_catalogue,
13681     # or already has all tools
13682     $dbh->do(q|
13683         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
13684         SELECT borrowernumber, 13, 'upload_general_files'
13685         FROM borrowers bo
13686         WHERE flags<>1 AND flags & POW(2,13) = 0 AND
13687             ( flags & POW(2,9) > 0 OR (
13688                 SELECT COUNT(*) FROM user_permissions
13689                 WHERE borrowernumber=bo.borrowernumber AND module_bit=9 ) > 0 )
13690             AND ( SELECT COUNT(*) FROM uploaded_files ) > 0;
13691     |);
13692
13693     SetVersion( $DBversion );
13694     print "Upgrade to $DBversion done (Bug 17663 - Forgotten userpermissions)\n";
13695 }
13696
13697 $DBversion = '16.06.00.049';
13698 if( CheckVersion( $DBversion ) ) {
13699     $dbh->do(q|
13700         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
13701         VALUES ('ReplytoDefault',  '',  NULL,  'The default email address to be set as replyto.',  'Free');
13702     |);
13703
13704     $dbh->do(q|
13705         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
13706         VALUES ('ReturnpathDefault',  '',  NULL,  'The default email address to be set as return-path',  'Free');
13707     |);
13708
13709     SetVersion( $DBversion );
13710     print "Upgrade to $DBversion done (Bug 17391 - ReturnpathDefault and ReplyToDefault missing from syspref.sql)\n";
13711 }
13712
13713 $DBversion = "16.06.00.050";
13714 if ( CheckVersion($DBversion) ) {
13715
13716     # If index issn_idx still exists, we assume that dbrev 3.15.00.049 failed,
13717     # and we repeat it (partially).
13718     # Note: the db rev only pertains to biblioitems and is not needed for
13719     # deletedbiblioitems.
13720
13721     my $temp = $dbh->selectall_arrayref( "SHOW INDEXES FROM biblioitems WHERE key_name = 'issn_idx'" );
13722
13723     if( @$temp > 0 ) {
13724         $dbh->do( "ALTER TABLE biblioitems DROP INDEX isbn" );
13725         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn" );
13726         $dbh->do( "ALTER TABLE biblioitems DROP INDEX issn_idx" );
13727         $dbh->do( "ALTER TABLE biblioitems CHANGE isbn isbn MEDIUMTEXT NULL DEFAULT NULL, CHANGE issn issn MEDIUMTEXT NULL DEFAULT NULL" );
13728         $dbh->do( "ALTER TABLE biblioitems ADD INDEX isbn ( isbn ( 255 ) ), ADD INDEX issn ( issn ( 255 ) )" );
13729         print "Upgrade to $DBversion done (Bug 8835). Removed issn_idx.\n";
13730     } else {
13731         print "Upgrade to $DBversion done (Bug 8835). Everything is fine.\n";
13732     }
13733
13734     SetVersion($DBversion);
13735 }
13736
13737 $DBversion = "16.11.00.000";
13738 if ( CheckVersion($DBversion) ) {
13739     print "Upgrade to $DBversion done (Koha 16.11)\n";
13740     SetVersion($DBversion);
13741 }
13742
13743 $DBversion = "16.12.00.000";
13744 if ( CheckVersion($DBversion) ) {
13745     print "Upgrade to $DBversion done (Koha 16.12 - Our battered suitcases were piled on the sidewalk again; we had longer ways to go. But no matter, the road is life.)\n";
13746     SetVersion($DBversion);
13747 }
13748
13749 $DBversion = "16.12.00.001";
13750 if ( CheckVersion($DBversion) ) {
13751     $dbh->do(q{
13752         ALTER TABLE borrower_modifications
13753         ADD COLUMN extended_attributes text DEFAULT NULL
13754         AFTER privacy
13755     });
13756
13757     print "Upgrade to $DBversion done (Bug 17767 - Let Koha::Patron::Modification handle extended attributes)\n";
13758     SetVersion($DBversion);
13759 }
13760
13761 $DBversion = '16.12.00.002';
13762 if ( CheckVersion($DBversion) ) {
13763     unless (column_exists( 'branchtransfers', 'branchtransfer_id' )
13764         and index_exists( 'branchtransfers', 'PRIMARY' ) )
13765     {
13766         $dbh->do(
13767             "ALTER TABLE branchtransfers
13768                  ADD COLUMN branchtransfer_id int(12) NOT NULL auto_increment FIRST, ADD CONSTRAINT PRIMARY KEY (branchtransfer_id);"
13769         );
13770     }
13771
13772     SetVersion($DBversion);
13773     print "Upgrade to $DBversion done (Bug 14187 - branchtransfer needs a primary key (id) for DBIx and common sense.)\n";
13774 }
13775
13776 $DBversion = '16.12.00.003';
13777 if ( CheckVersion($DBversion) ) {
13778     $dbh->do(q{DELETE FROM systempreferences WHERE variable="Persona"});
13779     SetVersion($DBversion);
13780     print "Upgrade to $DBversion done (Bug 17486 - Remove 'Mozilla Persona' as an authentication method)\n";
13781 }
13782
13783 $DBversion = '16.12.00.004';
13784 if ( CheckVersion($DBversion) ) {
13785     $dbh->do(q{
13786         CREATE TABLE biblio_metadata (
13787             `id` INT(11) NOT NULL AUTO_INCREMENT,
13788             `biblionumber` INT(11) NOT NULL,
13789             `format` VARCHAR(16) NOT NULL,
13790             `marcflavour` VARCHAR(16) NOT NULL,
13791             `metadata` LONGTEXT NOT NULL,
13792             PRIMARY KEY(id),
13793             UNIQUE KEY `biblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13794             CONSTRAINT `biblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13795         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13796     });
13797     $dbh->do(q{
13798         CREATE TABLE deletedbiblio_metadata (
13799             `id` INT(11) NOT NULL AUTO_INCREMENT,
13800             `biblionumber` INT(11) NOT NULL,
13801             `format` VARCHAR(16) NOT NULL,
13802             `marcflavour` VARCHAR(16) NOT NULL,
13803             `metadata` LONGTEXT NOT NULL,
13804             PRIMARY KEY(id),
13805             UNIQUE KEY `deletedbiblio_metadata_uniq_key` (`biblionumber`,`format`,`marcflavour`),
13806             CONSTRAINT `deletedbiblio_metadata_fk_1` FOREIGN KEY (biblionumber) REFERENCES deletedbiblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
13807         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
13808     });
13809     $dbh->do(q{
13810         INSERT INTO biblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM biblioitems;
13811     });
13812     $dbh->do(q{
13813         INSERT INTO deletedbiblio_metadata ( biblionumber, format, marcflavour, metadata ) SELECT biblionumber, 'marcxml', 'CHANGEME', marcxml FROM deletedbiblioitems;
13814     });
13815     $dbh->do(q{
13816         UPDATE biblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13817     });
13818     $dbh->do(q{
13819         UPDATE deletedbiblio_metadata SET marcflavour = (SELECT value FROM systempreferences WHERE variable="marcflavour");
13820     });
13821     $dbh->do(q{
13822         ALTER TABLE biblioitems DROP COLUMN marcxml;
13823     });
13824     $dbh->do(q{
13825         ALTER TABLE deletedbiblioitems DROP COLUMN marcxml;
13826     });
13827     SetVersion($DBversion);
13828     print "Upgrade to $DBversion done (Bug 17196 - Move marcxml out of the biblioitems table)\n";
13829 }
13830
13831 $DBversion = '16.12.00.005';
13832 if( CheckVersion( $DBversion ) ) {
13833     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES('AuthorityMergeMode','loose','loose|strict','Authority merge mode','Choice')");
13834
13835     SetVersion( $DBversion );
13836     print "Upgrade to $DBversion done (Bug 17913 - AuthorityMergeMode)\n";
13837 }
13838
13839 $DBversion = "16.12.00.006";
13840 if ( CheckVersion($DBversion) ) {
13841     unless (     column_exists( 'borrower_attributes', 'id' )
13842              and index_exists( 'borrower_attributes', 'PRIMARY' ) )
13843     {
13844         $dbh->do(q{
13845             ALTER TABLE `borrower_attributes`
13846                 ADD `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
13847         });
13848     }
13849
13850     print "Upgrade to $DBversion done (Bug 17813: Table borrower_attributes needs a primary key\n";
13851     SetVersion($DBversion);
13852 }
13853
13854 $DBversion = "16.12.00.007";
13855 if( CheckVersion( $DBversion ) ) {
13856
13857     if ( column_exists('opac_news', 'new' ) ) {
13858         $dbh->do(q|ALTER TABLE opac_news CHANGE COLUMN new content text NOT NULL|);
13859     }
13860
13861     $dbh->do(q|
13862         UPDATE letter SET content = REPLACE(content, "<<opac_news.new>>", "<<opac_news.content>>") WHERE content LIKE "%<<opac_news.new>>%"
13863     |);
13864
13865     SetVersion( $DBversion );
13866     print "Upgrade to $DBversion done (Bug 17960 - Rename opac_news with opac_news.content (template notices have been updated!))\n";
13867 }
13868
13869 $DBversion = "16.12.00.008";
13870 if( CheckVersion( $DBversion ) ) {
13871     $dbh->do(q{
13872         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13873         ('MarcItemFieldsToOrder','','Set the mapping values for new item records created from a MARC record in a staged file. In a YAML format.', NULL, 'textarea');
13874     });
13875
13876     SetVersion( $DBversion );
13877     print "Upgrade to $DBversion done (Bug 15503 - Grab Item Information from Order Files)\n";
13878 }
13879
13880 $DBversion = "16.12.00.009";
13881 if( CheckVersion( $DBversion ) ) {
13882     $dbh->do(q{
13883         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13884         ('OPACHoldsIfAvailableAtPickup','1','','Allow to pickup up holds at libraries where the item is available','YesNo');
13885     });
13886
13887     $dbh->do(q{
13888         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
13889         ('OPACHoldsIfAvailableAtPickupExceptions','','','List the patron categories not affected by OPACHoldsIfAvailableAtPickup if off','Free');
13890     });
13891
13892     SetVersion( $DBversion );
13893     print "Upgrade to $DBversion done (Bug 17453 - Inter-site holds improvement)\n";
13894 }
13895
13896 $DBversion = "16.12.00.010";
13897 if( CheckVersion( $DBversion ) ) {
13898     $dbh->do(q{
13899         ALTER TABLE borrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13900     });
13901
13902     $dbh->do(q{
13903         ALTER TABLE deletedborrowers ADD overdrive_auth_token text default NULL AFTER lastseen;
13904     });
13905
13906     $dbh->do(q{
13907         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
13908         VALUES ('OverDriveCirculation','0','Enable client to see their OverDrive account','','YesNo');
13909     });
13910
13911     SetVersion( $DBversion );
13912     print "Upgrade to $DBversion done (Bug 16034 - Integration with OverDrive Patron API)\n";
13913 }
13914
13915 $DBversion = "16.12.00.011";
13916 if( CheckVersion( $DBversion ) ) {
13917     $dbh->do(q{
13918         ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum') NOT NULL
13919         COMMENT 'what type of data this holds, relevant when storing it in the search engine';
13920     });
13921
13922     SetVersion( $DBversion );
13923     print "Upgrade to $DBversion done (Bug 17260 - updatedatabase.pl fails on invalid entries in ENUM and BOOLEAN columns)\n";
13924 }
13925
13926 $DBversion = "16.12.00.012";
13927 if( CheckVersion( $DBversion ) ) {
13928     $dbh->do(q{
13929         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`)
13930         VALUES ('OpacNewsLibrarySelect', '0', '', 'Show selector for branches on OPAC news page', 'YesNo');
13931     });
13932
13933     SetVersion( $DBversion );
13934     print "Upgrade to $DBversion done (Bug 14764 - Add OPAC News branch selector)\n";
13935 }
13936
13937 $DBversion = "16.12.00.013";
13938 if( CheckVersion( $DBversion ) ) {
13939     $dbh->do(q{
13940         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
13941         VALUES ('CircSidebar','0','','Activate or deactivate the navigation sidebar on all Circulation pages','YesNo');
13942     });
13943
13944     SetVersion( $DBversion );
13945     print "Upgrade to $DBversion done (Bug 16530 - Add a circ sidebar navigation menu)\n";
13946 }
13947
13948 $DBversion = "16.12.00.014";
13949 if( CheckVersion( $DBversion ) ) {
13950     $dbh->do(q{
13951             INSERT INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
13952             ('LoadSearchHistoryToTheFirstLoggedUser', '1', NULL, 'If ON, the next user will automatically get the last searches in his history', 'YesNo');
13953             });
13954             SetVersion( $DBversion );
13955             print "Upgrade to $DBversion done (Bug 8010 - Search history can be added to the wrong patron)\n";
13956             }
13957
13958 $DBversion = "16.12.00.015";
13959 if( CheckVersion( $DBversion ) ) {
13960     unless( column_exists( 'branches', 'geolocation' ) ) {
13961         $dbh->do(q|
13962                 ALTER TABLE branches ADD COLUMN geolocation VARCHAR(255) DEFAULT NULL after opac_info
13963                 |);
13964     }
13965
13966     $dbh->do(q|
13967             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsGeolocation', '', NULL, 'Geolocation of the main library', 'Free');
13968             |);
13969     $dbh->do(q|
13970             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsLibrariesInfo', '', NULL, 'Share libraries information', 'YesNo');
13971             |);
13972     $dbh->do(q|
13973             INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type ) VALUES ('UsageStatsPublicID', '', NULL, 'Public ID for Hea website', 'Free');
13974             |);
13975         
13976         SetVersion( $DBversion );
13977     print "Upgrade to $DBversion done (Bug 18066 - Hea version 2)\n";
13978 }
13979
13980 $DBversion = "16.12.00.016";
13981 if ( CheckVersion($DBversion) ) {
13982     unless ( column_exists( 'borrower_attribute_types', 'opac_editable' ) )
13983     {
13984         $dbh->do(q{
13985             ALTER TABLE borrower_attribute_types
13986                 ADD COLUMN `opac_editable` tinyint(1) NOT NULL default 0 AFTER `opac_display`
13987         });
13988     }
13989
13990     print "Upgrade to $DBversion done (Bug 13757: Make patron attributes editable in the opac if set to 'editable in OPAC)'\n";
13991     SetVersion($DBversion);
13992 }
13993
13994 $DBversion = "16.12.00.017";
13995 if ( CheckVersion($DBversion) ) {
13996     $dbh->do(q{
13997         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
13998         VALUES ('CumulativeRestrictionPeriods',  0,  NULL,  'Cumulate the restriction periods instead of keeping the highest',  'YesNo')
13999     });
14000
14001     print "Upgrade to $DBversion done (Bug 14146 - Additional days are not added to restriction period when checking-in several overdues for same patron)'\n";
14002     SetVersion($DBversion);
14003 }
14004
14005 $DBversion = "16.12.00.018";
14006 if ( CheckVersion($DBversion) ) {
14007     $dbh->do(q{
14008         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type )
14009             SELECT 'ExportCircHistory', COUNT(*), NULL, "Display the export circulation options",  'YesNo'
14010             FROM systempreferences
14011             WHERE ( variable = 'ExportRemoveFields' AND value != "" AND value IS NOT NULL )
14012                 OR ( variable = 'ExportWithCsvProfile' AND value != "" AND value IS NOT NULL );
14013     });
14014
14015     $dbh->do(q{
14016         DELETE FROM systempreferences WHERE variable="ExportWithCsvProfile";
14017     });
14018
14019     print "Upgrade to $DBversion done (Bug 15498 - Replace ExportWithCsvProfile with ExportCircHistory)'\n";
14020     SetVersion($DBversion);
14021 }
14022
14023 $DBversion = "16.12.00.019";
14024 if( CheckVersion( $DBversion ) ) {
14025     if ( column_exists( 'issues', 'return' ) ) {
14026         $dbh->do(q|ALTER TABLE issues DROP column `return`|);
14027     }
14028
14029     if ( column_exists( 'old_issues', 'return' ) ) {
14030         $dbh->do(q|ALTER TABLE old_issues DROP column `return`|);
14031     }
14032
14033     SetVersion( $DBversion );
14034     print "Upgrade to $DBversion done (Bug 18173 - Remove issues.return DB field)\n";
14035 }
14036
14037 $DBversion = "16.12.00.020";
14038 if( CheckVersion( $DBversion ) ) {
14039     $dbh->do(q{
14040         UPDATE systempreferences SET options="any_time_is_placed|not_always|any_time_is_collected" WHERE variable="HoldFeeMode";
14041     });
14042
14043     $dbh->do(q{
14044         UPDATE systempreferences SET value="any_time_is_placed" WHERE variable="HoldFeeMode" AND value="always";
14045     });
14046
14047     SetVersion( $DBversion );
14048     print "Upgrade to $DBversion done (Bug 17560 - Hold fee placement at point of checkout)\n";
14049 }
14050
14051 $DBversion = "16.12.00.021";
14052 if( CheckVersion( $DBversion ) ) {
14053     $dbh->do(q{
14054         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14055         ('RenewalLog','0','','If ON, log information about renewals','YesNo');
14056     });
14057
14058     SetVersion( $DBversion );
14059     print "Upgrade to $DBversion done (Bug 17708 - Renewal log seems empty)\n";
14060 }
14061
14062 $DBversion = "16.12.00.022";
14063 if( CheckVersion( $DBversion ) ) {
14064     print "NOTE: The sender for claim notifications has been corrected. The email address of the staff member is no longer used. We will use the branch email address or KohaAdminEmailAddress, as is done for other notices.\n";
14065     SetVersion( $DBversion );
14066     print "Upgrade to $DBversion done (Bug 17866 - Change sender for serial claim notifications)\n";
14067 }
14068
14069 $DBversion = '16.12.00.023';
14070 if( CheckVersion( $DBversion ) ) {
14071     my $oldval = C4::Context->preference('dontmerge');
14072     my $newval = $oldval ? 0 : 50;
14073
14074     # Remove dontmerge, add AuthorityMergeLimit
14075     $dbh->do(q{
14076         DELETE FROM systempreferences WHERE variable = 'dontmerge';
14077     });
14078     $dbh->do(qq{
14079         INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('AuthorityMergeLimit','$newval',NULL,'Maximum number of biblio records updated immediately when an authority record has been modified.','integer');
14080     });
14081
14082     $dbh->do(q{
14083         ALTER TABLE need_merge_authorities
14084             ADD COLUMN authid_new BIGINT AFTER authid,
14085             ADD COLUMN reportxml text AFTER authid_new,
14086             ADD COLUMN timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
14087     });
14088
14089     $dbh->do(q{
14090         UPDATE need_merge_authorities SET authid_new=authid WHERE done <> 1
14091     });
14092
14093     SetVersion( $DBversion );
14094     if( $newval == 0 ) {
14095         print "NOTE: Since dontmerge was enabled, we have initialized AuthorityMergeLimit to 0 records. Please consider raising this value. This will allow for performing smaller merges directly and only postponing larger merges.\n";
14096     }
14097     print "IMPORTANT NOTE: If you are not using a Debian package install, please verify that you no longer use misc/migration_tools/merge_authority.pl in your cron files AND add misc/cronjobs/merge_authorities.pl to cron now. This job is no longer optional! You need it to perform larger authority merges.\n";
14098     print "Upgrade to $DBversion done (Bug 9988 - Add AuthorityMergeLimit)\n";
14099 }
14100
14101 $DBversion = '16.12.00.024';
14102 if( CheckVersion( $DBversion ) ) {
14103     $dbh->do(q{
14104         UPDATE systempreferences SET variable="NoticeBcc" WHERE variable="OverdueNoticeBcc";
14105     });
14106
14107     SetVersion( $DBversion );
14108     print "Upgrade to $DBversion done (Bug 14537 - The system preference 'OverdueNoticeBcc' is mis-named.)\n";
14109 }
14110
14111 $DBversion = '16.12.00.025';
14112 if( CheckVersion( $DBversion ) ) {
14113     $dbh->do(q|
14114         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14115         VALUES ('UploadPurgeTemporaryFilesDays','',NULL,'If not empty, number of days used when automatically deleting temporary uploads','integer');
14116     |);
14117
14118     my ( $cnt ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM uploaded_files WHERE permanent IS NULL or permanent=0" );
14119     if( $cnt ) {
14120         print "NOTE: You have $cnt temporary uploads. You could benefit from setting pref UploadPurgeTemporaryFilesDays now to automatically delete them.\n";
14121     }
14122
14123     SetVersion( $DBversion );
14124     print "Upgrade to $DBversion done (Bug 17669 - Introduce preference for deleting temporary uploads)\n";
14125 }
14126
14127 $DBversion = '16.12.00.026';
14128 if( CheckVersion( $DBversion ) ) {
14129
14130     # In order to be overcomplete, we check if the situation is what we expect
14131     if( !index_exists( 'serialitems', 'PRIMARY' ) ) {
14132         if( index_exists( 'serialitems', 'serialitemsidx' ) ) {
14133             $dbh->do(q|
14134                 ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber), DROP INDEX serialitemsidx;
14135             |);
14136         } else {
14137             $dbh->do(q|ALTER TABLE serialitems ADD PRIMARY KEY (itemnumber)|);
14138         }
14139     }
14140
14141     SetVersion( $DBversion );
14142     print "Upgrade to $DBversion done (Bug 18427 - Add a primary key to serialitems)\n";
14143 }
14144
14145 $DBversion = '16.12.00.027';
14146 if( CheckVersion( $DBversion ) ) {
14147
14148     $dbh->do(q{
14149         CREATE TABLE IF NOT EXISTS club_templates (
14150           id int(11) NOT NULL AUTO_INCREMENT,
14151           `name` tinytext NOT NULL,
14152           description text,
14153           is_enrollable_from_opac tinyint(1) NOT NULL DEFAULT '0',
14154           is_email_required tinyint(1) NOT NULL DEFAULT '0',
14155           branchcode varchar(10) NULL DEFAULT NULL,
14156           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14157           date_updated timestamp NULL DEFAULT NULL,
14158           is_deletable tinyint(1) NOT NULL DEFAULT '1',
14159           PRIMARY KEY (id),
14160           KEY ct_branchcode (branchcode),
14161           CONSTRAINT `club_templates_ibfk_1` FOREIGN KEY (branchcode) REFERENCES `branches` (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
14162         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14163     });
14164
14165     $dbh->do(q{
14166         CREATE TABLE IF NOT EXISTS clubs (
14167           id int(11) NOT NULL AUTO_INCREMENT,
14168           club_template_id int(11) NOT NULL,
14169           `name` tinytext NOT NULL,
14170           description text,
14171           date_start date DEFAULT NULL,
14172           date_end date DEFAULT NULL,
14173           branchcode varchar(10) NULL DEFAULT NULL,
14174           date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14175           date_updated timestamp NULL DEFAULT NULL,
14176           PRIMARY KEY (id),
14177           KEY club_template_id (club_template_id),
14178           KEY branchcode (branchcode),
14179           CONSTRAINT clubs_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE,
14180           CONSTRAINT clubs_ibfk_2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode)
14181         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14182     });
14183
14184     $dbh->do(q{
14185         CREATE TABLE IF NOT EXISTS club_enrollments (
14186           id int(11) NOT NULL AUTO_INCREMENT,
14187           club_id int(11) NOT NULL,
14188           borrowernumber int(11) NOT NULL,
14189           date_enrolled timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
14190           date_canceled timestamp NULL DEFAULT NULL,
14191           date_created timestamp NULL DEFAULT NULL,
14192           date_updated timestamp NULL DEFAULT NULL,
14193           branchcode varchar(10) NULL DEFAULT NULL,
14194           PRIMARY KEY (id),
14195           KEY club_id (club_id),
14196           KEY borrowernumber (borrowernumber),
14197           KEY branchcode (branchcode),
14198           CONSTRAINT club_enrollments_ibfk_1 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE,
14199           CONSTRAINT club_enrollments_ibfk_2 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
14200           CONSTRAINT club_enrollments_ibfk_3 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE
14201         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14202     });
14203
14204     $dbh->do(q{
14205         CREATE TABLE IF NOT EXISTS club_template_enrollment_fields (
14206           id int(11) NOT NULL AUTO_INCREMENT,
14207           club_template_id int(11) NOT NULL,
14208           `name` tinytext NOT NULL,
14209           description text,
14210           authorised_value_category varchar(16) DEFAULT NULL,
14211           PRIMARY KEY (id),
14212           KEY club_template_id (club_template_id),
14213           CONSTRAINT club_template_enrollment_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14214         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14215     });
14216
14217     $dbh->do(q{
14218         CREATE TABLE IF NOT EXISTS club_enrollment_fields (
14219           id int(11) NOT NULL AUTO_INCREMENT,
14220           club_enrollment_id int(11) NOT NULL,
14221           club_template_enrollment_field_id int(11) NOT NULL,
14222           `value` text NOT NULL,
14223           PRIMARY KEY (id),
14224           KEY club_enrollment_id (club_enrollment_id),
14225           KEY club_template_enrollment_field_id (club_template_enrollment_field_id),
14226           CONSTRAINT club_enrollment_fields_ibfk_1 FOREIGN KEY (club_enrollment_id) REFERENCES club_enrollments (id) ON DELETE CASCADE ON UPDATE CASCADE,
14227           CONSTRAINT club_enrollment_fields_ibfk_2 FOREIGN KEY (club_template_enrollment_field_id) REFERENCES club_template_enrollment_fields (id) ON DELETE CASCADE ON UPDATE CASCADE
14228         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14229     });
14230
14231     $dbh->do(q{
14232         CREATE TABLE IF NOT EXISTS club_template_fields (
14233           id int(11) NOT NULL AUTO_INCREMENT,
14234           club_template_id int(11) NOT NULL,
14235           `name` tinytext NOT NULL,
14236           description text,
14237           authorised_value_category varchar(16) DEFAULT NULL,
14238           PRIMARY KEY (id),
14239           KEY club_template_id (club_template_id),
14240           CONSTRAINT club_template_fields_ibfk_1 FOREIGN KEY (club_template_id) REFERENCES club_templates (id) ON DELETE CASCADE ON UPDATE CASCADE
14241         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14242     });
14243
14244     $dbh->do(q{
14245         CREATE TABLE IF NOT EXISTS club_fields (
14246           id int(11) NOT NULL AUTO_INCREMENT,
14247           club_template_field_id int(11) NOT NULL,
14248           club_id int(11) NOT NULL,
14249           `value` text,
14250           PRIMARY KEY (id),
14251           KEY club_template_field_id (club_template_field_id),
14252           KEY club_id (club_id),
14253           CONSTRAINT club_fields_ibfk_3 FOREIGN KEY (club_template_field_id) REFERENCES club_template_fields (id) ON DELETE CASCADE ON UPDATE CASCADE,
14254           CONSTRAINT club_fields_ibfk_4 FOREIGN KEY (club_id) REFERENCES clubs (id) ON DELETE CASCADE ON UPDATE CASCADE
14255         ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14256     });
14257
14258     $dbh->do(q{
14259         INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (21, 'clubs', 'Patron clubs', '0');
14260     });
14261
14262     $dbh->do(q{
14263         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
14264            (21, 'edit_templates', 'Create and update club templates'),
14265            (21, 'edit_clubs', 'Create and update clubs'),
14266            (21, 'enroll', 'Enroll patrons in clubs')
14267         ;
14268     });
14269
14270     SetVersion( $DBversion );
14271     print "Upgrade to $DBversion done (Bug 12461 - Add patron clubs feature)\n";
14272 }
14273
14274 $DBversion = '16.12.00.028';
14275 if( CheckVersion( $DBversion ) ) {
14276     $dbh->do(q{
14277         UPDATE systempreferences  SET options = 'us|de|fr' WHERE variable = 'AddressFormat';
14278     });
14279
14280     SetVersion( $DBversion );
14281     print "Upgrade to $DBversion done (Bug 18110 - Adds FR to the syspref AddressFormat)\n";
14282 }
14283
14284 $DBversion = '16.12.00.029';
14285 if( CheckVersion( $DBversion ) ) {
14286     unless( column_exists( 'issues', 'note' ) ) {
14287         $dbh->do(q|ALTER TABLE issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14288     }
14289     unless( column_exists( 'issues', 'notedate' ) ) {
14290         $dbh->do(q|ALTER TABLE issues ADD notedate datetime default NULL AFTER note|);
14291     }
14292     unless( column_exists( 'old_issues', 'note' ) ) {
14293         $dbh->do(q|ALTER TABLE old_issues ADD note mediumtext default NULL AFTER onsite_checkout|);
14294     }
14295     unless( column_exists( 'old_issues', 'notedate' ) ) {
14296         $dbh->do(q|ALTER TABLE old_issues ADD notedate datetime default NULL AFTER note|);
14297     }
14298
14299     $dbh->do(q|
14300         INSERT IGNORE INTO letter (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
14301         VALUES ('circulation', 'CHECKOUT_NOTE', '', 'Checkout note on item set by patron', '0', 'Checkout note', '<<borrowers.firstname>> <<borrowers.surname>> has added a note to the item <<biblio.title>> - <<biblio.author>> (<<biblio.biblionumber>>).','email');
14302     |);
14303
14304     $dbh->do(q|
14305         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`)
14306         VALUES ('AllowCheckoutNotes', '0', NULL, 'Allow patrons to submit notes about checked out items.','YesNo');
14307     |);
14308
14309     SetVersion( $DBversion );
14310     print "Upgrade to $DBversion done (Bug 14224: Add column issues.note and issues.notedate)\n";
14311 }
14312
14313 $DBversion = '16.12.00.030';
14314 if( CheckVersion( $DBversion ) ) {
14315     unless( column_exists( 'issuingrules', 'no_auto_renewal_after_hard_limit' ) ) {
14316         $dbh->do(q{
14317             ALTER TABLE issuingrules ADD COLUMN no_auto_renewal_after_hard_limit DATE DEFAULT NULL AFTER no_auto_renewal_after;
14318         });
14319     }
14320
14321     SetVersion( $DBversion );
14322     print "Upgrade to $DBversion done (Bug 16344 - Add a circ rule to limit the auto renewals given a specific date)\n";
14323 }
14324
14325 $DBversion = '16.12.00.031';
14326 if( CheckVersion( $DBversion ) ) {
14327     if ( !index_exists( 'biblioitems', 'timestamp' ) ) {
14328         $dbh->do("ALTER TABLE biblioitems ADD KEY `timestamp` (`timestamp`);");
14329     }
14330     if ( !index_exists( 'deletedbiblioitems', 'timestamp' ) ) {
14331         $dbh->do("ALTER TABLE deletedbiblioitems ADD KEY `timestamp` (`timestamp`);");
14332     }
14333     if ( !index_exists( 'items', 'timestamp' ) ) {
14334         $dbh->do("ALTER TABLE items ADD KEY `timestamp` (`timestamp`);");
14335     }
14336     if ( !index_exists( 'deleteditems', 'timestamp' ) ) {
14337         $dbh->do("ALTER TABLE deleteditems ADD KEY `timestamp` (`timestamp`);");
14338     }
14339
14340     SetVersion( $DBversion );
14341     print "Upgrade to $DBversion done (Bug 15108: OAI-PMH provider improvements)\n";
14342 }
14343
14344 $DBversion = '16.12.00.032';
14345 if( CheckVersion( $DBversion ) ) {
14346     require Koha::Calendar;
14347
14348     $dbh->do(q{
14349         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) 
14350         VALUES ('ExcludeHolidaysFromMaxPickUpDelay', '0', 'If ON, reserves max pickup delay takes into account the closed days.', NULL, 'Integer');
14351     });
14352
14353     my $waiting_holds = $dbh->selectall_arrayref(q|
14354         SELECT expirationdate, waitingdate, branchcode
14355         FROM reserves
14356         WHERE found = 'W' AND priority = 0
14357     |, { Slice => {} });
14358     my $update_sth = $dbh->prepare(q|
14359         UPDATE reserves
14360         SET expirationdate = ?
14361         WHERE reserve_id = ?
14362     |);
14363     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
14364     for my $hold ( @$waiting_holds ) {
14365
14366         my $requested_expiration;
14367         if ($hold->{expirationdate}) {
14368             $requested_expiration = dt_from_string($hold->{expirationdate});
14369         }
14370
14371         my $expirationdate = dt_from_string($hold->{waitingdate});
14372         if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
14373             my $calendar = Koha::Calendar->new( branchcode => $hold->{branchcode}, days_mode => C4::Context->preference('useDaysMode') );
14374             $expirationdate = $calendar->days_forward( $expirationdate, $max_pickup_delay );
14375         } else {
14376             $expirationdate->add( days => $max_pickup_delay );
14377         }
14378
14379         my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
14380         $update_sth->execute($cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd, $hold->{reserve_id});
14381     }
14382
14383     SetVersion( $DBversion );
14384     print "Upgrade to $DBversion done (Bug 12063 - Update reserves.expirationdate)\n";
14385 }
14386
14387 $DBversion = '16.12.00.033';
14388 if( CheckVersion( $DBversion ) ) {
14389
14390     if( !column_exists( 'letter', 'lang' ) ) {
14391         $dbh->do( "ALTER TABLE letter ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER message_transport_type" );
14392     }
14393
14394     if( !column_exists( 'borrowers', 'lang' ) ) {
14395         $dbh->do( "ALTER TABLE borrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14396         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN lang VARCHAR(25) NOT NULL DEFAULT 'default' AFTER lastseen" );
14397     }
14398
14399     # Add test on existene of this key
14400     $dbh->do( "ALTER TABLE message_transports DROP FOREIGN KEY message_transports_ibfk_3 ");
14401     $dbh->do( "ALTER TABLE letter DROP PRIMARY KEY ");
14402     $dbh->do( "ALTER TABLE letter ADD PRIMARY KEY (`module`, `code`, `branchcode`, `message_transport_type`, `lang`) ");
14403
14404     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
14405         VALUES ('TranslateNotices',  '0',  NULL,  'Allow notices to be translated',  'YesNo') ");
14406
14407     SetVersion( $DBversion );
14408     print "Upgrade to $DBversion done (Bug 17762 - Add columns letter.lang and borrowers.lang to allow translation of notices)\n";
14409 }
14410
14411 $DBversion = '16.12.00.034';
14412 if( CheckVersion( $DBversion ) ) {
14413     $dbh->do(q{
14414         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14415         VALUES ('OPACFineNoRenewalsBlockAutoRenew','0','','Block/Allow auto renewals if the patron owe more than OPACFineNoRenewals','YesNo')
14416     });
14417
14418     SetVersion( $DBversion );
14419     print "Upgrade to $DBversion done (Bug 15582 - Ability to block auto renewals if the OPACFineNoRenewals amount is reached)\n";
14420 }
14421
14422 $DBversion = '16.12.00.035';
14423 if( CheckVersion( $DBversion ) ) {
14424     if( !column_exists( 'issues', 'auto_renew_error' ) ) {
14425         $dbh->do(q{
14426            ALTER TABLE issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14427         });
14428     }
14429
14430     if( !column_exists( 'old_issues', 'auto_renew_error' ) ) {
14431         $dbh->do(q{
14432             ALTER TABLE old_issues ADD COLUMN auto_renew_error VARCHAR(32) DEFAULT NULL AFTER auto_renew;
14433         });
14434     }
14435
14436     $dbh->do(q{
14437             INSERT INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS', 'Notification of automatic renewal', 'Automatic renewal notice',
14438         "Dear [% borrower.firstname %] [% borrower.surname %],
14439 [% IF checkout.auto_renew_error %]
14440 The following item, [% biblio.title %], has not been renewed because:
14441 [% IF checkout.auto_renew_error == 'too_many' %]
14442 You have reached the maximum number of checkouts possible.
14443 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
14444 This item is on hold for another patron.
14445 [% ELSIF checkout.auto_renew_error == 'restriction' %]
14446 You are currently restricted.
14447 [% ELSIF checkout.auto_renew_error == 'overdue' %]
14448 You have overdue items.
14449 [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
14450 It\'s too late to renew this item.
14451 [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
14452 Your total unpaid fines are too high.
14453 [% END %]
14454 [% ELSE %]
14455 The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]
14456 [% END %]", 'email');
14457     });
14458
14459     SetVersion( $DBversion );
14460     print "Upgrade to $DBversion done (Bug 15705 - Notify the user on auto renewing)\n";
14461 }
14462
14463 $DBversion = '16.12.00.036';
14464 if( CheckVersion( $DBversion ) ) {
14465     $dbh->do(q{
14466         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14467         VALUES ('NumSavedReports', '20', NULL, 'By default, show this number of saved reports.', 'Integer');
14468     });
14469
14470     SetVersion( $DBversion );
14471     print "Upgrade to $DBversion done (Bug 17465 - Add a System Preference to control number of Saved Reports displayed)\n";
14472 }
14473
14474 $DBversion = '16.12.00.037';
14475 if( CheckVersion( $DBversion ) ) {
14476     $dbh->do( q|
14477         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14478         VALUES ('FailedLoginAttempts','','','Number of login attempts before lockout the patron account','Integer');
14479     |);
14480
14481     unless( column_exists( 'borrowers', 'login_attempts' ) ) {
14482         $dbh->do(q|
14483             ALTER TABLE borrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14484         |);
14485         $dbh->do(q|
14486             ALTER TABLE deletedborrowers ADD COLUMN login_attempts INT(4) DEFAULT 0 AFTER lastseen
14487         |);
14488     }
14489
14490     SetVersion( $DBversion );
14491     print "Upgrade to $DBversion done (Bug 18314 - Add FailedLoginAttempts and borrowers.login_attempts)\n";
14492 }
14493
14494 $DBversion = '16.12.00.038';
14495 if( CheckVersion( $DBversion ) ) {
14496     $dbh->do(q{
14497         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14498         ('ExportRemoveFields','',NULL,'List of fields for non export in circulation.pl (separated by a space)','Free');
14499     });
14500
14501     SetVersion( $DBversion );
14502     print "Upgrade to $DBversion done (Bug 18663 - Missing db update for ExportRemoveFields)\n";
14503 }
14504
14505 $DBversion = '16.12.00.039';
14506 if( CheckVersion( $DBversion ) ) {
14507     $dbh->do(q{
14508         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14509         ('TalkingTechItivaPhoneNotification','0',NULL,'If ON, enables Talking Tech I-tiva phone notifications','YesNo');
14510     });
14511
14512     SetVersion( $DBversion );
14513     print "Upgrade to $DBversion done (Bug 18600 - Missing db update for TalkingTechItivaPhoneNotification)\n";
14514 }
14515
14516 $DBversion = '17.05.00.000';
14517 if( CheckVersion( $DBversion ) ) {
14518
14519     SetVersion( $DBversion );
14520     print "Upgrade to $DBversion done (Koha 17.05)\n";
14521 }
14522
14523 $DBversion = '17.06.00.000';
14524 if( CheckVersion( $DBversion ) ) {
14525     SetVersion( $DBversion );
14526     print "Upgrade to $DBversion done (He pai ake te iti i te kore)\n";
14527 }
14528
14529 $DBversion = '17.06.00.001';
14530 if( CheckVersion( $DBversion ) ) {
14531
14532     unless ( column_exists( 'export_format', 'used_for' ) ) {
14533         $dbh->do(q|ALTER TABLE export_format ADD used_for varchar(255) DEFAULT 'export_records' AFTER type|);
14534
14535         $dbh->do(q|UPDATE export_format SET used_for = 'late_issues' WHERE type = 'sql'|);
14536         $dbh->do(q|UPDATE export_format SET used_for = 'export_records' WHERE type = 'marc'|);
14537     }
14538     SetVersion( $DBversion );
14539     print "Upgrade to $DBversion done (Bug 8612 - Add new column export_format.used_for)\n";
14540 }
14541
14542 $DBversion = '17.06.00.002';
14543 if ( CheckVersion($DBversion) ) {
14544
14545     unless ( column_exists('virtualshelves', 'allow_change_from_owner' ) ) {
14546         $dbh->do(q|
14547             ALTER TABLE virtualshelves
14548             ADD COLUMN allow_change_from_owner tinyint(1) default 1,
14549             ADD COLUMN allow_change_from_others tinyint(1) default 0
14550         |);
14551
14552         # Conversion:
14553         # Since we had no readonly lists, change_from_owner is set to true.
14554         # When adding or delete_other was granted, change_from_others is true.
14555         # Note: In my opinion the best choice; there is no exact match.
14556         $dbh->do(q|
14557             UPDATE virtualshelves
14558             SET allow_change_from_owner = 1,
14559                 allow_change_from_others = CASE WHEN allow_add=1 OR allow_delete_other=1 THEN 1 ELSE 0 END
14560         |);
14561
14562         # Remove the old columns
14563         $dbh->do(q|
14564             ALTER TABLE virtualshelves
14565             DROP COLUMN allow_add,
14566             DROP COLUMN allow_delete_own,
14567             DROP COLUMN allow_delete_other
14568         |);
14569     }
14570
14571     SetVersion($DBversion);
14572     print "Upgrade to $DBversion done (Bug 18228 - Alter table virtualshelves to simplify permissions)\n";
14573 }
14574
14575 $DBversion = '17.06.00.003';
14576 if ( CheckVersion($DBversion) ) {
14577
14578     # Fetch all auth types
14579     my $authtypes = $dbh->selectcol_arrayref(q|SELECT authtypecode FROM auth_types|);
14580
14581     if ( grep { $_ eq 'Default' } @$authtypes ) {
14582
14583         # If this exists as an authtypecode, we don't do anything
14584     }
14585     else {
14586         # Replace the incorrect Default by empty string
14587         $dbh->do(q|
14588             UPDATE auth_header SET authtypecode='' WHERE authtypecode='Default'
14589         |);
14590     }
14591
14592     SetVersion($DBversion);
14593     print "Upgrade to $DBversion done (Bug 18801 - Update incorrect Default auth type codes)\n";
14594 }
14595
14596 $DBversion = '17.06.00.004';
14597 if( CheckVersion( $DBversion ) ) {
14598     $dbh->do(q{
14599         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14600         ('GoogleOpenIDConnectAutoRegister',   '0',NULL,' Google OpenID Connect logins to auto-register patrons.','YesNo'),
14601         ('GoogleOpenIDConnectDefaultCategory','','','This category code will be used to create Google OpenID Connect patrons.','Textarea'),
14602         ('GoogleOpenIDConnectDefaultBranch',  '','','This branch code will be used to create Google OpenID Connect patrons.','Textarea');
14603     });
14604
14605     SetVersion( $DBversion );
14606     print "Upgrade to $DBversion done (Bug 16892: Add automatic patron registration via OAuth2 login)\n";
14607 }
14608
14609 $DBversion = '17.06.00.005';
14610 if( CheckVersion( $DBversion ) ) {
14611     $dbh->do(q{
14612         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES  ('StaffLangSelectorMode','footer','top|both|footer','Select the location to display the language selector in staff client','Choice')
14613         });
14614
14615     SetVersion( $DBversion );
14616     print "Upgrade to $DBversion done (Bug 18718 - Language selector in staff header menu similar to OPAC )\n";
14617 }
14618
14619 $DBversion = '17.06.00.006';
14620 if( CheckVersion( $DBversion ) ) {
14621     print q{WARNING: Bug 18811 fixed an inconsistency in the visibility settings for authority frameworks. It is recommended that you run script misc/maintenance/auth_show_hidden_data.pl to check if you have data in hidden fields and adjust your frameworks accordingly to prevent data loss when editing such records.};
14622     print "\n";
14623
14624     SetVersion( $DBversion );
14625     print "Upgrade to $DBversion done (Bug 18811 - Visibility settings inconsistent between framework and authority editor)\n";
14626 }
14627
14628 $DBversion = '17.06.00.007';
14629 if( CheckVersion( $DBversion ) ) {
14630     if( !column_exists( 'branches', 'marcorgcode' ) ) {
14631         $dbh->do( "ALTER TABLE branches ADD COLUMN marcorgcode VARCHAR(16) default NULL AFTER geolocation" );
14632     }
14633
14634     SetVersion( $DBversion );
14635     print "Upgrade to $DBversion done (Bug 10132 - MARCOrgCode on branch level (branches.marcorgcode))\n";
14636 }
14637
14638 $DBversion = '17.06.00.008';
14639 if( CheckVersion( $DBversion ) ) {
14640     unless ( column_exists( 'borrowers', 'date_renewed' ) ) {
14641         $dbh->do(q{
14642             ALTER TABLE borrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14643         });
14644     }
14645
14646     unless ( column_exists( 'deletedborrowers', 'date_renewed' ) ) {
14647         $dbh->do(q{
14648             ALTER TABLE deletedborrowers ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14649         });
14650     }
14651
14652     unless ( column_exists( 'borrower_modifications', 'date_renewed' ) ) {
14653         $dbh->do(q{
14654             ALTER TABLE borrower_modifications ADD COLUMN date_renewed DATE NULL DEFAULT NULL AFTER dateexpiry;
14655         });
14656     }
14657
14658     SetVersion( $DBversion );
14659     print "Upgrade to $DBversion done (Bug 6758 - Capture membership renewal date for reporting purposes (borrowers.date_renewed))\n";
14660 }
14661
14662 $DBversion = '17.06.00.009';
14663 if( CheckVersion( $DBversion ) ) {
14664     $dbh->do(q{
14665         ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14666     });
14667     $dbh->do(q{
14668         ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) DEFAULT 0 AFTER lang;
14669     });
14670
14671     SetVersion( $DBversion );
14672     print "Upgrade to $DBversion done (Bug 19344 -  Reorder lang and login_attempts in the [deleted]borrowers tables)\n";
14673 }
14674
14675 $DBversion = '17.06.00.010';
14676 if ( CheckVersion($DBversion) ) {
14677     $dbh->do(q{
14678         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
14679         VALUES (
14680             'DefaultCountryField008','','',
14681             'Fill in the default country code for field 008 Range 15-17 of MARC21 - Place of publication, production, or execution. See <a href=\"http://www.loc.gov/marc/countries/countries_code.html\">MARC Code List for Countries</a>','Free')
14682     });
14683     SetVersion($DBversion);
14684     print "Upgrade to $DBversion done (Bug 13912 - System preference for default place of publication (country code) for field 008, range 15-17)\n";
14685 }
14686
14687 $DBversion = '17.06.00.011';
14688 if ( CheckVersion($DBversion) ) {
14689     # Drop index that might exist because of bug 5337
14690     if( index_exists('biblioitems', 'ean')) {
14691         $dbh->do(q{ ALTER TABLE biblioitems DROP INDEX ean });
14692     }
14693     if( index_exists('deletedbiblioitems', 'ean')) {
14694         $dbh->do(q{ ALTER TABLE deletedbiblioitems DROP INDEX ean });
14695     }
14696
14697     # Change data type of column
14698     $dbh->do(q{ ALTER TABLE biblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14699     $dbh->do(q{ ALTER TABLE deletedbiblioitems MODIFY COLUMN ean MEDIUMTEXT default NULL });
14700
14701     # Add indexes
14702     $dbh->do(q{ ALTER TABLE biblioitems ADD INDEX ean ( ean(255) )});
14703     $dbh->do(q{ ALTER TABLE deletedbiblioitems ADD INDEX ean ( ean(255 ) )});
14704
14705     SetVersion($DBversion);
14706     print "Upgrade to $DBversion done (Bug 13766 - Make ean mediumtext and add ean indexes)\n";
14707 }
14708
14709 $DBversion = '17.06.00.012';
14710 if( CheckVersion( $DBversion ) ) {
14711     my $where = q|host='clio-db.cc.columbia.edu' AND port=7090|;
14712     my $sql = "SELECT COUNT(*) FROM z3950servers WHERE $where";
14713     my ( $cnt ) = $dbh->selectrow_array( $sql );
14714     if( $cnt ) {
14715         $dbh->do( "DELETE FROM z3950servers WHERE $where" );
14716         print "Removed $cnt Z39.50 target(s) for Columbia University\n";
14717     }
14718
14719     SetVersion( $DBversion );
14720     print "Upgrade to $DBversion done (Bug 19043 - Z39.50 target for Columbia University is no longer publicly available.)\n";
14721 }
14722
14723 $DBversion = '17.06.00.013';
14724 if( CheckVersion( $DBversion ) ) {
14725     $dbh->do( "UPDATE systempreferences SET value = CONCAT('http://', value) WHERE variable = 'staffClientBaseURL' AND value <> '' AND value NOT LIKE 'http%'" );
14726
14727     my ( $staffClientBaseURL_used_in_notices ) = $dbh->selectrow_array(q|
14728         SELECT COUNT(*) FROM letter where content like "%staffClientBaseURL%"
14729     |);
14730     if ( $staffClientBaseURL_used_in_notices ) {
14731         warn "\tYou may need to update one or more notice templates if they contain 'staffClientBaseURL'\n";
14732     }
14733
14734     SetVersion( $DBversion );
14735     print "Upgrade to $DBversion done (Bug 16401 - fix potentialy bad set staffClientBaseURL preference)\n";
14736 }
14737
14738 $DBversion = '17.06.00.014';
14739 if( CheckVersion( $DBversion ) ) {
14740     unless( column_exists('aqbasket','create_items') ){
14741         $dbh->do(q{
14742             ALTER TABLE aqbasket
14743                 ADD COLUMN create_items ENUM('ordering', 'receiving', 'cataloguing') default NULL AFTER is_standing
14744         });
14745     }
14746
14747     SetVersion( $DBversion );
14748     print "Upgrade to $DBversion done (Bug 15685 - Allow creation of items (AcqCreateItem) to be customizable per-basket)\n";
14749 }
14750
14751 $DBversion = '17.06.00.015';
14752 if( CheckVersion( $DBversion ) ) {
14753     $dbh->do(q{
14754         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
14755         ('SelfCheckoutByLogin','0',NULL,'Have patrons login into the web-based self checkout system with their username/password or their cardnumber','YesNo')
14756     });
14757
14758     SetVersion( $DBversion );
14759     print "Upgrade to $DBversion done (Bug 19186 - Insert system preference SelfCheckoutByLogin if missing)\n";
14760 }
14761
14762 $DBversion = '17.06.00.016';
14763 if( CheckVersion( $DBversion ) ) {
14764     $dbh->do(q{
14765         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
14766         VALUES ('RequireStrongPassword','0','','Require a strong login password for staff and patrons','YesNo');
14767     });
14768
14769     SetVersion( $DBversion );
14770     print "Upgrade to $DBversion done (Bug 18298 - Allow enforcing password complexity (system preference RequireStrongPassword))\n";
14771 }
14772
14773 $DBversion = '17.06.00.017';
14774 if( CheckVersion( $DBversion ) ) {
14775     unless (TableExists('account_offsets')) {
14776         $dbh->do(q{
14777             DROP TABLE IF EXISTS `accountoffsets`;
14778         });
14779
14780         $dbh->do(q{
14781             CREATE TABLE IF NOT EXISTS `account_offset_types` (
14782               `type` varchar(16) NOT NULL, -- The type of offset this is
14783               PRIMARY KEY (`type`)
14784             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14785         });
14786
14787         $dbh->do(q{
14788             CREATE TABLE IF NOT EXISTS `account_offsets` (
14789               `id` int(11) NOT NULL auto_increment, -- unique identifier for each offset
14790               `credit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline the increased the patron's balance
14791               `debit_id` int(11) NULL DEFAULT NULL, -- The id of the accountline that decreased the patron's balance
14792               `type` varchar(16) NOT NULL, -- The type of offset this is
14793               `amount` decimal(26,6) NOT NULL, -- The amount of the change
14794               `created_on` timestamp NOT NULL default CURRENT_TIMESTAMP,
14795               PRIMARY KEY (`id`),
14796               CONSTRAINT `account_offsets_ibfk_p` FOREIGN KEY (`credit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14797               CONSTRAINT `account_offsets_ibfk_f` FOREIGN KEY (`debit_id`) REFERENCES `accountlines` (`accountlines_id`) ON DELETE CASCADE ON UPDATE CASCADE,
14798               CONSTRAINT `account_offsets_ibfk_t` FOREIGN KEY (`type`) REFERENCES `account_offset_types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE
14799             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14800         });
14801
14802         $dbh->do(q{
14803             INSERT IGNORE INTO account_offset_types ( type ) VALUES
14804             ('Writeoff'),
14805             ('Payment'),
14806             ('Lost Item'),
14807             ('Processing Fee'),
14808             ('Manual Debit'),
14809             ('Reverse Payment'),
14810             ('Forgiven'),
14811             ('Dropbox'),
14812             ('Rental Fee'),
14813             ('Fine Update'),
14814             ('Fine');
14815         });
14816     }
14817
14818     SetVersion( $DBversion );
14819     print "Upgrade to $DBversion done (Bug 14826 - Resurrect account offsets table (Add new tables account_offsets and account_offset_types))\n";
14820 }
14821
14822 $DBversion = '17.06.00.018';
14823 if( CheckVersion( $DBversion ) ) {
14824     $dbh->do(q{
14825         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('useDefaultReplacementCost',0,'default replacement cost defined in item type','YesNo');
14826     });
14827     $dbh->do(q{
14828         INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES ('ProcessingFeeNote','','Set the text to be recorded in the column note, table accountlines when the processing fee (defined in item type) is applied','textarea');
14829     });
14830     $dbh->do(q{
14831         ALTER TABLE `itemtypes` MODIFY COLUMN `rentalcharge` DECIMAL(28,6) NULL DEFAULT NULL;
14832     });
14833     unless ( column_exists( 'itemtypes', 'defaultreplacecost' ) ) {
14834         $dbh->do(q{
14835             ALTER TABLE `itemtypes` ADD `defaultreplacecost` DECIMAL(28,6) NULL DEFAULT NULL AFTER `rentalcharge`;
14836         });
14837     }
14838     unless ( column_exists( 'itemtypes', 'processfee' ) ) {
14839         $dbh->do(q{
14840             ALTER TABLE `itemtypes` ADD `processfee` DECIMAL(28,6) NULL DEFAULT NULL AFTER `defaultreplacecost`;
14841         });
14842
14843     }
14844     SetVersion( $DBversion );
14845     print "Upgrade to $DBversion done (Bug 12768 - Insert system preferences useDefaultReplacementCost and ProcessingFeeNote + Add new columns defaultreplacecost and processfee to the itemtypes table)\n";
14846 }
14847
14848 $DBversion = '17.06.00.019';
14849 if( CheckVersion( $DBversion ) ) {
14850     $dbh->do(q{
14851         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Processing Fee' );
14852     });
14853
14854     SetVersion( $DBversion );
14855     print "Upgrade to $DBversion done (Bug 12768 - Add 'Processing Fee' to the account_offset_types table if missing)\n";
14856 }
14857
14858 $DBversion = '17.06.00.020';
14859 if( CheckVersion( $DBversion ) ) {
14860     $dbh->do(q{
14861         UPDATE systempreferences
14862         SET
14863             variable='OpacLocationOnDetail',
14864             options='holding|home|both|column',
14865             explanation='In the OPAC detail, display the shelving location on its own column or under a library columns.'
14866         WHERE
14867             variable='OpacLocationBranchToDisplayShelving'
14868     });
14869
14870     SetVersion( $DBversion );
14871     print "Upgrade to $DBversion done (Bug 19028: Add 'shelving location' to holdings table in detail page (Rename syspref OpacLocationBranchToDisplayShelving with OpacLocationOnDetail))\n";
14872 }
14873
14874 $DBversion = '17.06.00.021';
14875 if( CheckVersion( $DBversion ) ) {
14876     $dbh->do(q{
14877         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type` ) VALUES ('SCOMainUserBlock','','70|10','Add a block of HTML that will display on the self checkout screen','Textarea')
14878     });
14879
14880     SetVersion( $DBversion );
14881     print "Upgrade to $DBversion done (Bug 17381 - Add system preference SCOMainUserBlock)\n";
14882 }
14883
14884 $DBversion = '17.06.00.022';
14885 if( CheckVersion( $DBversion ) ) {
14886     my $hide_barcode = C4::Context->preference('OPACShowBarcode') ? 0 : 1;
14887     $dbh->do(q{
14888         DELETE FROM systempreferences
14889         WHERE
14890             variable='OPACShowBarcode'
14891     });
14892
14893     # Configure column visibility if it isn't
14894     $dbh->do(q{
14895         INSERT IGNORE INTO columns_settings
14896             (module,page,tablename,columnname,cannot_be_toggled,is_hidden)
14897         VALUES
14898             ('opac','biblio-detail','holdingst','item_barcode',0,?)
14899     }, undef, $hide_barcode);
14900
14901     SetVersion( $DBversion );
14902     print "Upgrade to $DBversion done (Bug 19038: Remove OPACShowBarcode syspref)\n";
14903 }
14904
14905 $DBversion = '17.06.00.023';
14906 if( CheckVersion( $DBversion ) ) {
14907     $dbh->do(q{
14908         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14909         ('MarkLostItemsAsReturned','1','','Mark items as returned when flagged as lost','YesNo');
14910     });
14911
14912     SetVersion( $DBversion );
14913     print "Upgrade to $DBversion done (Bug 12363 - Add system preference MarkLostItemsAsReturned)\n";
14914 }
14915
14916 $DBversion = '17.06.00.024';
14917 if( CheckVersion( $DBversion ) ) {
14918     $dbh->do(q{
14919         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`) VALUES
14920         ('OPACUserSummary', 1, NULL, "Show the summary of a logged in user's checkouts, overdues, holds and fines on the mainpage", 'YesNo');
14921     });
14922
14923     SetVersion( $DBversion );
14924     print "Upgrade to $DBversion done (Bug 2093 - Add system preference OPACUserSummary)\n";
14925 }
14926
14927 $DBversion = '17.06.00.025';
14928 if( CheckVersion( $DBversion ) ) {
14929     $dbh->do(q{
14930         ALTER TABLE borrowers MODIFY cardnumber varchar(32);
14931     });
14932     $dbh->do(q{
14933         ALTER TABLE borrower_modifications MODIFY cardnumber varchar(32);
14934     });
14935     $dbh->do(q{
14936         ALTER TABLE deletedborrowers MODIFY cardnumber varchar(32);
14937     });
14938     $dbh->do(q{
14939         ALTER TABLE pending_offline_operations MODIFY cardnumber varchar(32);
14940     });
14941     $dbh->do(q{
14942         ALTER TABLE tmp_holdsqueue MODIFY cardnumber varchar(32);
14943     });
14944
14945     SetVersion( $DBversion );
14946     print "Upgrade to $DBversion done (Bug 13178 - Increase cardnumber fields to VARCHAR(32))\n";
14947 }
14948
14949 $DBversion = '17.06.00.026';
14950 if( CheckVersion( $DBversion ) ) {
14951     $dbh->do(q{
14952         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
14953         ('BlockReturnOfLostItems','0','0','If enabled, items that are marked as lost cannot be returned.','YesNo');
14954     });
14955
14956     SetVersion( $DBversion );
14957     print "Upgrade to $DBversion done (Bug 10748 - Add system preference BlockReturnOfLostItems)\n";
14958 }
14959
14960 $DBversion = '17.06.00.027';
14961 if( CheckVersion( $DBversion ) ) {
14962     if ( !column_exists( 'statistics', 'location' ) ) {
14963         $dbh->do('ALTER TABLE statistics ADD COLUMN location VARCHAR(80) default NULL AFTER itemtype');
14964     }
14965
14966     SetVersion($DBversion);
14967     print "Upgrade to $DBversion done (Bug 18882 - Add location code to statistics table for checkouts and renewals)\n";
14968 }
14969
14970 $DBversion = '17.06.00.028';
14971 if( CheckVersion( $DBversion ) ) {
14972     if ( !TableExists( 'illrequests' ) ) {
14973         $dbh->do(q{
14974             CREATE TABLE illrequests (
14975                illrequest_id serial PRIMARY KEY,           -- ILL request number
14976                borrowernumber integer DEFAULT NULL,        -- Patron associated with request
14977                biblio_id integer DEFAULT NULL,             -- Potential bib linked to request
14978                branchcode varchar(50) NOT NULL,            -- The branch associated with the request
14979                status varchar(50) DEFAULT NULL,            -- Current Koha status of request
14980                placed date DEFAULT NULL,                   -- Date the request was placed
14981                replied date DEFAULT NULL,                  -- Last API response
14982                updated timestamp DEFAULT CURRENT_TIMESTAMP -- Last modification to request
14983                  ON UPDATE CURRENT_TIMESTAMP,
14984                completed date DEFAULT NULL,                -- Date the request was completed
14985                medium varchar(30) DEFAULT NULL,            -- The Koha request type
14986                accessurl varchar(500) DEFAULT NULL,        -- Potential URL for accessing item
14987                cost varchar(20) DEFAULT NULL,              -- Cost of request
14988                notesopac text DEFAULT NULL,                -- Patron notes attached to request
14989                notesstaff text DEFAULT NULL,               -- Staff notes attached to request
14990                orderid varchar(50) DEFAULT NULL,           -- Backend id attached to request
14991                backend varchar(20) DEFAULT NULL,           -- The backend used to create request
14992                CONSTRAINT `illrequests_bnfk`
14993                  FOREIGN KEY (`borrowernumber`)
14994                  REFERENCES `borrowers` (`borrowernumber`)
14995                  ON UPDATE CASCADE ON DELETE CASCADE,
14996                CONSTRAINT `illrequests_bcfk_2`
14997                  FOREIGN KEY (`branchcode`)
14998                  REFERENCES `branches` (`branchcode`)
14999                  ON UPDATE CASCADE ON DELETE CASCADE
15000            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15001         });
15002     }
15003
15004     if ( !TableExists( 'illrequestattributes' ) ) {
15005         $dbh->do(q{
15006             CREATE TABLE illrequestattributes (
15007                 illrequest_id bigint(20) unsigned NOT NULL, -- ILL request number
15008                 type varchar(200) NOT NULL,                 -- API ILL property name
15009                 value text NOT NULL,                        -- API ILL property value
15010                 PRIMARY KEY  (`illrequest_id`,`type`),
15011                 CONSTRAINT `illrequestattributes_ifk`
15012                   FOREIGN KEY (illrequest_id)
15013                   REFERENCES `illrequests` (`illrequest_id`)
15014                   ON UPDATE CASCADE ON DELETE CASCADE
15015             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15016         });
15017     }
15018
15019     # System preferences
15020     $dbh->do(q{
15021         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15022             ('ILLModule','0','If ON, enables the interlibrary loans module.','','YesNo');
15023     });
15024
15025     $dbh->do(q{
15026         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
15027             ('ILLModuleCopyrightClearance','','70|10','Enter text to enable the copyright clearance stage of request creation. Text will be displayed','Textarea');
15028     });
15029     # userflags
15030     $dbh->do(q{
15031         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15032             (22,'ill','The Interlibrary Loans Module',0);
15033     });
15034
15035     SetVersion( $DBversion );
15036     print "Upgrade to $DBversion done (Bug 7317 - Add an Interlibrary Loan Module to Circulation and OPAC)\n";
15037 }
15038
15039 $DBversion = '17.11.00.000';
15040 if( CheckVersion( $DBversion ) ) {
15041     SetVersion( $DBversion );
15042     print "Upgrade to $DBversion done (Koha 17.11)\n";
15043 }
15044
15045 $DBversion = '17.12.00.000';
15046 if( CheckVersion( $DBversion ) ) {
15047     SetVersion( $DBversion );
15048     print "Upgrade to $DBversion done (Tē tōia, tē haumatia)\n";
15049 }
15050
15051 $DBversion = '17.12.00.001';
15052 if( CheckVersion( $DBversion ) ) {
15053     foreach my $table (qw(biblio_metadata deletedbiblio_metadata)) {
15054         if (!column_exists($table, 'timestamp')) {
15055             $dbh->do(qq{
15056                 ALTER TABLE `$table`
15057                 ADD COLUMN `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER `metadata`,
15058                 ADD KEY `timestamp` (`timestamp`)
15059             });
15060             $dbh->do(qq{
15061                 UPDATE $table metadata
15062                     LEFT JOIN biblioitems ON (biblioitems.biblionumber = metadata.biblionumber)
15063                     LEFT JOIN biblio ON (biblio.biblionumber = metadata.biblionumber)
15064                 SET metadata.timestamp = GREATEST(biblioitems.timestamp, biblio.timestamp);
15065             });
15066         }
15067     }
15068
15069     SetVersion( $DBversion );
15070     print "Upgrade to $DBversion done (Bug 19724 - Add [deleted]biblio_metadata.timestamp)\n";
15071 }
15072
15073 $DBversion = '17.12.00.002';
15074 if( CheckVersion( $DBversion ) ) {
15075
15076     my $msss = $dbh->selectall_arrayref(q|
15077         SELECT kohafield, tagfield, tagsubfield, frameworkcode
15078         FROM marc_subfield_structure
15079         WHERE   frameworkcode != ''
15080     |, { Slice => {} });
15081
15082
15083     my $sth = $dbh->prepare(q|
15084         SELECT kohafield
15085         FROM marc_subfield_structure
15086         WHERE frameworkcode = ''
15087         AND tagfield = ?
15088         AND tagsubfield = ?
15089     |);
15090
15091     my @exceptions;
15092     for my $mss ( @$msss ) {
15093         $sth->execute($mss->{tagfield}, $mss->{tagsubfield} );
15094         my ( $default_kohafield ) = $sth->fetchrow_array();
15095         if( $mss->{kohafield} ) {
15096             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => $mss->{kohafield} } if not $default_kohafield or $default_kohafield ne $mss->{kohafield};
15097         } else {
15098             push @exceptions, { frameworkcode => $mss->{frameworkcode}, tagfield => $mss->{tagfield}, tagsubfield => $mss->{tagsubfield}, kohafield => q{} } if $default_kohafield;
15099         }
15100     }
15101
15102     if (@exceptions) {
15103         print "WARNING: The Default framework is now considered as authoritative for Koha to MARC mappings. We have found that your additional frameworks contained "
15104           . scalar(@exceptions)
15105           . " mapping(s) that deviate from the standard mappings. Please look at the following list and consider if you need to add them again in Default (possibly as a second mapping).\n";
15106         for my $exception (@exceptions) {
15107             print "Field "
15108               . $exception->{tagfield} . '$'
15109               . $exception->{tagsubfield}
15110               . " in framework "
15111               . $exception->{frameworkcode} . ': ';
15112             if ( $exception->{kohafield} ) {
15113                 print "Mapping to "
15114                   . $exception->{kohafield}
15115                   . " has been adjusted.\n";
15116             }
15117             else {
15118                 print "Mapping has been reset.\n";
15119             }
15120         }
15121
15122         # Sync kohafield
15123
15124         # Clear the destination frameworks first
15125         $dbh->do(q|
15126             UPDATE marc_subfield_structure
15127             SET kohafield = NULL
15128             WHERE   frameworkcode > ''
15129                 AND     Kohafield > ''
15130         |);
15131
15132         # Now copy from Default
15133         my $msss = $dbh->selectall_arrayref(q|
15134             SELECT kohafield, tagfield, tagsubfield
15135             FROM marc_subfield_structure
15136             WHERE   frameworkcode = ''
15137                 AND     kohafield > ''
15138         |, { Slice => {} });
15139         my $sth = $dbh->prepare(q|
15140             UPDATE marc_subfield_structure
15141             SET kohafield = ?
15142             WHERE frameworkcode > ''
15143             AND tagfield = ?
15144             AND tagsubfield = ?
15145         |);
15146         for my $mss (@$msss) {
15147             $sth->execute( $mss->{kohafield}, $mss->{tagfield},
15148                 $mss->{tagsubfield} );
15149         }
15150
15151         # Clear the cache
15152         my @frameworkcodes = $dbh->selectall_arrayref(q|
15153             SELECT frameworkcode FROM biblio_framework WHERE frameworkcode > ''
15154         |);
15155         for my $frameworkcode (@frameworkcodes) {
15156             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
15157         }
15158         Koha::Caches->get_instance->clear_from_cache("default_value_for_mod_marc-");
15159     }
15160
15161     SetVersion( $DBversion );
15162     print "Upgrade to $DBversion done (Bug 19096 - Make Default authoritative for Koha to MARC mappings)\n";
15163 }
15164
15165 $DBversion = '17.12.00.003';
15166 if( CheckVersion( $DBversion ) ) {
15167     $dbh->do(q|DROP TABLE IF EXISTS notifys|);
15168
15169     if( column_exists( 'accountlines', 'notify_id' ) ) {
15170         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_id|);
15171         $dbh->do(q|ALTER TABLE accountlines DROP COLUMN notify_level|);
15172     }
15173
15174     SetVersion( $DBversion );
15175     print "Upgrade to $DBversion done (Bug 10021 - Drop notifys-related table and columns)\n";
15176 }
15177
15178 $DBversion = '17.12.00.004';
15179 if( CheckVersion( $DBversion ) ) {
15180     $dbh->do(q{
15181         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
15182         VALUES
15183             ('RESTdefaultPageSize','20','','Set the default number of results returned by the REST API endpoints','Integer')
15184     });
15185
15186     SetVersion( $DBversion );
15187     print "Upgrade to $DBversion done (Bug 19278 - Add a configurable default page size for REST endpoints)\n";
15188 }
15189
15190 $DBversion = '17.12.00.005';
15191 if( CheckVersion( $DBversion ) ) {
15192     # For installations having the note already
15193     $dbh->do(q{
15194         UPDATE letter
15195         SET code    = 'CHECKOUT_NOTE',
15196             name    = 'Checkout note on item set by patron',
15197             title   = 'Checkout note',
15198             content = REPLACE(content, "<<biblio.item>>", "<<biblio.title>>")
15199         WHERE code = 'PATRON_NOTE'
15200     });
15201     # For installations coming from 17.11
15202     $dbh->do(q{
15203         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
15204         VALUES ('circulation', 'CHECKOUT_NOTE', '', 'Checkout note on item set by patron', '0', 'Checkout note', '<<borrowers.firstname>> <<borrowers.surname>> has added a note to the item <<biblio.title>> - <<biblio.author>> (<<biblio.biblionumber>>).','email')
15205     });
15206
15207     SetVersion( $DBversion );
15208     print "Upgrade to $DBversion done (Bug 18915 - Correct CHECKOUT_NOTE notice template)\n";
15209 }
15210
15211 $DBversion = '17.12.00.006';
15212 if( CheckVersion( $DBversion ) ) {
15213     $dbh->do(q{
15214         UPDATE systempreferences SET value=replace(value, "http://www.scholar", "https://scholar") WHERE variable='OPACSearchForTitleIn';
15215     });
15216
15217     SetVersion( $DBversion );
15218     print "Upgrade to $DBversion done (Bug 17682 - Update URL for Google Scholar in OPACSearchForTitleIn)\n";
15219 }
15220
15221 $DBversion = '17.12.00.007';
15222 if( CheckVersion( $DBversion ) ) {
15223
15224     unless ( TableExists( 'library_groups' ) ) {
15225         $dbh->do(q{
15226             CREATE TABLE library_groups (
15227                 id INT(11) NOT NULL auto_increment,    -- unique id for each group
15228                 parent_id INT(11) NULL DEFAULT NULL,   -- if this is a child group, the id of the parent group
15229                 branchcode VARCHAR(10) NULL DEFAULT NULL, -- The branchcode of a branch belonging to the parent group
15230                 title VARCHAR(100) NULL DEFAULT NULL,     -- Short description of the goup
15231                 description TEXT NULL DEFAULT NULL,    -- Longer explanation of the group, if necessary
15232                 created_on TIMESTAMP NULL,             -- Date and time of creation
15233                 updated_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Date and time of last
15234                 PRIMARY KEY id ( id ),
15235                 FOREIGN KEY (parent_id) REFERENCES library_groups(id) ON UPDATE CASCADE ON DELETE CASCADE,
15236                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON UPDATE CASCADE ON DELETE CASCADE,
15237                 UNIQUE KEY title ( title )
15238             ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
15239         });
15240     }
15241
15242     SetVersion( $DBversion );
15243     print "Upgrade to $DBversion done (Bug 15707 - Add new table library_groups)\n";
15244 }
15245
15246 $DBversion = '17.12.00.008';
15247 if ( CheckVersion($DBversion) ) {
15248
15249     if ( TableExists( 'branchcategories' ) and TableExists('branchrelations' )) {
15250         $dbh->do(q{
15251             INSERT INTO library_groups ( title, description, created_on ) VALUES ( '__SEARCH_GROUPS__', 'Library search groups', NOW() )
15252         });
15253         my $search_groups_root_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15254
15255         my $sth = $dbh->prepare("SELECT * FROM branchcategories");
15256
15257         my $sth2 = $dbh->prepare("INSERT INTO library_groups ( parent_id, title, description, created_on ) VALUES ( ?, ?, ?, NOW() )");
15258
15259         my $sth3 = $dbh->prepare("SELECT * FROM branchrelations WHERE categorycode = ?");
15260
15261         my $sth4 = $dbh->prepare("INSERT INTO library_groups ( parent_id, branchcode, created_on ) VALUES ( ?, ?, NOW() )");
15262
15263         $sth->execute();
15264         while ( my $lc = $sth->fetchrow_hashref ) {
15265             my $description = $lc->{categorycode};
15266             $description .= " - " . $lc->{codedescription} if $lc->{codedescription};
15267
15268             $sth2->execute($search_groups_root_id, $lc->{categoryname}, $description);
15269
15270             my $subgroup_id = $dbh->last_insert_id(undef, undef, 'library_groups', undef);
15271
15272             $sth3->execute( $lc->{categorycode} );
15273
15274             while ( my $l = $sth3->fetchrow_hashref ) {
15275                 $sth4->execute( $subgroup_id, $l->{branchcode} );
15276             }
15277         }
15278
15279         $dbh->do("DROP TABLE branchrelations");
15280         $dbh->do("DROP TABLE branchcategories");
15281     }
15282
15283     print "Upgrade to $DBversion done (Bug 16735 - Migrate library search groups into the new hierarchical groups)\n";
15284     SetVersion($DBversion);
15285 }
15286
15287 $DBversion = '17.12.00.009';
15288 if ( CheckVersion($DBversion) ) {
15289     $dbh->do(q|
15290         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
15291         (4, 'edit_borrowers', 'Add, modify and view patron information'),
15292         (4, 'view_borrower_infos_from_any_libraries', 'View patron infos from any libraries');
15293     |);
15294
15295     # We are lucky here, there is nothing else to do: flags 4-borrowers did not contain sub permissions
15296
15297     SetVersion( $DBversion );
15298     print "Upgrade to $DBversion done (Bug 18403 - Add the view_borrower_infos_from_any_libraries permission )\n";
15299 }
15300
15301 $DBversion = '17.12.00.010';
15302 if( CheckVersion( $DBversion ) ) {
15303
15304     if( !column_exists( 'library_groups', 'ft_hide_patron_info' ) ) {
15305         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_hide_patron_info tinyint(1) NOT NULL DEFAULT 0 AFTER description" );
15306     }
15307
15308     SetVersion( $DBversion );
15309     print "Upgrade to $DBversion done (Bug 20133 - Add library_groups.ft_hide_patron_info)\n";
15310 }
15311
15312 $DBversion = '17.12.00.011';
15313 if( CheckVersion( $DBversion ) ) {
15314
15315     if( !column_exists( 'library_groups', 'ft_search_groups_opac' ) ) {
15316         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_opac tinyint(1) NOT NULL DEFAULT 0 AFTER ft_hide_patron_info" );
15317         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_search_groups_staff tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_opac" );
15318         $dbh->do( "UPDATE library_groups SET ft_search_groups_staff = 1 AND ft_search_groups_opac = 1 WHERE title = '__SEARCH_GROUPS__'" );
15319     }
15320
15321     SetVersion( $DBversion );
15322     print "Upgrade to $DBversion done (Bug 20157 - Use group 'features' to decide which groups to use for group searching functionality)\n";
15323 }
15324
15325 $DBversion = '17.12.00.012';
15326 if( CheckVersion( $DBversion ) ) {
15327
15328     $dbh->do( q|
15329         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15330         VALUES ('AutoSwitchPatron', '0', '', 'Auto switch to patron', 'YesNo');
15331     |);
15332
15333     SetVersion( $DBversion );
15334     print "Upgrade to $DBversion done (Bug 15752 - Add system preference AutoSwitchPatron)\n";
15335 }
15336
15337 $DBversion = '17.12.00.013';
15338 if( CheckVersion( $DBversion ) ) {
15339
15340     $dbh->do(q|
15341         ALTER TABLE club_enrollments MODIFY date_created timestamp NULL DEFAULT NULL;
15342     |);
15343
15344     SetVersion( $DBversion );
15345     print "Upgrade to $DBversion done (Bug 20175 - Set DEFAULT NULL value for club_enrollments.date_created)\n";
15346 }
15347
15348 $DBversion = '17.12.00.014';
15349 if( CheckVersion( $DBversion ) ) {
15350     $dbh->do( "UPDATE marc_subfield_structure SET kohafield=NULL where kohafield='additionalauthors.author'" );
15351     SetVersion( $DBversion );
15352     print "Upgrade to $DBversion done (Bug 19790 - Remove additionalauthors.author from installer files)\n";
15353 }
15354
15355 $DBversion = '17.12.00.015';
15356 if( CheckVersion( $DBversion ) ) {
15357     $dbh->do(q|
15358         ALTER TABLE borrowers
15359         MODIFY surname MEDIUMTEXT,
15360         MODIFY address MEDIUMTEXT,
15361         MODIFY city MEDIUMTEXT
15362     |);
15363     $dbh->do(q|
15364         ALTER TABLE deletedborrowers
15365         MODIFY surname MEDIUMTEXT,
15366         MODIFY address MEDIUMTEXT,
15367         MODIFY city MEDIUMTEXT
15368     |);
15369
15370     $dbh->do(q|
15371         ALTER TABLE export_format
15372         MODIFY csv_separator VARCHAR(2) NOT NULL DEFAULT ',',
15373         MODIFY field_separator VARCHAR(2),
15374         MODIFY subfield_separator VARCHAR(2)
15375     |);
15376     $dbh->do(q|
15377         ALTER TABLE export_format MODIFY encoding VARCHAR(255) NOT NULL DEFAULT 'utf8'
15378     |);
15379
15380     $dbh->do(q|
15381         ALTER TABLE reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15382     |);
15383     $dbh->do(q|
15384         ALTER TABLE old_reserves MODIFY lowestPriority tinyint(1) NOT NULL DEFAULT 0
15385     |);
15386
15387     SetVersion( $DBversion );
15388     print "Upgrade to $DBversion done (Bug 20144 - Adapt DB structure to work with new SQL modes)\n";
15389 }
15390
15391 $DBversion = '17.12.00.016';
15392 if( CheckVersion( $DBversion ) ) {
15393     $dbh->do(q|SET foreign_key_checks = 0|);
15394     my $sth = $dbh->table_info( '','','','TABLE' );
15395
15396     while ( my ( $cat, $schema, $name, $type, $remarks ) = $sth->fetchrow_array ) {
15397         my $table_sth = $dbh->prepare(qq|SHOW CREATE TABLE $name|);
15398         $table_sth->execute;
15399         my @table = $table_sth->fetchrow_array;
15400         unless ( $table[1] =~ /COLLATE=utf8mb4_unicode_ci/ ) {
15401             # Some users might have done the upgrade to utf8mb4 on their own
15402             # to support supplemental chars (japanese, chinese, etc)
15403             if ( $name eq 'additional_fields' ) {
15404                 $dbh->do(qq|
15405                     ALTER TABLE $name
15406                         DROP KEY `fields_uniq`,
15407                         ADD UNIQUE KEY `fields_uniq` (`tablename` (191), `name` (191))
15408                 |);
15409                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15410             }
15411             elsif ( $name eq 'authorised_values' ) {
15412                 $dbh->do(qq|
15413                     ALTER TABLE $name
15414                         DROP KEY `lib`,
15415                         ADD KEY `lib` (`lib` (191))
15416                 |);
15417                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15418             }
15419             elsif ( $name eq 'borrower_modifications' ) {
15420                 $dbh->do(qq|
15421                     ALTER TABLE $name
15422                         DROP PRIMARY KEY,
15423                         DROP KEY `verification_token`,
15424                         ADD PRIMARY KEY (`verification_token` (191),`borrowernumber`),
15425                         ADD KEY `verification_token` (`verification_token` (191))
15426                 |);
15427                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15428             }
15429             elsif ( $name eq 'columns_settings' ) {
15430                 $dbh->do(qq|
15431                     ALTER TABLE $name
15432                         DROP PRIMARY KEY,
15433                         ADD PRIMARY KEY (`module` (191), `page` (191), `tablename` (191), `columnname` (191))
15434                 |);
15435                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15436             }
15437             elsif ( $name eq 'illrequestattributes' ) {
15438                 $dbh->do(qq|
15439                     ALTER TABLE $name
15440                         DROP PRIMARY KEY,
15441                         ADD PRIMARY KEY  (`illrequest_id`, `type` (191))
15442                 |);
15443                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15444             }
15445             elsif ( $name eq 'items_search_fields' ) {
15446                 $dbh->do(qq|
15447                     ALTER TABLE $name
15448                         DROP PRIMARY KEY,
15449                         ADD PRIMARY KEY (`name` (191))
15450                 |);
15451                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15452             }
15453             elsif ( $name eq 'marc_subfield_structure' ) {
15454                 # In this case we convert each column explicitly
15455                 # to preserve 'tagsubield' collation (utf8mb4_bin)
15456                 $dbh->do(qq|
15457                     ALTER TABLE $name
15458                         MODIFY COLUMN tagfield
15459                             VARCHAR(3) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15460                         MODIFY COLUMN tagsubfield
15461                             VARCHAR(1) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
15462                         MODIFY COLUMN liblibrarian
15463                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15464                         MODIFY COLUMN libopac
15465                             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15466                         MODIFY COLUMN kohafield
15467                             VARCHAR(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15468                         MODIFY COLUMN authorised_value
15469                             VARCHAR(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15470                         MODIFY COLUMN authtypecode
15471                             VARCHAR(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15472                         MODIFY COLUMN value_builder
15473                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15474                         MODIFY COLUMN frameworkcode
15475                             VARCHAR(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
15476                         MODIFY COLUMN seealso
15477                             VARCHAR(1100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15478                         MODIFY COLUMN link
15479                             VARCHAR(80) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
15480                         MODIFY COLUMN defaultvalue
15481                             MEDIUMTEXT COLLATE utf8mb4_unicode_ci default NULL
15482                 |);
15483                 $dbh->do(qq|ALTER TABLE $name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15484             }
15485             elsif ( $name eq 'plugin_data' ) {
15486                 $dbh->do(qq|
15487                     ALTER TABLE $name
15488                         DROP PRIMARY KEY,
15489                         ADD PRIMARY KEY (`plugin_class` (191), `plugin_key` (191))
15490                 |);
15491                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15492             }
15493             elsif ( $name eq 'search_field' ) {
15494                 $dbh->do(qq|
15495                     ALTER TABLE $name
15496                         DROP KEY `name`,
15497                         ADD UNIQUE KEY `name` (`name` (191))
15498                 |);
15499                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15500             }
15501             elsif ( $name eq 'search_marc_map' ) {
15502                 $dbh->do(qq|
15503                     ALTER TABLE $name
15504                         DROP KEY `index_name`,
15505                         ADD UNIQUE KEY `index_name` (`index_name`, `marc_field` (191), `marc_type`)
15506                 |);
15507                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15508             }
15509             elsif ( $name eq 'sms_providers' ) {
15510                 $dbh->do(qq|
15511                     ALTER TABLE $name
15512                         DROP KEY `name`,
15513                         ADD UNIQUE KEY `name` (`name` (191))
15514                 |);
15515                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15516             }
15517             elsif ( $name eq 'tags' ) {
15518                 $dbh->do(qq|
15519                     ALTER TABLE $name
15520                         DROP PRIMARY KEY,
15521                         ADD PRIMARY KEY (`entry` (191))
15522                 |);
15523                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15524             }
15525             elsif ( $name eq 'tags_approval' ) {
15526                 $dbh->do(qq|
15527                     ALTER TABLE $name
15528                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15529                 |);
15530                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15531             }
15532             elsif ( $name eq 'tags_index' ) {
15533                 $dbh->do(qq|
15534                     ALTER TABLE $name
15535                         MODIFY COLUMN `term` VARCHAR(191) NOT NULL
15536                 |);
15537                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15538             }
15539             else {
15540                 $dbh->do(qq|ALTER TABLE $name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci|);
15541             }
15542         }
15543     }
15544     $dbh->do(q|SET foreign_key_checks = 1|);
15545
15546     print "Upgrade to $DBversion done (Bug 18336 - Convert DB tables to utf8mb4 🎁)\n";
15547     SetVersion($DBversion);
15548 }
15549
15550
15551 $DBversion = '17.12.00.017';
15552 if( CheckVersion( $DBversion ) ) {
15553
15554     if( !column_exists( 'items', 'damaged_on' ) ) {
15555         $dbh->do( "ALTER TABLE items ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15556     }
15557     if( !column_exists( 'deleteditems', 'damaged_on' ) ) {
15558         $dbh->do( "ALTER TABLE deleteditems ADD COLUMN damaged_on DATETIME NULL AFTER damaged");
15559     }
15560
15561     SetVersion( $DBversion );
15562     print "Upgrade to $DBversion done (Bug 17672 - Add damaged_on to items and deleteditems tables)\n";
15563 }
15564
15565 $DBversion = '17.12.00.018';
15566 if( CheckVersion( $DBversion ) ) {
15567
15568     $dbh->do( q|
15569         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES  ('BrowseResultSelection','0',NULL,'Enable/Disable browsing search results fromt the bibliographic record detail page in staff client','YesNo')
15570     |);
15571
15572     SetVersion( $DBversion );
15573     print "Upgrade to $DBversion done (Bug 19290 - Add system preference BrowseResultSelection)\n";
15574 }
15575
15576 $DBversion = '17.12.00.019';
15577 if( CheckVersion( $DBversion ) ) {
15578
15579     $dbh->do(q|UPDATE auth_subfield_structure SET hidden=1 WHERE hidden<>0|);
15580
15581     SetVersion( $DBversion );
15582     print "Upgrade to $DBversion done (Bug 20074 - Auth_subfield_structure changes hidden attribute)\n";
15583 }
15584
15585 $DBversion = '17.12.00.020';
15586 if( CheckVersion( $DBversion ) ) {
15587
15588     $dbh->do(q|
15589         INSERT IGNORE INTO language_descriptions(subtag, type, lang, description)
15590         VALUES ('vi', 'language', 'de', 'Vietnamesisch')
15591     |);
15592
15593     $dbh->do(q|
15594         UPDATE language_descriptions SET description = 'Tiếng Việt'
15595         WHERE subtag = 'vi' and type = 'language' and lang = 'vi'
15596     |);
15597
15598     SetVersion( $DBversion );
15599     print "Upgrade to $DBversion done (Bug 20082 - Update descriptions of Vietnamese language)\n";
15600 }
15601
15602 $DBversion = '17.12.00.021';
15603 if( CheckVersion( $DBversion ) ) {
15604
15605     $dbh->do(q|
15606         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
15607         ('PurgeSuggestionsOlderThan', '', NULL, 'Default value for cronjob purge_suggestions.pl', 'Integer');
15608     |);
15609
15610     SetVersion( $DBversion );
15611     print "Upgrade to $DBversion done (Bug 13287 - Add system preference PurgeSuggestionsOlderThan)\n";
15612 }
15613
15614 $DBversion = '17.12.00.022';
15615 if( CheckVersion( $DBversion ) ) {
15616
15617     if( !column_exists( 'currency', 'p_sep_by_space' ) ) {
15618         $dbh->do(q|
15619             ALTER TABLE currency ADD COLUMN p_sep_by_space tinyint(1) default 0 after archived
15620         |);
15621     }
15622
15623     SetVersion( $DBversion );
15624     print "Upgrade to $DBversion done (Bug 4078 - Add column currency.p_sep_by_space)\n";
15625 }
15626
15627 $DBversion = '17.12.00.023';
15628 if( CheckVersion( $DBversion ) ) {
15629     $dbh->do(q{
15630         DELETE FROM systempreferences
15631         WHERE variable='checkdigit'
15632     });
15633
15634     SetVersion( $DBversion );
15635     print "Upgrade to $DBversion done (Bug 20264 - Remove system preference 'checkdigit')\n";
15636 }
15637
15638 $DBversion = '17.12.00.024';
15639 if( CheckVersion( $DBversion ) ) {
15640
15641     $dbh->do(q{
15642         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15643         VALUES ('SelfCheckInMainUserBlock', '', '70|10', 'Add a block of HTML that will display on the self check-in screen.', 'Textarea');
15644     });
15645
15646     $dbh->do(q{
15647         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15648         VALUES ('SelfCheckInModule', 0, NULL, 'Enable the standalone self-checkin module.', 'YesNo');
15649     });
15650
15651     $dbh->do(q{
15652         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15653         VALUES ('SelfCheckInModuleUserID', NULL, NULL, 'Patron ID (borrowernumber) to be allowed on the self-checkin module.', 'Integer');
15654     });
15655
15656     $dbh->do(q{
15657         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15658         VALUES ('SelfCheckInTimeout', 120, NULL, 'Define the number of seconds before the self check-in module times out.', 'Integer');
15659     });
15660
15661     $dbh->do(q{
15662         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15663         VALUES ('SelfCheckInUserCSS', '', NULL, 'Add CSS to be included in the self check-in module in an embedded <style> tag.', 'free');
15664     });
15665
15666     $dbh->do(q{
15667         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
15668         VALUES ('SelfCheckInUserJS', '', NULL, 'Define custom javascript for inclusion in the self check-in module.', 'free');
15669     });
15670
15671     # Add new userflag for self check
15672     $dbh->do(q{
15673         INSERT IGNORE INTO userflags (bit,flag,flagdesc,defaulton) VALUES
15674             (23,'self_check','Self check modules',0);
15675     });
15676
15677     # Add self check-in module subpermission
15678     $dbh->do(q{
15679         INSERT IGNORE INTO permissions (module_bit,code,description)
15680         VALUES (23, 'self_checkin_module', 'Log into the self check-in module');
15681     });
15682
15683     # Add self check-in module subpermission
15684     $dbh->do(q{
15685         INSERT IGNORE INTO permissions (module_bit,code,description)
15686         VALUES (23, 'self_checkout_module', 'Perform self checkout at the OPAC. It should be used for the patron matching the AutoSelfCheckID');
15687     });
15688
15689     # Update patrons with self_checkout permission
15690     # IMPORTANT: Needs to happen before removing the old subpermission
15691     $dbh->do(q{
15692         UPDATE user_permissions
15693         SET module_bit = 23,
15694                   code = 'self_checkout_module'
15695         WHERE module_bit = 1 AND code = 'self_checkout';
15696     });
15697
15698     # Remove old self_checkout permission
15699     $dbh->do(q{
15700         DELETE IGNORE FROM permissions
15701         WHERE  code='self_checkout';
15702     });
15703
15704     SetVersion( $DBversion );
15705     print "Upgrade to $DBversion done (Bug 15492 - Add a standalone self-checkin module)\n";
15706 }
15707
15708 $DBversion = '17.12.00.025';
15709 if( CheckVersion( $DBversion ) ) {
15710     $dbh->do(q|
15711         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15712         VALUES ('StaffLoginInstructions','','HTML to go into the login box for the staff client',NULL,'Free')
15713     |);
15714     $dbh->do(q|
15715         UPDATE systempreferences
15716         SET variable = 'OpacLoginInstructions'
15717         WHERE variable = 'NoLoginInstructions'
15718     |);
15719
15720     SetVersion( $DBversion );
15721     print "Upgrade to $DBversion done (Bug 20291 - Add StaffLoginInstructions system preference and rename NoLoginInstructions with OpacLoginInstructions)\n";
15722 }
15723
15724 $DBversion = '17.12.00.026';
15725 if( CheckVersion( $DBversion ) ) {
15726     if( !column_exists( 'issuingrules', 'suspension_chargeperiod' ) ) {
15727         $dbh->do(q|
15728             ALTER TABLE issuingrules ADD COLUMN suspension_chargeperiod int(11) DEFAULT '1' AFTER maxsuspensiondays;
15729         |);
15730     }
15731
15732     SetVersion( $DBversion );
15733     print "Upgrade to $DBversion done (Bug 19804 - Add issuingrules.suspension_chargeperiod)\n";
15734 }
15735
15736 $DBversion = '17.12.00.027';
15737 if( CheckVersion( $DBversion ) ) {
15738     $dbh->do(q|
15739         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15740         VALUES ('UseACQFrameworkForBiblioRecords','0','','Use the ACQ framework for the catalog details','YesNo')
15741     |);
15742
15743     SetVersion( $DBversion );
15744     print "Upgrade to $DBversion done (Bug 19289 - Add system preference UseACQFrameworkForBiblioRecords)\n";
15745 }
15746
15747 $DBversion = '17.12.00.028';
15748 if( CheckVersion( $DBversion ) ) {
15749     if( !column_exists( 'marc_tag_structure', 'ind1_defaultvalue' ) ) {
15750         $dbh->do(q|
15751             ALTER TABLE marc_tag_structure
15752             ADD COLUMN ind2_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value,
15753             ADD COLUMN ind1_defaultvalue VARCHAR(1) NOT NULL DEFAULT '' AFTER authorised_value;
15754         |);
15755     }
15756
15757     SetVersion( $DBversion );
15758     print "Upgrade to $DBversion done (Bug 9701 - Add default indicators (marc_tag_structure.indX_defaultvalue))\n";
15759 }
15760
15761 $DBversion = '17.12.00.029';
15762 if( CheckVersion( $DBversion ) ) {
15763     my $pref =
15764 q|# PERSO_NAME  100 600 696 700 796 800 896
15765 marc21, 100, ind1:auth1
15766 marc21, 600, ind1:auth1, ind2:thesaurus
15767 marc21, 696, ind1:auth1
15768 marc21, 700, ind1:auth1
15769 marc21, 796, ind1:auth1
15770 marc21, 800, ind1:auth1
15771 marc21, 896, ind1:auth1
15772 # CORPO_NAME  110 610 697 710 797 810 897
15773 marc21, 110, ind1:auth1
15774 marc21, 610, ind1:auth1, ind2:thesaurus
15775 marc21, 697, ind1:auth1
15776 marc21, 710, ind1:auth1
15777 marc21, 797, ind1:auth1
15778 marc21, 810, ind1:auth1
15779 marc21, 897, ind1:auth1
15780 # MEETI_NAME    111 611 698 711 798 811 898
15781 marc21, 111, ind1:auth1
15782 marc21, 611, ind1:auth1, ind2:thesaurus
15783 marc21, 698, ind1:auth1
15784 marc21, 711, ind1:auth1
15785 marc21, 798, ind1:auth1
15786 marc21, 811, ind1:auth1
15787 marc21, 898, ind1:auth1
15788 # UNIF_TITLE        130 440 630 699 730 799 830 899 / 240
15789 marc21, 130, ind1:auth2
15790 marc21, 240, , ind2:auth2
15791 marc21, 440, , ind2:auth2
15792 marc21, 630, ind1:auth2, ind2:thesaurus
15793 marc21, 699, ind1:auth2
15794 marc21, 730, ind1:auth2
15795 marc21, 799, ind1:auth2
15796 marc21, 830, , ind2:auth2
15797 marc21, 899, ind1:auth2
15798 # CHRON_TERM    648
15799 marc21, 648, , ind2:thesaurus
15800 # TOPIC_TERM      650 654 656 657 658 690
15801 marc21, 650, , ind2:thesaurus
15802 # GEOGR_NAME   651 662 691 / 751
15803 marc21, 651, , ind2:thesaurus
15804 # GENRE/FORM    655
15805 marc21, 655, , ind2:thesaurus
15806
15807 # UNIMARC: Always copy the indicators from the authority
15808 unimarc, *, ind1:auth1, ind2:auth2|;
15809
15810     $dbh->do( q|
15811         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15812         VALUES ( 'AuthorityControlledIndicators', ?, 'Authority controlled indicators per biblio field', NULL, 'Free' );
15813     |, undef, $pref );
15814
15815     SetVersion( $DBversion );
15816     print "Upgrade to $DBversion done (Bug 14769 - Authorities merge: Set correct indicators in biblio field (new system preference AuthorityControlledIndicators))\n";
15817 }
15818
15819 $DBversion = '17.12.00.030';
15820 if( CheckVersion( $DBversion ) ) {
15821     $dbh->do(q|
15822         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
15823         VALUES ('NovelistSelectStaffProfile',NULL,'Novelist staff client user Profile',NULL,'free')
15824     |);
15825
15826     SetVersion( $DBversion );
15827     print "Upgrade to $DBversion done (Bug 19882 - Add system preference NovelistSelectStaffProfile)\n";
15828 }
15829
15830 $DBversion = '17.12.00.031';
15831 if( CheckVersion( $DBversion ) ) {
15832     $dbh->do(q|
15833         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
15834         VALUES ('MarcFieldDocURL', NULL, NULL, 'URL used for MARC field documentation. Following substitutions are available: {MARC} = marc flavour, eg. \"MARC21\" or \"UNIMARC\". {FIELD} = field number, eg. \"000\" or \"048\". {LANG} = user language, eg. \"en\" or \"fi-FI\"', 'free')
15835     |);
15836
15837     SetVersion( $DBversion );
15838     print "Upgrade to $DBversion done (Bug 11674 - Add system preference MarcFieldDocURL)\n";
15839 }
15840
15841 $DBversion = '17.12.00.032';
15842 if( CheckVersion( $DBversion ) ) {
15843     $dbh->do(q|
15844         UPDATE letter SET code = "SERIAL_ALERT" WHERE code = "RLIST";
15845     |);
15846     $dbh->do(q|
15847         UPDATE letter SET name = "New serial issue" WHERE name = "Routing List";
15848     |);
15849     $dbh->do(q|
15850         UPDATE subscription SET letter = "SERIAL_ALERT" WHERE letter = "RLIST";
15851     |);
15852
15853     SetVersion( $DBversion );
15854     print "Upgrade to $DBversion done (Bug 19794 - Rename RLIST notice to SERIAL_ALERT)\n";
15855 }
15856
15857 $DBversion = '17.12.00.033';
15858 if( CheckVersion( $DBversion ) ) {
15859     if ( !column_exists( 'accountlines', 'payment_type' ) ) {
15860         $dbh->do(q{
15861             ALTER TABLE accountlines ADD payment_type varchar(80) default NULL AFTER accounttype
15862         });
15863     }
15864
15865     $dbh->do(q{
15866         INSERT IGNORE INTO authorised_value_categories( category_name ) VALUES ('PAYMENT_TYPE')
15867     });
15868
15869     SetVersion( $DBversion );
15870     print "Upgrade to $DBversion done (Bug 18786 - Add ability to create custom payment types)\n";
15871 }
15872
15873 $DBversion = '17.12.00.034';
15874 if( CheckVersion( $DBversion ) ) {
15875
15876     $dbh->do( q{
15877         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Void Payment')
15878     } );
15879
15880     SetVersion( $DBversion );
15881     print "Upgrade to $DBversion done (Bug 18790 - Add ability to void payment)\n";
15882 }
15883
15884 $DBversion = '17.12.00.035';
15885 if( CheckVersion( $DBversion ) ) {
15886     my ( $original_value ) = $dbh->selectrow_array(q|
15887         SELECT value FROM systempreferences WHERE variable="MarkLostItemsAsReturned"
15888     |);
15889     if ( $original_value and $original_value eq '1' ) {
15890         $dbh->do(q{
15891             UPDATE systempreferences
15892             SET type="multiple",
15893                 options="batchmod|moredetail|cronjob|additem",
15894                 value="batchmod,moredetail,cronjob,additem"
15895             WHERE variable="MarkLostItemsAsReturned"
15896         });
15897     } else {
15898         $dbh->do(q{
15899             UPDATE systempreferences
15900             SET type="multiple",
15901                 options="batchmod|moredetail|cronjob|additem",
15902                 value=""
15903             WHERE variable="MarkLostItemsAsReturned"
15904         });
15905     }
15906
15907     SetVersion( $DBversion );
15908     print "Upgrade to $DBversion done (Bug 19974 - Make MarkLostItemsAsReturned multiple)\n";
15909 }
15910
15911 $DBversion = '17.12.00.036';
15912 if( CheckVersion( $DBversion ) ) {
15913
15914     $dbh->do( q{
15915         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('CanMarkHoldsToPullAsLost','do_not_allow','do_not_allow|allow|allow_and_notify','Add a button to the "Holds to pull" screen to mark an item as lost and notify the patron.','Choice');
15916     } );
15917     $dbh->do( q{
15918         INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('reserves', 'CANCEL_HOLD_ON_LOST', '', 'Hold has been cancelled', 0, "Hold has been cancelled", "Dear [% borrower.firstname %] [% borrower.surname %],\n\nWe regret to inform you, that the following item can not be provided due to it being missing. Your hold was cancelled.\n\nTitle: [% biblio.title %]\nAuthor: [% biblio.author %]\nCopy: [% item.copynumber %]\nLocation: [% branch.branchname %]", 'email', 'default');
15919     } );
15920     $dbh->do( q{
15921         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES ('UpdateItemWhenLostFromHoldList','',NULL,'This is a list of values to update an item when it is marked as lost from the holds to pull screen','Free');
15922     } );
15923     $dbh->do( q{
15924         UPDATE systempreferences SET options="batchmod|moredetail|cronjob|additem|pendingreserves" WHERE variable="MarkLostItemsAsReturned";
15925     } );
15926
15927     SetVersion( $DBversion );
15928     print "Upgrade to $DBversion done (Bug 19287 - Add ability to mark an item 'Lost' from 'Holds to pull' list (CanMarkHoldsToPullAsLost, UpdateItemWhenLostFromHoldList and CANCEL_HOLD_ON_LOST))\n";
15929 }
15930
15931 $DBversion = '17.12.00.037';
15932 if( CheckVersion( $DBversion ) ) {
15933
15934     SetVersion( $DBversion );
15935     print "Upgrade to $DBversion done (This change has been reverted, nothing done!)\n";
15936 }
15937
15938 $DBversion = '17.12.00.038';
15939 if( CheckVersion( $DBversion ) ) {
15940
15941     $dbh->do( q{
15942         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'slo' WHERE iso639_2_code = 'slk' AND rfc4646_subtag = 'sk';
15943     } );
15944
15945     SetVersion( $DBversion );
15946     print "Upgrade to $DBversion done (Bug 20245 - Use Bibliographic code value for Slovak language)\n";
15947 }
15948
15949 $DBversion = '17.12.00.039';
15950 if( CheckVersion( $DBversion ) ) {
15951
15952     $dbh->do( q{
15953         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'baq' WHERE iso639_2_code = 'eus' AND rfc4646_subtag = 'eu';
15954     } );
15955     $dbh->do( q{
15956         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'mao' WHERE iso639_2_code = 'mri' AND rfc4646_subtag = 'mi';
15957     } );
15958     $dbh->do( q{
15959         UPDATE language_rfc4646_to_iso639 SET iso639_2_code = 'alb' WHERE iso639_2_code = 'sqi' AND rfc4646_subtag = 'sq';
15960     } );
15961
15962     SetVersion( $DBversion );
15963     print "Upgrade to $DBversion done (Bug 20482 - Use Bibliographic code value for Basque, Maori and Albanian languages)\n";
15964 }
15965
15966 $DBversion = '17.12.00.040';
15967 if( CheckVersion( $DBversion ) ) {
15968
15969     $dbh->do( q{
15970         INSERT IGNORE INTO systempreferences ( value, variable, options, explanation, type )
15971         VALUES ( '0', 'ProtectSuperlibrarianPrivileges', NULL, 'If enabled, non-superlibrarians cannot set superlibrarian privileges', 'YesNo' )
15972     } );
15973
15974     SetVersion( $DBversion );
15975     print "Upgrade to $DBversion done (Bug 20100 - Add new system preference ProtectSuperlibrarianPrivileges)\n";
15976 }
15977
15978 $DBversion = '17.12.00.041';
15979 if( CheckVersion( $DBversion ) ) {
15980
15981     $dbh->do( q{
15982         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (13, 'access_files', 'Access to the files stored on the server');
15983     } );
15984
15985     SetVersion( $DBversion );
15986     print "Upgrade to $DBversion done (Bug 11317 - Add a new permission to access files stored on the server)\n";
15987 }
15988
15989 $DBversion = '17.12.00.042';
15990 if( CheckVersion( $DBversion ) ) {
15991
15992     if (!TableExists('oauth_access_tokens')) {
15993         $dbh->do(q{
15994             CREATE TABLE oauth_access_tokens (
15995                 `access_token` VARCHAR(191) NOT NULL,
15996                 `client_id`    VARCHAR(191) NOT NULL,
15997                 `expires`      INT NOT NULL,
15998                 PRIMARY KEY (`access_token`)
15999             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16000         });
16001     }
16002
16003     SetVersion( $DBversion );
16004     print "Upgrade to $DBversion done (Bug 20402 - Implement OAuth2 authentication for REST API)\n";
16005 }
16006
16007 $DBversion = '17.12.00.043';
16008 if(CheckVersion($DBversion)) {
16009
16010     if (!TableExists('api_keys')) {
16011         $dbh->do(q{
16012             CREATE TABLE `api_keys` (
16013                 `client_id`   VARCHAR(191) NOT NULL,
16014                 `secret`      VARCHAR(191) NOT NULL,
16015                 `description` VARCHAR(255) NOT NULL,
16016                 `patron_id`   INT(11) NOT NULL,
16017                 `active`      TINYINT(1) DEFAULT 1 NOT NULL,
16018                 PRIMARY KEY `client_id` (`client_id`),
16019                 UNIQUE KEY `secret` (`secret`),
16020                 KEY `patron_id` (`patron_id`),
16021                 CONSTRAINT `api_keys_fk_patron_id`
16022                   FOREIGN KEY (`patron_id`)
16023                   REFERENCES `borrowers` (`borrowernumber`)
16024                   ON DELETE CASCADE ON UPDATE CASCADE
16025             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16026         });
16027     }
16028
16029     print "Upgrade to $DBversion done (Bug 20568 - Add API key management interface for patrons)\n";
16030     SetVersion($DBversion);
16031 }
16032
16033 $DBversion = '17.12.00.044';
16034 if(CheckVersion($DBversion)) {
16035
16036     $dbh->do(q{
16037         INSERT IGNORE INTO systempreferences (`variable`,`value`,`options`,`explanation`,`type`)
16038         VALUES
16039             ('RESTOAuth2ClientCredentials','0',NULL,'If enabled, the OAuth2 client credentials flow is enabled for the REST API.','YesNo');
16040     });
16041
16042     print "Upgrade to $DBversion done (Bug 20624 - Disable OAuth2 client credentials grant by default)\n";
16043     SetVersion($DBversion);
16044 }
16045
16046 $DBversion = '18.05.00.000';
16047 if( CheckVersion( $DBversion ) ) {
16048     SetVersion( $DBversion );
16049     print "Upgrade to $DBversion done (Koha 18.05)\n";
16050 }
16051
16052 $DBversion = '18.06.00.000';
16053 if( CheckVersion( $DBversion ) ) {
16054     SetVersion( $DBversion );
16055     print "Upgrade to $DBversion done (Koha 18.06 - It's Adventure time!)\n";
16056 }
16057
16058 $DBversion = '18.06.00.001';
16059 if( CheckVersion( $DBversion ) ) {
16060     $dbh->do(q{UPDATE permissions SET description = 'Manage budgets' WHERE code = 'period_manage';});
16061     $dbh->do(q{UPDATE permissions SET description = 'Manage funds' WHERE code = 'budget_manage';});
16062     $dbh->do(q{UPDATE permissions SET description = 'Modify funds (can''t create lines, but can modify existing ones)' WHERE code = 'budget_modify';});
16063     $dbh->do(q{UPDATE permissions SET description = 'Manage baskets and order lines' WHERE code = 'order_manage';});
16064     $dbh->do(q{UPDATE permissions SET description = 'Manage all baskets and order lines, regardless of restrictions on them' WHERE code = 'order_manage_all';});
16065     $dbh->do(q{UPDATE permissions SET description = 'Manage basket groups' WHERE code = 'group_manage';});
16066     $dbh->do(q{UPDATE permissions SET description = 'Receive orders and manage shipments' WHERE code = 'order_receive';});
16067     $dbh->do(q{UPDATE permissions SET description = 'Add and delete funds (but can''t modify funds)' WHERE code = 'budget_add_del';});
16068     $dbh->do(q{UPDATE permissions SET description = 'Manage all funds' WHERE code = 'budget_manage_all';});
16069     SetVersion( $DBversion );
16070     print "Upgrade to $DBversion done (Bug 3849- Improve descriptions of granular acquisition permissions)\n";
16071 }
16072
16073 $DBversion = '18.06.00.002';
16074 if( CheckVersion( $DBversion ) ) {
16075     $dbh->do(q{DELETE FROM userflags WHERE bit = 12 AND flag = 'management';});
16076     $dbh->do(q{UPDATE borrowers SET flags = flags - ( flags & (1<<12) ) WHERE flags & (1 << 12);});
16077     SetVersion( $DBversion );
16078     print "Upgrade to $DBversion done (Bug 2426 - Remove deprecated management permission)\n";
16079 }
16080
16081 $DBversion = '18.06.00.003';
16082 if( CheckVersion( $DBversion ) ) {
16083     $dbh->do( "ALTER TABLE search_field CHANGE COLUMN type type ENUM('', 'string', 'date', 'number', 'boolean', 'sum', 'isbn', 'stdno') NOT NULL COMMENT 'what type of data this holds, relevant when storing it in the search engine'" );
16084     SetVersion( $DBversion );
16085     print "Upgrade to $DBversion done (Bug 20073 - Add new types for Elasticsearch fields)\n";
16086 }
16087
16088 $DBversion = '18.06.00.004';
16089 if( CheckVersion( $DBversion ) ) {
16090
16091     # Add 'Manual Credit' offset type
16092     $dbh->do(q{
16093         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Manual Credit');
16094     });
16095
16096     # Fix wrong account offsets / Manual credits
16097     $dbh->do(q{
16098         UPDATE account_offsets
16099         SET credit_id=debit_id,
16100             debit_id=NULL,
16101             type='Manual Credit'
16102         WHERE amount < 0 AND
16103               type='Manual Debit' AND
16104               debit_id IN
16105                 (SELECT accountlines_id AS debit_id
16106                  FROM accountlines
16107                  WHERE accounttype='C');
16108     });
16109
16110     # Fix wrong account offsets / Manually forgiven amounts
16111     $dbh->do(q{
16112         UPDATE account_offsets
16113         SET credit_id=debit_id,
16114             debit_id=NULL,
16115             type='Writeoff'
16116         WHERE amount < 0 AND
16117               type='Manual Debit' AND
16118               debit_id IN
16119                 (SELECT accountlines_id AS debit_id
16120                  FROM accountlines
16121                  WHERE accounttype='FOR');
16122     });
16123
16124     SetVersion( $DBversion );
16125     print "Upgrade to $DBversion done (Bug 20980 - Manual credit offsets are stored as debits)\n";
16126 }
16127
16128 $DBversion = '18.06.00.005';
16129 if( CheckVersion( $DBversion ) ) {
16130     unless ( column_exists('aqorders', 'created_by') ) {
16131         $dbh->do( "ALTER TABLE aqorders ADD COLUMN created_by int(11) NULL DEFAULT NULL AFTER quantityreceived;" );
16132         unless ( foreign_key_exists('aqorders', 'aqorders_created_by') ) {
16133             $dbh->do( "ALTER TABLE aqorders ADD CONSTRAINT aqorders_created_by FOREIGN KEY (created_by) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;" );
16134         }
16135         $dbh->do( "UPDATE aqbasket LEFT JOIN borrowers ON ( aqbasket.authorisedby = borrowers.borrowernumber ) SET aqbasket.authorisedby = NULL WHERE borrowers.borrowernumber IS NULL;" );
16136         $dbh->do( "UPDATE aqorders LEFT JOIN aqbasket ON ( aqorders.basketno = aqbasket.basketno ) SET aqorders.created_by = aqbasket.authorisedby WHERE aqorders.created_by IS NULL;" );
16137     }
16138     SetVersion( $DBversion );
16139     print "Upgrade to $DBversion done (Bug 12395 - Save order line's creator)\n";
16140 }
16141
16142 $DBversion = '18.06.00.006';
16143 if( CheckVersion( $DBversion ) ) {
16144     unless ( column_exists('patron_lists', 'shared') ) {
16145         $dbh->do( "ALTER TABLE patron_lists ADD COLUMN shared tinyint(1) default 0 AFTER owner;" );
16146     }
16147     SetVersion( $DBversion );
16148     print "Upgrade to $DBversion done (Bug 19524 - Share patron lists between staff)\n";
16149 }
16150
16151 $DBversion = '18.06.00.007';
16152 if( CheckVersion( $DBversion ) ) {
16153     $dbh->do( "INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'currencies_manage', 'Manage currencies and exchange rates');" );
16154     $dbh->do(q{
16155         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
16156             SELECT borrowernumber, 11, 'currencies_manage' FROM borrowers WHERE flags & (1 << 3) OR borrowernumber IN
16157             (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16158     });
16159     SetVersion( $DBversion );
16160     print "Upgrade to $DBversion done (Bug 7651 - Add separate permission for managing currencies and exchange rates)\n";
16161 }
16162
16163 $DBversion = '18.06.00.008';
16164 if( CheckVersion( $DBversion ) ) {
16165     $dbh->do( "ALTER TABLE marc_modification_template_actions CHANGE action action ENUM('delete_field','add_field','update_field','move_field','copy_field','copy_and_replace_field')" );
16166     SetVersion( $DBversion );
16167     print "Upgrade to $DBversion done (Bug 13560 - need an add option in marc modification templates)\n";
16168 }
16169
16170 $DBversion = '18.06.00.009';
16171 if( CheckVersion( $DBversion ) ) {
16172     $dbh->do( "
16173         CREATE TABLE IF NOT EXISTS aqinvoice_adjustments (
16174             adjustment_id int(11) NOT NULL AUTO_INCREMENT,
16175             invoiceid int(11) NOT NULL,
16176             adjustment decimal(28,6),
16177             reason varchar(80) default NULL,
16178             note mediumtext default NULL,
16179             budget_id int(11) default NULL,
16180             encumber_open smallint(1) NOT NULL default 1,
16181             timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
16182             PRIMARY KEY (adjustment_id),
16183             CONSTRAINT aqinvoice_adjustments_fk_invoiceid FOREIGN KEY (invoiceid) REFERENCES aqinvoices (invoiceid) ON DELETE CASCADE ON UPDATE CASCADE,
16184             CONSTRAINT aqinvoice_adjustments_fk_budget_id FOREIGN KEY (budget_id) REFERENCES aqbudgets (budget_id) ON DELETE SET NULL ON UPDATE CASCADE
16185         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
16186         " );
16187     $dbh->do("INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ADJ_REASON')");
16188     SetVersion( $DBversion );
16189     print "Upgrade to $DBversion done (Bug 19166 - Add the ability to add adjustments to an invoice)\n";
16190 }
16191
16192 $DBversion = '18.06.00.010';
16193 if( CheckVersion( $DBversion ) ) {
16194     $dbh->do(q{
16195         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`)
16196         VALUES
16197             ('circulation', 'ACCOUNT_PAYMENT', '', 'Account payment', 0, 'Account payment', '[%- USE Price -%]\r\nA payment of [% credit.amount * -1 | $Price %] has been applied to your account.\r\n\r\nThis payment affected the following fees:\r\n[%- FOREACH o IN offsets %]\r\nDescription: [% o.debit.description %]\r\nAmount paid: [% o.amount * -1 | $Price %]\r\nAmount remaining: [% o.debit.amountoutstanding | $Price %]\r\n[% END %]', 'email', 'default'),
16198                 ('circulation', 'ACCOUNT_WRITEOFF', '', 'Account writeoff', 0, 'Account writeoff', '[%- USE Price -%]\r\nAn account writeoff of [% credit.amount * -1 | $Price %] has been applied to your account.\r\n\r\nThis writeoff affected the following fees:\r\n[%- FOREACH o IN offsets %]\r\nDescription: [% o.debit.description %]\r\nAmount paid: [% o.amount * -1 | $Price %]\r\nAmount remaining: [% o.debit.amountoutstanding | $Price %]\r\n[% END %]', 'email', 'default');
16199     });
16200     $dbh->do(q{
16201         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`)
16202         VALUES ('UseEmailReceipts','0','','Send email receipts for payments and write-offs','YesNo')
16203     });
16204     SetVersion( $DBversion );
16205     print "Upgrade to $DBversion done (Bug 19191 - Add ability to email receipts for account payments and write-offs)\n";
16206 }
16207
16208 $DBversion = '18.06.00.011';
16209 if( CheckVersion( $DBversion ) ) {
16210     unless( column_exists( 'issues', 'noteseen' ) ) {
16211         $dbh->do(q|ALTER TABLE issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16212     }
16213
16214     unless( column_exists( 'old_issues', 'noteseen' ) ) {
16215         $dbh->do(q|ALTER TABLE old_issues ADD COLUMN noteseen int(1) default NULL AFTER notedate|);
16216     }
16217     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 1, 'manage_checkout_notes', 'Mark checkout notes as seen/not seen');|);
16218     SetVersion( $DBversion );
16219     print "Upgrade to $DBversion done (Bug 17698: Add column issues.noteseen and old_issues.noteseen)\n";
16220 }
16221
16222 $DBversion = '18.06.00.012';
16223 if( CheckVersion( $DBversion ) ) {
16224     $dbh->do(q|INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (11, 'suggestions_manage', 'Manage purchase suggestions');|);
16225     $dbh->do(q|INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code) SELECT borrowernumber, 11, 'suggestions_manage' FROM borrowers WHERE flags & (1 << 2);|);
16226     SetVersion( $DBversion );
16227     print "Upgrade to $DBversion done (Bug 11911 - Add separate permission for managing suggestions)\n";
16228 }
16229
16230 $DBversion = '18.06.00.013';
16231 if( CheckVersion( $DBversion ) ) {
16232     $dbh->do(q{
16233         INSERT IGNORE INTO `account_offset_types` (`type`) VALUES ('Credit Applied');
16234     });
16235     SetVersion( $DBversion );
16236     print "Upgrade to $DBversion done (Bug 20997 - Add Koha::Account::Line::apply)\n";
16237 }
16238
16239 $DBversion = '18.06.00.014';
16240 if( CheckVersion( $DBversion ) ) {
16241     $dbh->do(q{
16242             INSERT IGNORE INTO  systempreferences (variable, value, options, explanation) VALUES ('HidePersonalPatronDetailOnCirculation', 0, 'YesNo', 'Hide patrons phone number, email address, street address and city in the circulation page');
16243     });
16244     SetVersion( $DBversion );
16245     print "Upgrade to $DBversion done (Bug 21121 - New syspref to allow hiding of private patron data in circulation page)\n";
16246 }
16247
16248 $DBversion = '18.06.00.015';
16249 if( CheckVersion( $DBversion ) ) {
16250     $dbh->do(q{DELETE FROM systempreferences where variable="OCLCAffiliateID";});
16251     $dbh->do(q{DELETE FROM systempreferences where variable="XISBN";});
16252     $dbh->do(q{DELETE FROM systempreferences where variable="XISBNDailyLimit";});
16253     SetVersion( $DBversion );
16254     print "Upgrade to $DBversion done (Bug 21226 - Remove prefs OCLCAffiliateID, XISBN and XISBNDailyLimit)\n";
16255 }
16256
16257 $DBversion = '18.06.00.016';
16258 if( CheckVersion( $DBversion ) ) {
16259     my $dtf  = Koha::Database->new->schema->storage->datetime_parser;
16260     my $days = C4::Context->preference('MaxPickupDelay') || 7;
16261     my $date = dt_from_string()->add( days => $days );
16262     my $sql  = q|UPDATE reserves SET expirationdate = ? WHERE expirationdate IS NULL AND waitingdate IS NOT NULL|;
16263     $dbh->do( $sql, undef, $dtf->format_datetime($date) );
16264     SetVersion( $DBversion );
16265     print "Upgrade to $DBversion done (Bug 20773 - expirationdate filled for waiting holds)\n";
16266 }
16267
16268 $DBversion = '18.06.00.017';
16269 if( CheckVersion( $DBversion ) ) {
16270     $dbh->do(q|INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('ROADTYPE');|);
16271     SetVersion( $DBversion );
16272     print "Upgrade to $DBversion done (Bug 21144: Add ROADTYPE to default authorised values categories)\n";
16273 }
16274
16275 $DBversion = '18.06.00.018';
16276 if( CheckVersion( $DBversion ) ) {
16277     $dbh->do( q|
16278 UPDATE items LEFT JOIN issues USING (itemnumber)
16279 SET items.onloan = NULL
16280 WHERE issues.itemnumber IS NULL
16281     |);
16282     SetVersion( $DBversion );
16283     print "Upgrade to $DBversion done (Bug 20487: Clear items.onloan for unissued items)\n";
16284 }
16285
16286 $DBversion = '18.06.00.019';
16287 if( CheckVersion( $DBversion ) ) {
16288     $dbh->do( q|
16289 INSERT IGNORE INTO columns_settings (module, page, tablename, columnname, cannot_be_toggled, is_hidden) VALUES
16290 ("circ", "circulation", "issues-table", "collection", 0, 1),
16291 ("members", "moremember", "issues-table", "collection", 0, 1);
16292     |);
16293     SetVersion( $DBversion );
16294     print "Upgrade to $DBversion done (Bug 19719: Default to hiding collection code column)\n";
16295 }
16296
16297 $DBversion = '18.06.00.020';
16298 if( CheckVersion( $DBversion ) ) {
16299     if( !column_exists( 'branch_borrower_circ_rules', 'max_holds' ) ) {
16300         $dbh->do(q{
16301             ALTER TABLE branch_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16302         });
16303     }
16304     if( !column_exists( 'default_borrower_circ_rules', 'max_holds' ) ) {
16305         $dbh->do(q{
16306             ALTER TABLE default_borrower_circ_rules ADD COLUMN max_holds INT(4) NULL DEFAULT NULL AFTER maxonsiteissueqty
16307         });
16308     }
16309     SetVersion( $DBversion );
16310     print "Upgrade to $DBversion done (Bug 15524 - Set limit on maximum possible holds per patron by category)\n";
16311 }
16312
16313 $DBversion = '18.06.00.021';
16314 if( CheckVersion( $DBversion ) ) {
16315     my $dbh = C4::Context->dbh;
16316     unless ( C4::Context->preference('NorwegianPatronDBEnable') ) {
16317         $dbh->do(q|
16318             DELETE FROM systempreferences
16319             WHERE variable IN ('NorwegianPatronDBEnable', 'NorwegianPatronDBEndpoint', 'NorwegianPatronDBUsername', 'NorwegianPatronDBPassword', 'NorwegianPatronDBSearchNLAfterLocalHit')
16320         |);
16321         if ( TableExists('borrower_sync') ) {
16322             $dbh->do(q|DROP TABLE borrower_sync|);
16323         }
16324     }
16325     SetVersion( $DBversion );
16326     print "Upgrade to $DBversion done (Bug 21068 - Remove system preferences NorwegianPatronDB*)\n";
16327 }
16328
16329 $DBversion = '18.06.00.022';
16330 if( CheckVersion( $DBversion ) ) {
16331     my $dbh = C4::Context->dbh;
16332     $dbh->do(q|
16333         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16334         ('HoldsAutoFill','0',NULL,'If on, librarian will not be asked if hold should be filled, it will be filled automatically','YesNo'),
16335         ('HoldsAutoFillPrintSlip','0',NULL,'If on, hold slip print dialog will be displayed automatically','YesNo')
16336     |);
16337     SetVersion( $DBversion );
16338     print "Upgrade to $DBversion done (Bug 19383 - Add ability to print hold receipts automatically)\n";
16339 }
16340
16341 $DBversion = '18.06.00.023';
16342 if( CheckVersion( $DBversion ) ) {
16343     if( !column_exists( 'aqorders', 'replacementprice' ) ){
16344         $dbh->do( "ALTER TABLE aqorders ADD COLUMN replacementprice DECIMAL(28,6)" );
16345         $dbh->do( "UPDATE aqorders set replacementprice = rrp WHERE replacementprice IS NULL" );
16346     }
16347     SetVersion( $DBversion );
16348     print "Upgrade to $DBversion done (Bug 18639 - Add replacementprice field to aqorders table)\n";
16349 }
16350
16351 $DBversion = '18.06.00.024';
16352 if( CheckVersion( $DBversion ) ) {
16353     if( !column_exists( 'branches', 'pickup_location' ) ){
16354         $dbh->do( "ALTER TABLE branches ADD COLUMN pickup_location TINYINT(1) not null default 1" );
16355     }
16356     SetVersion( $DBversion );
16357     print "Upgrade to $DBversion done (Bug 7534 - Let libraries have configuration for pickup locations)\n";
16358 }
16359
16360 $DBversion = '18.06.00.025';
16361 if( CheckVersion( $DBversion ) ) {
16362     $dbh->do(q{
16363         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16364         ('KohaManualBaseURL','https://koha-community.org/manual/','','Where is the Koha manual/documentation located?','Free'),
16365         ('KohaManualLanguage','en','en|ar|cs|es|de|fr|it|pt_BR|tr|zh_TW','What is the language of the online manual you want to use?','Choice')
16366     });
16367     SetVersion( $DBversion );
16368     print "Upgrade to $DBversion done (Bug 19817: Add pref KohaManualLanguage and KohaManualBaseURL)\n";
16369 }
16370
16371 $DBversion = '18.06.00.026';
16372 if( CheckVersion( $DBversion ) ) {
16373     $dbh->do(q|
16374 INSERT IGNORE INTO  systempreferences (variable, value, options, explanation, type) VALUES ('ArticleRequestsLinkControl', 'always', 'always\|calc', 'Control display of article request link on search results', 'Choice')
16375     |);
16376     SetVersion( $DBversion );
16377     print "Upgrade to $DBversion done (Bug 17530 - Add pref ArticleRequestsLinkControl)\n";
16378 }
16379
16380 $DBversion = '18.06.00.027';
16381 if( CheckVersion( $DBversion ) ) {
16382     $dbh->do( "DROP TABLE IF EXISTS services_throttle" );
16383     SetVersion( $DBversion );
16384     print "Upgrade to $DBversion done (Bug 21235: Remove table services_throttle)\n";
16385 }
16386
16387 $DBversion = '18.06.00.028';
16388 if( CheckVersion( $DBversion ) ) {
16389     $dbh->do(q{
16390 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
16391 ('HoldsSplitQueue','nothing','nothing|branch|itemtype|branch_itemtype','In the staff client, split the holds view by the given criteria','Choice'),
16392 ('HoldsSplitQueueNumbering', 'actual', 'actual|virtual', 'If the holds queue is split, decide if the acual priorities should be displayed', 'Choice');
16393 });
16394     SetVersion( $DBversion );
16395     print "Upgrade to $DBversion done (Bug 19469 - Add ability to split view of holds view on record by pickup library and/or itemtype)\n";
16396 }
16397
16398 $DBversion = '18.06.00.029';
16399 if( CheckVersion( $DBversion ) ) {
16400     unless ( index_exists( 'subscription', 'by_biblionumber' ) ) {
16401         $dbh->do(q{
16402             CREATE INDEX `by_biblionumber` ON `subscription` (`biblionumber`)
16403         });
16404     }
16405     SetVersion( $DBversion );
16406     print "Upgrade to $DBversion done (Bug 21288: Slowness in acquisition caused by GetInvoices\n";
16407 }
16408
16409 $DBversion = '18.06.00.030';
16410 if( CheckVersion( $DBversion ) ) {
16411     if ( column_exists( 'accountlines', 'dispute' ) ) {
16412         $dbh->do(q{
16413             ALTER TABLE `accountlines`
16414                 DROP COLUMN `dispute`
16415         });
16416     }
16417     SetVersion( $DBversion );
16418     print "Upgrade to $DBversion done (Bug 20777 - Remove unused field accountlines.dispute)\n";
16419 }
16420
16421 $DBversion = '18.06.00.031';
16422 if( CheckVersion( $DBversion ) ) {
16423     # Add table and add column
16424     unless (TableExists('patron_consent')) {
16425         $dbh->do(q|
16426     CREATE TABLE patron_consent (id int AUTO_INCREMENT, borrowernumber int NOT NULL, type enum('GDPR_PROCESSING' ), given_on datetime, refused_on datetime, PRIMARY KEY (id), FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE )
16427         |);
16428     }
16429     unless ( column_exists( 'borrower_modifications', 'gdpr_proc_consent' ) ) {
16430         $dbh->do(q|
16431     ALTER TABLE borrower_modifications ADD COLUMN gdpr_proc_consent datetime
16432         |);
16433     }
16434     # Add two sysprefs too
16435     $dbh->do(q|
16436 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('PrivacyPolicyURL','',NULL,'This URL is used in messages about GDPR consents.', 'Free')
16437     |);
16438     $dbh->do(q|
16439 INSERT IGNORE INTO systempreferences ( variable, value, options, explanation, type ) VALUES ('GDPR_Policy','','Enforced\|Permissive\|Disabled','General Data Protection Regulation - policy', 'Choice')
16440     |);
16441     SetVersion( $DBversion );
16442     print "Upgrade to $DBversion done (Bug 20819: Add patron_consent)\n";
16443 }
16444
16445 $DBversion = '18.06.00.032';
16446 if( CheckVersion( $DBversion ) ) {
16447     $dbh->do(q|ALTER TABLE items                   CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16448     $dbh->do(q|ALTER TABLE deleteditems            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16449     $dbh->do(q|ALTER TABLE branch_transfer_limits  CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16450     $dbh->do(q|ALTER TABLE course_items            CHANGE COLUMN ccode ccode varchar(80) default NULL|);
16451     SetVersion( $DBversion );
16452     print "Upgrade to $DBversion done (Bug 5458: length of items.ccode disagrees with authorised_values.authorised_value)\n";
16453 }
16454
16455 $DBversion = '18.06.00.033';
16456 if( CheckVersion( $DBversion ) ) {
16457     $dbh->do(q|
16458         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('AdditionalFieldsInZ3950ResultSearch', '', 'NULL', 'Determines which MARC field/subfields are displayed in -Additional field- column in the result of a search Z3950', 'Free')
16459     |);
16460     SetVersion( $DBversion );
16461     print "Upgrade to $DBversion done (Bug 12747 - Add AdditionalFieldsInZ3950ResultSearch system preference)\n";
16462 }
16463
16464 $DBversion = '18.06.00.034';
16465 if( CheckVersion( $DBversion ) ) {
16466     $dbh->do(q|
16467         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
16468         VALUES ('RecordedBooksClientSecret','','30','Client key for RecordedBooks integration','YesNo'),
16469                ('RecordedBooksLibraryID','','','Library ID for RecordedBooks integration','Integer'),
16470                ('RecordedBooksDomain','','','RecordedBooks domain','Free');
16471     |);
16472     SetVersion( $DBversion );
16473     print "Upgrade to $DBversion done (Bug 17602 - Integrate support for OneClickdigital/Recorded Books API)\n";
16474 }
16475
16476 $DBversion = '18.06.00.035';
16477 if( CheckVersion( $DBversion ) ) {
16478     $dbh->do(q{
16479         UPDATE `systempreferences` SET options = 'US|CA|DE|FR|IN|JP|UK' WHERE variable = 'AmazonLocale' AND options='US|CA|DE|FR|JP|UK';
16480     });
16481     SetVersion( $DBversion );
16482     print "Upgrade to $DBversion done (Bug 21403 - Add Indian Amazon Affiliate option to AmazonLocale setting)\n";
16483 }
16484
16485
16486 $DBversion = '18.06.00.036';
16487 if( CheckVersion( $DBversion ) ) {
16488     unless (TableExists('circulation_rules')){
16489         $dbh->do(q{
16490             CREATE TABLE `circulation_rules` (
16491               `id` int(11) NOT NULL auto_increment,
16492               `branchcode` varchar(10) NULL default NULL,
16493               `categorycode` varchar(10) NULL default NULL,
16494               `itemtype` varchar(10) NULL default NULL,
16495               `rule_name` varchar(32) NOT NULL,
16496               `rule_value` varchar(32) NOT NULL,
16497               PRIMARY KEY (`id`),
16498               CONSTRAINT `circ_rules_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
16499               CONSTRAINT `circ_rules_ibfk_2` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`) ON DELETE CASCADE ON UPDATE CASCADE,
16500               CONSTRAINT `circ_rules_ibfk_3` FOREIGN KEY (`itemtype`) REFERENCES `itemtypes` (`itemtype`) ON DELETE CASCADE ON UPDATE CASCADE,
16501               KEY `rule_name` (`rule_name`),
16502               UNIQUE (`branchcode`,`categorycode`,`itemtype`,`rule_name`)
16503             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16504         });
16505     }
16506     if (column_exists('branch_borrower_circ_rules', 'max_holds') ){
16507         $dbh->do(q{
16508             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16509             SELECT branchcode, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM branch_borrower_circ_rules
16510         });
16511         $dbh->do(q{
16512             ALTER TABLE branch_borrower_circ_rules DROP COLUMN max_holds
16513         });
16514     }
16515     if (column_exists('default_borrower_circ_rules', 'max_holds') ){
16516         $dbh->do(q{
16517             INSERT IGNORE INTO circulation_rules ( branchcode, categorycode, itemtype, rule_name, rule_value )
16518             SELECT NULL, categorycode, NULL, 'max_holds', COALESCE( max_holds, '' ) FROM default_borrower_circ_rules
16519         });
16520         $dbh->do(q{
16521             ALTER TABLE default_borrower_circ_rules DROP COLUMN max_holds
16522         });
16523     }
16524     SetVersion( $DBversion );
16525     print "Upgrade to $DBversion done (Bug 18887 - Introduce new table 'circulation_rules', use for 'max_holds' rules)\n";
16526 }
16527
16528 $DBversion = '18.06.00.037';
16529 if( CheckVersion( $DBversion ) ) {
16530     unless (TableExists('branches_overdrive')){
16531         $dbh->do( q|
16532             CREATE TABLE branches_overdrive (
16533                 `branchcode` VARCHAR( 10 ) NOT NULL ,
16534                 `authname` VARCHAR( 255 ) NOT NULL ,
16535                 PRIMARY KEY (`branchcode`) ,
16536                 CONSTRAINT `branches_overdrive_ibfk_1` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
16537             ) ENGINE = INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
16538         );
16539     }
16540     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveAuthname', '', 'Authname for OverDrive Patron Authentication, will be used as fallback if individual branch authname not set', NULL, 'Free');");
16541     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDriveWebsiteID','', 'WebsiteID provided by OverDrive', NULL, 'Free');");
16542     $dbh->do("INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OverDrivePasswordRequired','', 'Does the library require passwords for OverDrive SIP authentication', NULL, 'YesNo');");
16543     SetVersion( $DBversion );
16544     print "Upgrade to $DBversion done (Bug 21082 - Add overdrive patron auth method)\n";
16545 }
16546
16547 $DBversion = '18.06.00.038';
16548 if( CheckVersion( $DBversion ) ) {
16549     $dbh->do( "ALTER TABLE edifact_ean MODIFY branchcode VARCHAR(10) NULL DEFAULT NULL" );
16550     SetVersion( $DBversion );
16551     print "Upgrade to $DBversion done (Bug 21417 - EDI ordering fails when basket and EAN libraries do not match)\n";
16552 }
16553
16554 $DBversion = '18.06.00.039';
16555 if( CheckVersion( $DBversion ) ) {
16556     $dbh->do(q{
16557         INSERT IGNORE INTO `permissions` (module_bit, code, description) VALUES(3, 'manage_circ_rules_from_any_libraries', 'Manage circ rules for any libraries');
16558     });
16559     SetVersion( $DBversion );
16560     print "Upgrade to $DBversion done (Bug 15520 - Add more granular permission for only editing own library's circ rules)\n";
16561 }
16562
16563 $DBversion = '18.06.00.040';
16564 if( CheckVersion( $DBversion ) ) {
16565     # Stock Rotation Rotas
16566     unless (TableExists('stockrotationrotas')){
16567         $dbh->do(q{
16568           CREATE TABLE `stockrotationrotas` (
16569             `rota_id` int(11) auto_increment,         -- Stockrotation rota ID
16570             `title` varchar(100) NOT NULL,            -- Title for this rota
16571             `description` text NOT NULL,              -- Description for this rota
16572             `cyclical` tinyint(1) NOT NULL default 0, -- Should items on this rota keep cycling?
16573             `active` tinyint(1) NOT NULL default 0,   -- Is this rota currently active?
16574             PRIMARY KEY (`rota_id`),
16575             CONSTRAINT `stockrotationrotas_title`
16576             UNIQUE (`title`)
16577           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16578         });
16579     }
16580     # Stock Rotation Stages
16581     unless (TableExists('stockrotationstages')){
16582         $dbh->do(q{
16583           CREATE TABLE `stockrotationstages` (
16584               `stage_id` int(11) auto_increment,     -- Unique stage ID
16585               `position` int(11) NOT NULL,           -- The position of this stage within its rota
16586               `rota_id` int(11) NOT NULL,            -- The rota this stage belongs to
16587               `branchcode_id` varchar(10) NOT NULL,  -- Branch this stage relates to
16588               `duration` int(11) NOT NULL default 4, -- The number of days items shoud occupy this stage
16589               PRIMARY KEY (`stage_id`),
16590               CONSTRAINT `stockrotationstages_rifk`
16591                 FOREIGN KEY (`rota_id`)
16592                 REFERENCES `stockrotationrotas` (`rota_id`)
16593                 ON UPDATE CASCADE ON DELETE CASCADE,
16594               CONSTRAINT `stockrotationstages_bifk`
16595                 FOREIGN KEY (`branchcode_id`)
16596                 REFERENCES `branches` (`branchcode`)
16597                 ON UPDATE CASCADE ON DELETE CASCADE
16598           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16599         });
16600     }
16601     # Stock Rotation Items
16602     unless (TableExists('stockrotationitems')){
16603         $dbh->do(q{
16604           CREATE TABLE `stockrotationitems` (
16605               `itemnumber_id` int(11) NOT NULL,         -- Itemnumber to link to a stage & rota
16606               `stage_id` int(11) NOT NULL,              -- stage ID to link the item to
16607               `indemand` tinyint(1) NOT NULL default 0, -- Should this item be skipped for rotation?
16608               `fresh` tinyint(1) NOT NULL default 0,    -- Flag showing item is only just added to rota
16609               PRIMARY KEY (itemnumber_id),
16610               CONSTRAINT `stockrotationitems_iifk`
16611                 FOREIGN KEY (`itemnumber_id`)
16612                 REFERENCES `items` (`itemnumber`)
16613                 ON UPDATE CASCADE ON DELETE CASCADE,
16614               CONSTRAINT `stockrotationitems_sifk`
16615                 FOREIGN KEY (`stage_id`)
16616                 REFERENCES `stockrotationstages` (`stage_id`)
16617                 ON UPDATE CASCADE ON DELETE CASCADE
16618           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16619         });
16620     }
16621     # System preferences
16622     $dbh->do(q{
16623         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
16624         VALUES ('StockRotation','0','If ON, enables the stock rotation module','','YesNo'),
16625                ('RotationPreventTransfers','0','If ON, prevent any transfers for items on stock rotation rotas, except for stock rotation transfers','','YesNo');
16626     });
16627     # Permissions
16628     $dbh->do(q{
16629         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
16630         VALUES (24, 'stockrotation', 'Manage stockrotation operations', 0);
16631     });
16632     $dbh->do(q{
16633         INSERT IGNORE INTO `permissions` (`module_bit`, `code`, `description`)
16634         VALUES (24, 'manage_rotas', 'Create, edit and delete rotas'),
16635                (24, 'manage_rota_items', 'Add and remove items from rotas');
16636     });
16637     # Notices
16638     $dbh->do(q{
16639         INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`)
16640         VALUES ('circulation', 'SR_SLIP', '', 'Stock Rotation Slip', 0, 'Stockrotation Report', 'Stockrotation report for [% branch.name %]:\r\n\r\n[% IF branch.items.size %][% branch.items.size %] items to be processed for this branch.\r\n[% ELSE %]No items to be processed for this branch\r\n[% END %][% FOREACH item IN branch.items %][% IF item.reason ne \'in-demand\' %]Title: [% item.title %]\r\nAuthor: [% item.author %]\r\nCallnumber: [% item.callnumber %]\r\nLocation: [% item.location %]\r\nBarcode: [% item.barcode %]\r\nOn loan?: [% item.onloan %]\r\nStatus: [% item.reason %]\r\nCurrent Library: [% item.branch.branchname %] [% item.branch.branchcode %]\r\n\r\n[% END %][% END %]', 'email');
16641     });
16642     print "Upgrade to $DBversion done (Bug 11897 - Add Stock Rotation Feature)\n";
16643     SetVersion( $DBversion );
16644 }
16645
16646 $DBversion = '18.06.00.041';
16647 if( CheckVersion( $DBversion ) ) {
16648
16649      if( !column_exists( 'illrequests', 'price_paid' ) ) {
16650         $dbh->do(q{
16651             ALTER TABLE illrequests
16652                 ADD COLUMN price_paid varchar(20) DEFAULT NULL
16653                 AFTER cost
16654         });
16655      }
16656
16657      if( !column_exists( 'illrequestattributes', 'readonly' ) ) {
16658         $dbh->do(q{
16659             ALTER TABLE illrequestattributes
16660                 ADD COLUMN readonly tinyint(1) NOT NULL DEFAULT 1
16661                 AFTER value
16662         });
16663         $dbh->do(q{
16664             UPDATE illrequestattributes SET readonly = 1
16665         });
16666      }
16667
16668     SetVersion( $DBversion );
16669     print "Upgrade to $DBversion done (Bug 20772 - Add illrequestattributes.readonly and illrequest.price_paid columns)\n";
16670 }
16671
16672 $DBversion = '18.06.00.042';
16673 if( CheckVersion( $DBversion ) ) {
16674     $dbh->do( "alter table statistics change column ccode ccode varchar(80) default NULL" );
16675
16676     SetVersion( $DBversion );
16677     print "Upgrade to $DBversion done (Bug 21617: Make statistics.ccode longer)\n";
16678 }
16679
16680 $DBversion = "18.06.00.043";
16681 if ( CheckVersion($DBversion) ) {
16682     if ( !column_exists( 'issuingrules', 'holds_per_day' ) ) {
16683         $dbh->do(q{
16684             ALTER TABLE `issuingrules`
16685                 ADD COLUMN `holds_per_day` SMALLINT(6) DEFAULT NULL
16686                 AFTER `holds_per_record`
16687         });
16688     }
16689     print "Upgrade to $DBversion done (Bug 15486: Restrict number of holds placed by day)\n";
16690     SetVersion($DBversion);
16691 }
16692
16693 $DBversion = '18.06.00.044';
16694 if( CheckVersion( $DBversion ) ) {
16695     unless( column_exists( 'creator_batches', 'description' ) ) {
16696         $dbh->do(q|ALTER TABLE creator_batches ADD description mediumtext default NULL AFTER batch_id|);
16697     }
16698     SetVersion( $DBversion );
16699     print "Upgrade to $DBversion done (Bug 15766: Add column creator_batches.description)\n";
16700 }
16701
16702 $DBversion = '18.06.00.045';
16703 if( CheckVersion( $DBversion ) ) {
16704     $dbh->do(q(
16705         INSERT IGNORE INTO message_transports
16706         (message_attribute_id,message_transport_type,is_digest,letter_module,letter_code)
16707         VALUES
16708         (2, 'phone', 0, 'circulation', 'PREDUE'),
16709         (2, 'phone', 1, 'circulation', 'PREDUEDGST'),
16710         (4, 'phone', 0, 'reserves',    'HOLD')
16711         ));
16712     SetVersion( $DBversion );
16713     print "Upgrade to $DBversion done (Bug 21639 - Add phone transports by default)\n";
16714 }
16715
16716 $DBversion = '18.06.00.046';
16717 if( CheckVersion( $DBversion ) ) {
16718     unless (TableExists('illcomments')) {
16719         $dbh->do(q{
16720             CREATE TABLE illcomments (
16721                 illcomment_id int(11) NOT NULL AUTO_INCREMENT, -- Unique ID of the comment
16722                 illrequest_id bigint(20) unsigned NOT NULL,    -- ILL request number
16723                 borrowernumber integer DEFAULT NULL,           -- Link to the user who made the comment (could be librarian, patron or ILL partner library)
16724                 comment text DEFAULT NULL,                     -- The text of the comment
16725                 timestamp timestamp DEFAULT CURRENT_TIMESTAMP, -- Date and time when the comment was made
16726                 PRIMARY KEY  ( illcomment_id ),
16727                 CONSTRAINT illcomments_bnfk
16728                   FOREIGN KEY ( borrowernumber )
16729                   REFERENCES  borrowers  ( borrowernumber )
16730                   ON UPDATE CASCADE ON DELETE CASCADE,
16731                 CONSTRAINT illcomments_ifk
16732                   FOREIGN KEY (illrequest_id)
16733                   REFERENCES illrequests ( illrequest_id )
16734                   ON UPDATE CASCADE ON DELETE CASCADE
16735             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16736         });
16737     }
16738
16739     SetVersion( $DBversion );
16740     print "Upgrade to $DBversion done (Bug 18591 - Add comments to ILL requests)\n";
16741 }
16742
16743 $DBversion = '18.06.00.047';
16744 if( CheckVersion( $DBversion ) ) {
16745     # insert the authorized_value_category for CONTROL_NUM_SEQUENCE
16746     $dbh->do( "INSERT IGNORE INTO authorised_value_categories values ('CONTROL_NUM_SEQUENCE');" );
16747     SetVersion( $DBversion );
16748     print "Upgrade to $DBversion done (Bug 19263 - Advanced Editor - Rancor - Add auto control number (001) widget)\n";
16749 }
16750
16751 $DBversion = '18.06.00.048';
16752 if( CheckVersion( $DBversion ) ) {
16753     $dbh->do( "ALTER TABLE stockrotationrotas CHANGE COLUMN description description text" );
16754     SetVersion( $DBversion );
16755     print "Upgrade to $DBversion done (Bug 21682 - Remove default on stockrotationrotas.description)\n";
16756 }
16757
16758 $DBversion = '18.06.00.049';
16759 if( CheckVersion( $DBversion ) ) {
16760     $dbh->do(q{
16761         UPDATE letter SET content = REPLACE(content,"item.reason ne \'in-demand\'","item.reason != \'in-demand\'")
16762         WHERE code="SR_SLIP";
16763     });
16764     print "Upgrade to $DBversion done (Bug 21656 - Stock Rotation Notice, Template Toolkit Syntax Correction)\n";
16765     SetVersion( $DBversion );
16766 }
16767
16768 $DBversion = '18.06.00.050';
16769 if( CheckVersion( $DBversion ) ) {
16770     $dbh->do(q{
16771         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES ('OpacHiddenItemsExceptions','',NULL,'List of borrower categories, separated by |, that can see items otherwise hidden by OpacHiddenItems','Textarea');
16772     });
16773     print "Upgrade to $DBversion done (Bug 14385 - Add OpacHiddenItemExceptions)\n";
16774     SetVersion( $DBversion );
16775 }
16776
16777 $DBversion = '18.06.00.051';
16778 if( CheckVersion( $DBversion ) ) {
16779     $dbh->do(q{
16780         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
16781         ('AdlibrisCoversEnabled', '0', NULL, 'Display cover images in OPAC results and detail listing from Swedish retailer Adlibris.','YesNo'),
16782         ('AdlibrisCoversURL', 'http://www.adlibris.com/se/organisationer/showimagesafe.aspx', NULL, 'Base URL for Adlibris cover image web service.', 'Free');
16783     });
16784     print "Upgrade to $DBversion done (Bug 8630 - Add covers from AdLibris to the OPAC and Intranet)\n";
16785     SetVersion( $DBversion );
16786 }
16787
16788 $DBversion = '18.06.00.052';
16789 if( CheckVersion( $DBversion ) ) {
16790     $dbh->do(q{
16791         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
16792            ( 3, 'manage_sysprefs', 'Manage global system preferences'),
16793            ( 3, 'manage_libraries', 'Manage libraries and library groups'),
16794            ( 3, 'manage_itemtypes', 'Manage item types'),
16795            ( 3, 'manage_auth_values', 'Manage authorized values'),
16796            ( 3, 'manage_patron_categories', 'Manage patron categories'),
16797            ( 3, 'manage_patron_attributes', 'Manage extended patron attributes'),
16798            ( 3, 'manage_transfers', 'Manage library transfer limits and transport cost matrix'),
16799            ( 3, 'manage_item_circ_alerts', 'Manage item circulation alerts'),
16800            ( 3, 'manage_cities', 'Manage cities and towns'),
16801            ( 3, 'manage_marc_frameworks', 'Manage MARC bibliographic and authority frameworks'),
16802            ( 3, 'manage_keywords2koha_mappings', 'Manage keywords to Koha mappings'),
16803            ( 3, 'manage_classifications', 'Manage classification sources'),
16804            ( 3, 'manage_matching_rules', 'Manage record matching rules'),
16805            ( 3, 'manage_oai_sets', 'Manage OAI sets'),
16806            ( 3, 'manage_item_search_fields', 'Manage item search fields'),
16807            ( 3, 'manage_search_engine_config', 'Manage search engine configuration'),
16808            ( 3, 'manage_search_targets', 'Manage Z39.50 and SRU server configuration'),
16809            ( 3, 'manage_didyoumean', 'Manage Did you mean? configuration'),
16810            ( 3, 'manage_column_config', 'Manage column configuration'),
16811            ( 3, 'manage_sms_providers', 'Manage SMS cellular providers'),
16812            ( 3, 'manage_audio_alerts', 'Manage audio alerts'),
16813            ( 3, 'manage_usage_stats', 'Manage usage statistics settings');
16814     });
16815     $dbh->do(q{
16816         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16817             SELECT borrowernumber, 3, 'manage_sysprefs' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16818     });
16819     $dbh->do(q{
16820         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16821             SELECT borrowernumber, 3, 'manage_libraries' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16822     });
16823     $dbh->do(q{
16824         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16825             SELECT borrowernumber, 3, 'manage_itemtypes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16826     });
16827     $dbh->do(q{
16828         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16829             SELECT borrowernumber, 3, 'manage_auth_values' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16830     });
16831     $dbh->do(q{
16832         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16833             SELECT borrowernumber, 3, 'manage_patron_categories' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16834     });
16835     $dbh->do(q{
16836         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16837             SELECT borrowernumber, 3, 'manage_patron_attributes' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16838     });
16839     $dbh->do(q{
16840         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16841             SELECT borrowernumber, 3, 'manage_transfers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16842     });
16843     $dbh->do(q{
16844         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16845             SELECT borrowernumber, 3, 'manage_item_circ_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16846     });
16847     $dbh->do(q{
16848         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16849             SELECT borrowernumber, 3, 'manage_cities' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16850     });
16851     $dbh->do(q{
16852         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16853             SELECT borrowernumber, 3, 'manage_marc_frameworks' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16854     });
16855     $dbh->do(q{
16856         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16857             SELECT borrowernumber, 3, 'manage_keywords2koha_mappings' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16858     });
16859     $dbh->do(q{
16860         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16861             SELECT borrowernumber, 3, 'manage_classifications' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16862     });
16863     $dbh->do(q{
16864         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16865             SELECT borrowernumber, 3, 'manage_matching_rules' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16866     });
16867     $dbh->do(q{
16868         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16869             SELECT borrowernumber, 3, 'manage_oai_sets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16870     });
16871     $dbh->do(q{
16872         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16873             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16874     });
16875     $dbh->do(q{
16876         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16877             SELECT borrowernumber, 3, 'manage_search_engine_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16878     });
16879     $dbh->do(q{
16880         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16881             SELECT borrowernumber, 3, 'manage_search_targets' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16882     });
16883     $dbh->do(q{
16884         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16885             SELECT borrowernumber, 3, 'manage_didyoumean' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16886     });
16887     $dbh->do(q{
16888         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16889             SELECT borrowernumber, 3, 'manage_column_config' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16890     });
16891     $dbh->do(q{
16892         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16893             SELECT borrowernumber, 3, 'manage_sms_providers' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16894     });
16895     $dbh->do(q{
16896         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16897             SELECT borrowernumber, 3, 'manage_audio_alerts' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16898     });
16899     $dbh->do(q{
16900         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16901             SELECT borrowernumber, 3, 'manage_usage_stats' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM user_permissions WHERE code = 'parameters_remaining_permissions');
16902     });
16903     $dbh->do(q{
16904         INSERT INTO user_permissions (borrowernumber, module_bit, code)
16905             SELECT borrowernumber, 3, 'manage_item_search_fields' FROM borrowers WHERE flags & (1 << 2);
16906     });
16907     SetVersion( $DBversion );
16908     print "Upgrade to $DBversion done (Bug 14391: Add granular permissions to the administration module)\n";
16909 }
16910
16911 $DBversion = '18.06.00.053';
16912 if( CheckVersion( $DBversion ) ) {
16913     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('ItemsDeniedRenewal','','','This syspref allows to define custom rules for denying renewal of specific items.','Textarea')" );
16914     SetVersion( $DBversion );
16915     print "Upgrade to $DBversion done (Bug 15494 - Block renewals by arbitrary item values)\n";
16916 }
16917
16918 $DBversion = '18.06.00.054';
16919 if( CheckVersion( $DBversion ) ) {
16920     if( !column_exists( 'search_field', 'weight' ) ) {
16921         $dbh->do( "ALTER TABLE `search_field` ADD COLUMN `weight` decimal(5,2) DEFAULT NULL AFTER `type`" );
16922     }
16923     SetVersion( $DBversion );
16924     print "Upgrade to $DBversion done (Bug 18316 - Add column search_field.weight)\n";
16925 }
16926
16927 $DBversion = '18.06.00.055';
16928 if( CheckVersion( $DBversion ) ) {
16929     unless( column_exists( 'issuingrules', 'note' ) ) {
16930         $dbh->do(q|ALTER TABLE `issuingrules` ADD `note` varchar(100) default NULL AFTER `article_requests`|);
16931     }
16932     SetVersion( $DBversion );
16933     print "Upgrade to $DBversion done (Bug 12365: Add column issuingrules.note)\n";
16934 }
16935
16936 $DBversion = '18.06.00.056';
16937 if( CheckVersion( $DBversion ) ) {
16938
16939     # All attributes we're potentially interested in
16940     my $ff_req = $dbh->selectall_arrayref(
16941         'SELECT a.illrequest_id, a.type, a.value '.
16942         'FROM illrequests r, illrequestattributes a '.
16943         'WHERE r.illrequest_id = a.illrequest_id '.
16944         'AND r.backend = "FreeForm"',
16945         { Slice => {} }
16946     );
16947
16948     # Before we go any further, identify whether we've done
16949     # this before, we test for the presence of "container_title"
16950     # We stop as soon as we find one
16951     foreach my $req(@{$ff_req}) {
16952         if ($req->{type} eq 'container_title') {
16953             warn "Upgrade already carried out";
16954         }
16955     }
16956
16957     # Transform into a hashref with the key of the request ID
16958     my $requests = {};
16959     foreach my $request(@{$ff_req}) {
16960         my $id = $request->{illrequest_id};
16961         if (!exists $requests->{$id}) {
16962             $requests->{$id} = {};
16963         }
16964         $requests->{$id}->{$request->{type}} = $request->{value};
16965     }
16966
16967     # Transform any article requests
16968     my $transformed = {};
16969     foreach my $id(keys %{$requests}) {
16970         if (lc($requests->{$id}->{type}) eq 'article') {
16971             $transformed->{$id} = $requests->{$id};
16972             $transformed->{$id}->{type} = 'article';
16973             $transformed->{$id}->{container_title} = $transformed->{$id}->{title}
16974                 if defined $transformed->{$id}->{title} &&
16975                     length $transformed->{$id}->{title} > 0;
16976             $transformed->{$id}->{title} = $transformed->{$id}->{article_title}
16977                 if defined $transformed->{$id}->{article_title} &&
16978                     length $transformed->{$id}->{article_title} > 0;
16979             $transformed->{$id}->{author} = $transformed->{$id}->{article_author}
16980                 if defined $transformed->{$id}->{article_author} &&
16981                     length $transformed->{$id}->{article_author} > 0;
16982             $transformed->{$id}->{pages} = $transformed->{$id}->{article_pages}
16983                 if defined $transformed->{$id}->{article_pages} &&
16984                     length $transformed->{$id}->{article_pages} > 0;
16985         }
16986     }
16987
16988     # Now write back the transformed data
16989     # Rather than selectively replace, we just remove all attributes we've
16990     # transformed and re-write them
16991     my @changed = keys %{$transformed};
16992     my $changed_str = join(',', @changed);
16993
16994     if (scalar @changed > 0) {
16995         my ($raise_error) = $dbh->{RaiseError};
16996         $dbh->{AutoCommit} = 0;
16997         $dbh->{RaiseError} = 1;
16998         eval {
16999             my $del = $dbh->do(
17000                 "DELETE FROM illrequestattributes ".
17001                 "WHERE illrequest_id IN ($changed_str)"
17002             );
17003             foreach my $reqid(keys %{$transformed}) {
17004                 my $attr = $transformed->{$reqid};
17005                 foreach my $key(keys %{$attr}) {
17006                     my $sth = $dbh->prepare(
17007                         'INSERT INTO illrequestattributes '.
17008                         '(illrequest_id, type, value) '.
17009                         'VALUES '.
17010                         '(?, ?, ?)'
17011                     );
17012                     $sth->execute(
17013                         $reqid,
17014                         $key,
17015                         $attr->{$key}
17016                     );
17017                 }
17018             }
17019             $dbh->commit;
17020         };
17021
17022         if ($@) {
17023             warn "Upgrade to $DBversion failed: $@\n";
17024             eval { $dbh->rollback };
17025         } else {
17026             SetVersion( $DBversion );
17027             print "Upgrade to $DBversion done (Bug 21079 - Unify metadata schema across backends)\n";
17028         }
17029
17030         $dbh->{AutoCommit} = 1;
17031         $dbh->{RaiseError} = $raise_error;
17032     }
17033
17034 }
17035
17036 $DBversion = '18.06.00.057';
17037 if( CheckVersion( $DBversion ) ) {
17038     # System preferences
17039     $dbh->do(q{
17040         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`)
17041         VALUES ('showLastPatron','0','','If ON, enables the last patron feature in the intranet','YesNo');
17042     });
17043     SetVersion( $DBversion );
17044     print "Upgrade to $DBversion done (Bug 20312 - Add showLastPatron systempreference)\n";
17045 }
17046
17047 $DBversion = '18.06.00.058';
17048 if( CheckVersion( $DBversion ) ) {
17049     $dbh->do(q{
17050         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`, `type`) VALUES
17051         ('MarcFieldForCreatorId','',NULL,'Where to store the borrowernumber of the record''s creator','Free'),
17052         ('MarcFieldForCreatorName','',NULL,'Where to store the name of the record''s creator','Free'),
17053         ('MarcFieldForModifierId','',NULL,'Where to store the borrowernumber of the record''s last modifier','Free'),
17054         ('MarcFieldForModifierName','',NULL,'Where to store the name of the record''s last modifier','Free')
17055     });
17056
17057     SetVersion( $DBversion );
17058     print "Upgrade to $DBversion done (Bug 19349 - Add system preferences MarcFieldForCreatorId, MarcFieldForCreatorName, MarcFieldForModifierId, MarcFieldForModifierName)\n";
17059 }
17060
17061 $DBversion = '18.06.00.059';
17062 if( CheckVersion( $DBversion ) ) {
17063     $dbh->do(q{
17064         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  ('EmailSMSSendDriverFromAddress', '', '', 'Email SMS send driver from address override', 'Free');
17065     });
17066     SetVersion( $DBversion );
17067     print "Upgrade to $DBversion done (Bug 20356 - Add EmailSMSSendDriverFromAddress system preference)\n";
17068 }
17069
17070 $DBversion = '18.06.00.060';
17071 if( CheckVersion( $DBversion ) ) {
17072     unless( TableExists( 'class_split_rules' ) ) {
17073         $dbh->do(q|
17074             CREATE TABLE class_split_rules (
17075               class_split_rule varchar(10) NOT NULL default '',
17076               description LONGTEXT,
17077               split_routine varchar(30) NOT NULL default '',
17078               split_regex varchar(255) NOT NULL default '',
17079               PRIMARY KEY (class_split_rule),
17080               UNIQUE KEY class_split_rule_idx (class_split_rule)
17081             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
17082         |);
17083
17084         $dbh->do(q|
17085             ALTER TABLE class_sources
17086             ADD COLUMN class_split_rule varchar(10) NOT NULL default ''
17087             AFTER class_sort_rule
17088         |);
17089
17090         $dbh->do(q|
17091             UPDATE class_sources
17092             SET class_split_rule = class_sort_rule
17093         |);
17094
17095         $dbh->do(q|
17096             UPDATE class_sources
17097             SET class_split_rule = 'generic'
17098             WHERE class_split_rule NOT IN('dewey', 'generic', 'lcc')
17099         |);
17100
17101         $dbh->do(q|
17102             INSERT INTO class_split_rules(class_split_rule, description, split_routine)
17103             VALUES
17104             ('dewey', 'Default sorting rules for DDC', 'Dewey'),
17105             ('lcc', 'Default sorting rules for LCC', 'LCC'),
17106             ('generic', 'Generic call number sorting rules', 'Generic')
17107         |);
17108
17109         $dbh->do(q|
17110             ALTER TABLE class_sources
17111             ADD CONSTRAINT class_source_ibfk_2 FOREIGN KEY (class_split_rule)
17112             REFERENCES class_split_rules (class_split_rule)
17113         |);
17114     }
17115
17116     SetVersion( $DBversion );
17117     print "Upgrade to $DBversion done (Bug 15836 - Add class_sort_rules.split_routine and split_regex)\n";
17118 }
17119
17120 $DBversion = '18.06.00.061';
17121 if ( CheckVersion($DBversion) ) {
17122     $dbh->do(q{
17123         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
17124         ('ElasticsearchIndexStatus_biblios', '0', 'Biblios index status', NULL, NULL),
17125         ('ElasticsearchIndexStatus_authorities', '0', 'Authorities index status', NULL, NULL)
17126     });
17127     SetVersion($DBversion);
17128     print "Upgrade to $DBversion done (Bug 19893 - Add elasticsearch index status preferences)\n";
17129 }
17130
17131 $DBversion = '18.06.00.062';
17132 if( CheckVersion( $DBversion ) ) {
17133     $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name) VALUES ('PA_CLASS');");
17134     SetVersion( $DBversion );
17135     print "Upgrade to $DBversion done (Bug 21730: Add new authorised value category PA_CLASS)\n";
17136 }
17137
17138 $DBversion = '18.11.00.000';
17139 if( CheckVersion( $DBversion ) ) {
17140     SetVersion( $DBversion );
17141     print "Upgrade to $DBversion done (18.11.00 release)\n";
17142 }
17143
17144 $DBversion = '18.12.00.000';
17145 if( CheckVersion( $DBversion ) ) {
17146     SetVersion( $DBversion );
17147     print "Upgrade to $DBversion done (...and Steven!)\n";
17148 }
17149
17150 $DBversion = '18.12.00.001';
17151 if( CheckVersion( $DBversion ) ) {
17152     $dbh->do(q{
17153         UPDATE permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17154     });
17155     $dbh->do(q{
17156         UPDATE user_permissions SET code = 'manage_didyoumean' WHERE code = 'manage_didyouean';
17157     });
17158     SetVersion( $DBversion );
17159     print "Upgrade to $DBversion (Bug 21961 - Fix typo in manage_didyoumean permission)\n";
17160 }
17161
17162 $DBversion = '18.12.00.002';
17163 if( CheckVersion( $DBversion ) ) {
17164     my $sth = $dbh->prepare(q|SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME='accountlines_ibfk_1'|);
17165     $sth->execute;
17166     if ($sth->fetchrow_hashref) {
17167         $dbh->do(q|
17168             ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_1;
17169         |);
17170         $dbh->do(q|
17171             ALTER TABLE accountlines CHANGE COLUMN borrowernumber borrowernumber INT(11) DEFAULT NULL;
17172         |);
17173         $dbh->do(q|
17174             ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_borrowers FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE SET NULL ON UPDATE CASCADE;
17175         |);
17176     }
17177     SetVersion( $DBversion );
17178     print "Upgrade to $DBversion done (Bug 21065 - Set ON DELETE SET NULL on accountlines.borrowernumber)\n";
17179 }
17180
17181 $DBversion = '18.12.00.003';
17182 if( CheckVersion( $DBversion ) ) {
17183     # On a new installation the class_sources.sql will have failed, so we need to add all missing data
17184     my( $sort_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sort_rules|);
17185     if( !$sort_cnt ) {
17186         $dbh->do(q|INSERT INTO `class_sort_rules` (`class_sort_rule`, `description`, `sort_routine`) VALUES
17187                                ('dewey', 'Default filing rules for DDC', 'Dewey'),
17188                                ('lcc', 'Default filing rules for LCC', 'LCC'),
17189                                ('generic', 'Generic call number filing rules', 'Generic')
17190             |);
17191     }
17192
17193     my ( $split_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_split_rules|);
17194     if( !$split_cnt ) {
17195         $dbh->do(q|INSERT INTO `class_split_rules` (`class_split_rule`, `description`, `split_routine`) VALUES
17196                                ('dewey', 'Default splitting rules for DDC', 'Dewey'),
17197                                ('lcc', 'Default splitting rules for LCC', 'LCC'),
17198                                ('generic', 'Generic call number splitting rules', 'Generic')
17199             |);
17200     }
17201
17202     my( $source_cnt ) = $dbh->selectrow_array( q|SELECT COUNT(*) FROM class_sources|);
17203     if( !$source_cnt ) {
17204         $dbh->do(q|INSERT INTO `class_sources` (`cn_source`, `description`, `used`, `class_sort_rule`, `class_split_rule`) VALUES
17205                             ('ddc', 'Dewey Decimal Classification', 1, 'dewey', 'dewey'),
17206                             ('lcc', 'Library of Congress Classification', 1, 'lcc', 'lcc'),
17207                             ('udc', 'Universal Decimal Classification', 0, 'generic', 'generic'),
17208                             ('sudocs', 'SuDoc Classification (U.S. GPO)', 0, 'generic', 'generic'),
17209                             ('anscr', 'ANSCR (Sound Recordings)', 0, 'generic', 'generic'),
17210                             ('z', 'Other/Generic Classification Scheme', 0, 'generic', 'generic')
17211             |);
17212
17213     }
17214
17215     SetVersion( $DBversion );
17216     print "Upgrade to $DBversion done (Bug 22024 - Add missing splitting rule definitions)\n";
17217 }
17218
17219 $DBversion = '18.12.00.004';
17220 if( CheckVersion( $DBversion ) ) {
17221     if( !column_exists( 'accountlines', 'branchcode' ) ) {
17222         $dbh->do("ALTER TABLE accountlines ADD branchcode VARCHAR( 10 ) NULL DEFAULT NULL AFTER manager_id");
17223         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT accountlines_ibfk_branches FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE SET NULL ON UPDATE CASCADE");
17224     }
17225     SetVersion( $DBversion );
17226     print "Upgrade to $DBversion done (Bug 19066 - Add branchcode to accountlines)\n";
17227 }
17228
17229 $DBversion = '18.12.00.005';
17230 if( CheckVersion( $DBversion ) ) {
17231     $dbh->do(q{
17232         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17233         ('OverDriveUsername','cardnumber','cardnumber|userid','Which patron information should be passed as OverDrive username','Choice')
17234     });
17235     SetVersion( $DBversion );
17236     print "Upgrade to $DBversion done (Bug 22030: Add OverDriveUsername syspref)\n";
17237 }
17238
17239 $DBversion = '18.12.00.006';
17240 if( CheckVersion( $DBversion ) ) {
17241     $dbh->do(q{
17242         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17243         ('AccountAutoReconcile','0','If enabled, patron balances will get reconciled automatically on each transaction.',NULL,'YesNo');
17244     });
17245     SetVersion($DBversion);
17246     print "Upgrade to $DBversion done (Bug 21915 - Add a way to automatically reconcile balance for patrons)\n";
17247 }
17248
17249 $DBversion = '18.12.00.007';
17250 if( CheckVersion( $DBversion ) ) {
17251     if( column_exists( 'issuingrules', 'chargename' ) ) {
17252         $dbh->do( "ALTER TABLE issuingrules DROP chargename" );
17253     }
17254     SetVersion( $DBversion );
17255     print "Upgrade to $DBversion done (Bug 21753: Drop chargename from issuingrules )\n";
17256 }
17257
17258 $DBversion = '18.12.00.008';
17259 if( CheckVersion( $DBversion ) ) {
17260     if( !column_exists( 'subscription', 'mana_id' ) ) {
17261         $dbh->do( "ALTER TABLE subscription ADD mana_id int(11) NULL DEFAULT NULL" );
17262     }
17263
17264     if( !column_exists( 'saved_sql', 'mana_id' ) ) {
17265         $dbh->do( "ALTER TABLE saved_sql ADD mana_id int(11) NULL DEFAULT NULL" );
17266     }
17267     $dbh->do(q{
17268         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17269         ('Mana','2',NULL,'request to Mana Webservice. Mana centralize common information between other Koha to facilitate the creation of new subscriptions, vendors, report queries etc... You can search, share, import and comment the content of Mana.','Choice');
17270     });
17271     $dbh->do(q{
17272         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17273         ('AutoShareWithMana','','','defines datas automatically shared with mana','multiple');
17274     });
17275     $dbh->do(q{
17276         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
17277         ('ManaToken','',NULL,'Security token used for authentication on Mana KB service (anti spam)','Textarea');
17278     });
17279     SetVersion( $DBversion );
17280     print "Upgrade to $DBversion done (Bug 17047 - Mana knowledge base)\n";
17281 }
17282
17283 $DBversion = '18.12.00.009';
17284 if( CheckVersion( $DBversion ) ) {
17285     $dbh->do(q{
17286         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('FallbackToSMSIfNoEmail', 0, 'Enable|Disable', 'Send messages by SMS if no patron email is defined', 'YesNo');
17287     });
17288     SetVersion( $DBversion );
17289     print "Upgrade to $DBversion done (Bug 21241 - Add FallbackToSMSIfNoEmail syspref )\n";
17290 }
17291
17292 $DBversion = '18.12.00.010';
17293 if( CheckVersion( $DBversion ) ) {
17294     $dbh->do(q{
17295         INSERT IGNORE INTO systempreferences
17296             ( variable, value, options, explanation, type )
17297         VALUES
17298             ('RESTPublicAPI','1',NULL,'If enabled, the REST API will expose the /public endpoints.','YesNo')
17299     });
17300
17301     # Always end with this (adjust the bug info)
17302     SetVersion( $DBversion );
17303     print "Upgrade to $DBversion done (Bug 22061 - Add a /public namespace that can be switched on/off)\n";
17304 }
17305
17306 $DBversion = '18.12.00.011';
17307 if( CheckVersion( $DBversion ) ) {
17308     if ( column_exists( 'biblio_metadata', 'marcflavour' ) ) {
17309         $dbh->do(q{
17310             ALTER TABLE biblio_metadata
17311                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17312         });
17313     }
17314     if ( column_exists( 'deletedbiblio_metadata', 'marcflavour' ) ) {
17315         $dbh->do(q{
17316             ALTER TABLE deletedbiblio_metadata
17317                 CHANGE COLUMN marcflavour `schema` VARCHAR(16)
17318         });
17319     }
17320     SetVersion( $DBversion );
17321     print "Upgrade to $DBversion done (Bug 22155 - biblio_metadata.marcflavour should be renamed 'schema')\n";
17322 }
17323
17324 $DBversion = '18.12.00.012';
17325 if( CheckVersion( $DBversion ) ) {
17326     $dbh->do(q{
17327         INSERT IGNORE INTO systempreferences
17328             (variable, value, options, explanation, type )
17329         VALUES
17330             ('RESTBasicAuth','0',NULL,'If enabled, Basic authentication is enabled for the REST API.','YesNo')
17331     });
17332     SetVersion( $DBversion );
17333     print "Upgrade to $DBversion done (Bug 22132 - Add Basic authentication)\n";
17334 }
17335
17336 $DBversion = '18.12.00.013';
17337 if( CheckVersion( $DBversion ) ) {
17338     $dbh->do(q{
17339         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES ( 3, 'manage_mana', 'Manage Mana KB content sharing');
17340     });
17341     SetVersion( $DBversion );
17342     print "Upgrade to $DBversion done (Bug 22198 - Add ghranular permission setting for Mana KB)\n";
17343 }
17344
17345 $DBversion = '18.12.00.014';
17346 if( CheckVersion( $DBversion ) ) {
17347     unless( foreign_key_exists( 'messages', 'messages_borrowernumber' ) ) {
17348         $dbh->do(q|
17349             DELETE m FROM messages m
17350             LEFT JOIN borrowers b ON m.borrowernumber=b.borrowernumber
17351             WHERE b.borrowernumber IS NULL
17352         |);
17353         $dbh->do(q|
17354             ALTER TABLE messages
17355             ADD CONSTRAINT messages_borrowernumber
17356             FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE
17357         |);
17358     }
17359     SetVersion( $DBversion );
17360     print "Upgrade to $DBversion done (Bug 13515 - Add a FOREIGN KEY constaint on messages.borrowernumber)\n";
17361 }
17362
17363 $DBversion = '18.12.00.015';
17364 if( CheckVersion( $DBversion ) ) {
17365     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'cardnumber_replaced','cardnumber'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17366     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'previous_cardnumber','before'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17367     $dbh->do( "UPDATE action_logs SET info = REPLACE(info,'new_cardnumber','after'), timestamp = timestamp WHERE module='MEMBERS' AND action='MODIFY'" );
17368
17369     SetVersion( $DBversion );
17370     print "Upgrade to $DBversion done (Bug 3820 - Update patron modification logs)\n";
17371 }
17372
17373 $DBversion = '18.12.00.016';
17374 if( CheckVersion( $DBversion ) ) {
17375
17376     if ( !column_exists( 'illrequests', 'status_alias' ) ) {
17377         # Fresh upgrade, just add the column and constraint
17378         $dbh->do( "ALTER TABLE illrequests ADD COLUMN status_alias varchar(80) DEFAULT NULL AFTER status" );
17379     } else {
17380         # Migrate all existing foreign keys from referencing authorised_values.id
17381         # to referencing authorised_values.authorised_value
17382         # First remove the foreign key constraint and index
17383         if ( foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17384             $dbh->do( "ALTER TABLE illrequests DROP FOREIGN KEY illrequests_safk");
17385         }
17386         if ( index_exists( 'illrequests', 'illrequests_safk' ) ) {
17387             $dbh->do( "DROP INDEX illrequests_safk ON illrequests" );
17388         }
17389         # Now change the illrequests.status_alias column definition from int to varchar
17390         $dbh->do( "ALTER TABLE illrequests MODIFY COLUMN status_alias varchar(80)" );
17391         # Now replace all references to authorised_values.id with their
17392         # corresponding authorised_values.authorised_value
17393         my $sth = $dbh->prepare( "SELECT illrequest_id, status_alias FROM illrequests WHERE status_alias IS NOT NULL" );
17394         $sth->execute();
17395         while (my @row = $sth->fetchrow_array()) {
17396             my $r_id = $row[0];
17397             my $av_id = $row[1];
17398             # Get the authorised value's authorised_value value
17399             my ($av_val) = $dbh->selectrow_array( "SELECT authorised_value FROM authorised_values WHERE id = ?", {}, $av_id );
17400             # Now update illrequests.status_alias
17401             if ($av_val) {
17402                 $dbh->do( "UPDATE illrequests SET status_alias = ? WHERE illrequest_id = ?", {}, ($av_val, $r_id) );
17403             }
17404         }
17405     }
17406     if ( !foreign_key_exists( 'illrequests', 'illrequests_safk' ) ) {
17407         $dbh->do( "ALTER TABLE illrequests ADD CONSTRAINT illrequests_safk FOREIGN KEY (status_alias) REFERENCES authorised_values(authorised_value) ON UPDATE CASCADE ON DELETE SET NULL" );
17408     }
17409     $dbh->do( "INSERT IGNORE INTO authorised_value_categories SET category_name = 'ILLSTATUS'");
17410
17411     SetVersion( $DBversion );
17412     print "Upgrade to $DBversion done (Bug 20581 - Allow manual selection of custom ILL request statuses)\n";
17413 }
17414
17415 $DBversion = '18.12.00.017';
17416 if( CheckVersion( $DBversion ) ) {
17417     $dbh->do(q{
17418         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'fine_increase' ), ( 'fine_decrease' );
17419     });
17420     $dbh->do(q{
17421         UPDATE account_offsets SET type = 'fine_increase' WHERE type = 'Fine Update' AND amount > 0;
17422     });
17423     $dbh->do(q{
17424         UPDATE account_offsets SET type = 'fine_decrease' WHERE type = 'Fine Update' AND amount < 0;
17425     });
17426
17427     $dbh->do(q{
17428         DELETE FROM account_offset_types WHERE type = 'Fine Update';
17429     });
17430     SetVersion( $DBversion );
17431     print "Upgrade to $DBversion done (Bug 21747 - Update account_offset_types to include 'fine_increase' and 'fine_decrease')\n";
17432 }
17433
17434 $DBversion = '18.12.00.018';
17435 if( CheckVersion( $DBversion ) ) {
17436   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-publication', `label` = 'date-of-publication' WHERE `name` = 'pubdate'" );
17437   $dbh->do( "UPDATE `search_field` SET `name` = 'title-series', `label` = 'title-series' WHERE `name` = 'se'" );
17438   $dbh->do( "UPDATE `search_field` SET `name` = 'identifier-standard', `label` = 'identifier-standard' WHERE `name` = 'identifier-standard'" );
17439   $dbh->do( "UPDATE `search_field` SET `name` = 'author', `label` = 'author' WHERE `name` = 'author'" );
17440   $dbh->do( "UPDATE `search_field` SET `name` = 'control-number', `label` = 'control-number' WHERE `name` = 'control-number'" );
17441   $dbh->do( "UPDATE `search_field` SET `name` = 'place-of-publication', `label` = 'place-of-publication' WHERE `name` = 'place'" );
17442   $dbh->do( "UPDATE `search_field` SET `name` = 'date-of-acquisition', `label` = 'date-of-acquisition' WHERE `name` = 'acqdate'" );
17443   $dbh->do( "UPDATE `search_field` SET `name` = 'isbn', `label` = 'isbn' WHERE `name` = 'isbn'" );
17444   $dbh->do( "UPDATE `search_field` SET `name` = 'koha-auth-number', `label` = 'koha-auth-number' WHERE `name` = 'an'" );
17445   $dbh->do( "UPDATE `search_field` SET `name` = 'subject', `label` = 'subject' WHERE `name` = 'subject'" );
17446   $dbh->do( "UPDATE `search_field` SET `name` = 'publisher', `label` = 'publisher' WHERE `name` = 'publisher'" );
17447   $dbh->do( "UPDATE `search_field` SET `name` = 'record-source', `label` = 'record-source' WHERE `name` = 'record-source'" );
17448   $dbh->do( "UPDATE `search_field` SET `name` = 'title', `label` = 'title' WHERE `name` = 'title'" );
17449   $dbh->do( "UPDATE `search_field` SET `name` = 'local-classification', `label` = 'local-classification' WHERE `name` = 'local-classification'" );
17450   $dbh->do( "UPDATE `search_field` SET `name` = 'bib-level', `label` = 'bib-level' WHERE `name` = 'bib-level'" );
17451   $dbh->do( "UPDATE `search_field` SET `name` = 'microform-generation', `label` = 'microform-generation' WHERE `name` = 'microform-generation'" );
17452   $dbh->do( "UPDATE `search_field` SET `name` = 'material-type', `label` = 'material-type' WHERE `name` = 'material-type'" );
17453   $dbh->do( "UPDATE `search_field` SET `name` = 'bgf-number', `label` = 'bgf-number' WHERE `name` = 'bgf-number'" );
17454   $dbh->do( "UPDATE `search_field` SET `name` = 'number-db', `label` = 'number-db' WHERE `name` = 'number-db'" );
17455   $dbh->do( "UPDATE `search_field` SET `name` = 'number-natl-biblio', `label` = 'number-natl-biblio' WHERE `name` = 'number-natl-biblio'" );
17456   $dbh->do( "UPDATE `search_field` SET `name` = 'number-legal-deposit', `label` = 'number-legal-deposit' WHERE `name` = 'number-legal-deposit'" );
17457   $dbh->do( "UPDATE `search_field` SET `name` = 'issn', `label` = 'issn' WHERE `name` = 'issn'" );
17458   $dbh->do( "UPDATE `search_field` SET `name` = 'local-number', `label` = 'local-number' WHERE `name` = 'local-number'" );
17459   $dbh->do( "UPDATE `search_field` SET `name` = 'suppress', `label` = 'supress' WHERE `name` = 'suppress'" );
17460   $dbh->do( "UPDATE `search_field` SET `name` = 'bnb-card-number', `label` = 'bnb-card-number' WHERE `name` = 'bnb-card-number'" );
17461   $dbh->do( "UPDATE `search_field` SET `name` = 'date/time-last-modified', `label` = 'date/time-last-modified' WHERE `name` = 'date-time-last-modified'" );
17462   $dbh->do( "DELETE FROM `search_field` WHERE `name` = 'lc-cardnumber'" );
17463   $dbh->do( "DELETE FROM `search_marc_map` WHERE `id` NOT IN(SELECT `search_marc_map_id` FROM `search_marc_to_field`)" );
17464   SetVersion( $DBversion );
17465   print "Upgrade to $DBversion done (Bug 19575 - Use canonical field names and resolve aliased fields)\n";
17466 }
17467
17468 $DBversion = '18.12.00.019';
17469 if( CheckVersion( $DBversion ) ) {
17470     $dbh->do(q{
17471         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Reserve Fee' );
17472     });
17473
17474     SetVersion( $DBversion );
17475     print "Upgrade to $DBversion done (Bug 21728 - Add 'Reserve Fee' to the account_offset_types table if missing)\n";
17476 }
17477
17478 $DBversion = '18.12.00.020';
17479 if( CheckVersion( $DBversion ) ) {
17480     if ( TableExists( 'branch_borrower_circ_rules' ) ) {
17481         if ( column_exists( 'branch_borrower_circ_rules', 'maxissueqty' ) ) {
17482             $dbh->do("
17483                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17484                 SELECT categorycode, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17485                 FROM branch_borrower_circ_rules
17486             ");
17487             $dbh->do("
17488                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17489                 SELECT categorycode, branchcode, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17490                 FROM branch_borrower_circ_rules
17491             ");
17492             $dbh->do("DROP TABLE branch_borrower_circ_rules");
17493         }
17494     }
17495
17496     if ( TableExists( 'default_borrower_circ_rules' ) ) {
17497         if ( column_exists( 'default_borrower_circ_rules', 'maxissueqty' ) ) {
17498             $dbh->do("
17499                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17500                 SELECT categorycode, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17501                 FROM default_borrower_circ_rules
17502             ");
17503             $dbh->do("
17504                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17505                 SELECT categorycode, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17506                 FROM default_borrower_circ_rules
17507             ");
17508             $dbh->do("DROP TABLE default_borrower_circ_rules");
17509         }
17510     }
17511
17512     if ( column_exists( 'default_circ_rules', 'maxissueqty' ) ) {
17513         $dbh->do("
17514             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17515             SELECT NULL, NULL, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17516             FROM default_circ_rules
17517         ");
17518         $dbh->do("
17519             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17520             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17521             FROM default_circ_rules
17522         ");
17523         $dbh->do("ALTER TABLE default_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17524     }
17525
17526     if ( column_exists( 'default_branch_circ_rules', 'maxissueqty' ) ) {
17527         $dbh->do("
17528             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17529             SELECT NULL, branchcode, NULL, 'patron_maxissueqty', COALESCE( maxissueqty, '' )
17530             FROM default_branch_circ_rules
17531         ");
17532         $dbh->do("
17533             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17534             SELECT NULL, NULL, NULL, 'patron_maxonsiteissueqty', COALESCE( maxonsiteissueqty, '' )
17535             FROM default_branch_circ_rules
17536         ");
17537         $dbh->do("ALTER TABLE default_branch_circ_rules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17538     }
17539
17540     if ( column_exists( 'issuingrules', 'maxissueqty' ) ) {
17541         # Cleaning invalid rules before, to avoid FK contraints to fail
17542         $dbh->do(q|
17543             DELETE FROM issuingrules WHERE categorycode != '*' AND categorycode NOT IN (SELECT categorycode FROM categories);
17544         |);
17545         $dbh->do(q|
17546             DELETE FROM issuingrules WHERE branchcode != '*' AND branchcode NOT IN (SELECT branchcode FROM branches);
17547         |);
17548         $dbh->do(q|
17549             DELETE FROM issuingrules WHERE itemtype != '*' AND itemtype NOT IN (SELECT itemtype FROM itemtypes);
17550         |);
17551
17552         $dbh->do("
17553             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17554             SELECT IF(categorycode='*', NULL, categorycode),
17555                    IF(branchcode='*', NULL, branchcode),
17556                    IF(itemtype='*', NULL, itemtype),
17557                    'maxissueqty',
17558                    COALESCE( maxissueqty, '' )
17559             FROM issuingrules
17560         ");
17561         $dbh->do("
17562             INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
17563             SELECT IF(categorycode='*', NULL, categorycode),
17564                    IF(branchcode='*', NULL, branchcode),
17565                    IF(itemtype='*', NULL, itemtype),
17566                    'maxonsiteissueqty',
17567                    COALESCE( maxonsiteissueqty, '' )
17568             FROM issuingrules
17569         ");
17570         $dbh->do("ALTER TABLE issuingrules DROP COLUMN maxissueqty, DROP COLUMN maxonsiteissueqty");
17571     }
17572
17573     SetVersion( $DBversion );
17574     print "Upgrade to $DBversion done (Bug 18925 - Move maxissueqty and maxonsiteissueqty to circulation_rules)\n";
17575 }
17576
17577 $DBversion = '18.12.00.021';
17578 if ( CheckVersion($DBversion) ) {
17579
17580     if ( !column_exists( 'itemtypes', 'rentalcharge_daily' ) ) {
17581         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_daily` decimal(28,6) default NULL AFTER `rentalcharge`");
17582     }
17583
17584     if ( !column_exists( 'itemtypes', 'rentalcharge_hourly' ) ) {
17585         $dbh->do("ALTER TABLE `itemtypes` ADD COLUMN `rentalcharge_hourly` decimal(28,6) default NULL AFTER `rentalcharge_daily`");
17586     }
17587
17588     if ( column_exists( 'itemtypes', 'rental_charge_daily' ) ) {
17589         $dbh->do("UPDATE `itemtypes` SET `rentalcharge_daily` = `rental_charge_daily`");
17590         $dbh->do("ALTER TABLE `itemtypes` DROP COLUMN `rental_charge_daily`");
17591     }
17592
17593     SetVersion($DBversion);
17594     print "Upgrade to $DBversion done (Bug 20912 - Support granular rental charges)\n";
17595 }
17596
17597 $DBversion = '18.12.00.022';
17598 if( CheckVersion( $DBversion ) ) {
17599     $dbh->do( q{
17600         INSERT IGNORE INTO permissions (module_bit,code,description)
17601         VALUES
17602         (3,'manage_additional_fields','Add, edit, or delete additional custom fields for baskets or subscriptions (also requires order_manage or edit_subscription permissions)')
17603     });
17604     $dbh->do( q{
17605         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17606         SELECT borrowernumber, 3, 'manage_additional_fields' FROM borrowers WHERE borrowernumber IN (SELECT DISTINCT borrowernumber FROM user_permissions WHERE code = 'order_manage' OR code = 'edit_subscription');
17607     });
17608     $dbh->do( q{
17609         INSERT INTO user_permissions (borrowernumber, module_bit, code)
17610         SELECT borrowernumber, 3, 'manage_additional_fields' FROM borrowers WHERE borrowernumber IN (SELECT borrowernumber FROM borrowers WHERE MOD(flags DIV POWER(2,11),2)=1 OR MOD(flags DIV POWER(2,15),2) =1);
17611     });
17612     SetVersion( $DBversion );
17613     print "Upgrade to $DBversion done (Bug 15774 - Add permission for managing additional fields)\n";
17614 }
17615
17616 $DBversion = '18.12.00.023';
17617 if( CheckVersion( $DBversion ) ) {
17618     $dbh->do(q|
17619       INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
17620       VALUES ('ILLOpacbackends',NULL,NULL,'ILL backends to enabled for OPAC initiated requests','multiple');
17621     |);
17622
17623     # Always end with this (adjust the bug info)
17624     SetVersion( $DBversion );
17625     print "Upgrade to $DBversion done (Bug 20639 - Add ILLOpacbackends syspref)\n";
17626 }
17627
17628 $DBversion = '18.12.00.024';
17629 if ( CheckVersion($DBversion) ) {
17630
17631     # Fixup any pre-existing bad suggestedby, manageddate, accepteddate dates
17632     eval {
17633         local $dbh->{PrintError} = 0;
17634         $dbh->do(
17635             "UPDATE suggestions SET suggesteddate = '1970-01-01' WHERE suggesteddate = '0000-00-00';"
17636         );
17637         $dbh->do(
17638             "UPDATE suggestions SET manageddate = '1970-01-01' WHERE manageddate = '0000-00-00';"
17639         );
17640         $dbh->do(
17641             "UPDATE suggestions SET accepteddate = '1970-01-01' WHERE accepteddate = '0000-00-00';"
17642         );
17643     };
17644
17645     # Add constraint for suggestedby
17646     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_suggestedby' ) )
17647     {
17648         $dbh->do(
17649 "ALTER TABLE suggestions CHANGE COLUMN suggestedby suggestedby INT(11) NULL DEFAULT NULL;"
17650         );
17651         $dbh->do(
17652 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.suggestedby = borrowers.borrowernumber) SET suggestedby = null WHERE borrowernumber IS null"
17653         );
17654         $dbh->do(
17655 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_suggestedby` FOREIGN KEY (`suggestedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17656         );
17657     }
17658
17659     # Add constraint for managedby
17660     unless ( foreign_key_exists( 'suggestions', 'suggestions_ibfk_managedby' ) )
17661     {
17662         $dbh->do(
17663 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.managedby = borrowers.borrowernumber) SET managedby = null WHERE borrowernumber IS NULL"
17664         );
17665         $dbh->do(
17666 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_managedby` FOREIGN KEY (`managedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17667         );
17668     }
17669
17670     # Add constraint for acceptedby
17671     unless (
17672         foreign_key_exists( 'suggestions', 'suggestions_ibfk_acceptedby' ) )
17673     {
17674         $dbh->do(
17675 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.acceptedby = borrowers.borrowernumber) SET acceptedby = null WHERE borrowernumber IS NULL"
17676         );
17677         $dbh->do(
17678 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_acceptedby` FOREIGN KEY (`acceptedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17679         );
17680     }
17681
17682     # Add constraint for rejectedby
17683     unless (
17684         foreign_key_exists( 'suggestions', 'suggestions_ibfk_rejectedby' ) )
17685     {
17686         $dbh->do(
17687 "UPDATE suggestions LEFT JOIN borrowers ON (suggestions.rejectedby = borrowers.borrowernumber) SET rejectedby = null WHERE borrowernumber IS null"
17688         );
17689         $dbh->do(
17690 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_rejectedby` FOREIGN KEY (`rejectedby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17691         );
17692     }
17693
17694     # Add constraint for biblionumber
17695     unless (
17696         foreign_key_exists( 'suggestions', 'suggestions_ibfk_biblionumber' ) )
17697     {
17698         $dbh->do(
17699 "UPDATE suggestions s LEFT JOIN biblio b ON (s.biblionumber = b.biblionumber) SET s.biblionumber = null WHERE b.biblionumber IS null"
17700         );
17701         $dbh->do(
17702 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_biblionumber` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE SET NULL ON UPDATE CASCADE"
17703         );
17704     }
17705
17706     # Add constraint for branchcode
17707     unless (
17708         foreign_key_exists( 'suggestions', 'suggestions_ibfk_branchcode' ) )
17709     {
17710         $dbh->do(
17711 "UPDATE suggestions s LEFT JOIN branches b ON (s.branchcode = b.branchcode) SET s.branchcode = null WHERE b.branchcode IS null"
17712         );
17713         $dbh->do(
17714 "ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE SET NULL ON UPDATE CASCADE"
17715         );
17716     }
17717
17718     SetVersion($DBversion);
17719     print
17720 "Upgrade to $DBversion done (Bug 22368 - Add missing constraints to suggestions)\n";
17721 }
17722
17723 $DBversion = '18.12.00.025';
17724 if( CheckVersion( $DBversion ) ) {
17725
17726     $dbh->do('SET FOREIGN_KEY_CHECKS=0');
17727
17728     # Change columns accordingly
17729     $dbh->do(q{
17730         ALTER TABLE tags_index
17731             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17732     });
17733
17734     $dbh->do(q{
17735         ALTER TABLE tags_approval
17736             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17737     });
17738
17739     $dbh->do(q{
17740         ALTER TABLE tags_all
17741             MODIFY COLUMN term VARCHAR(191) COLLATE utf8mb4_bin NOT NULL;
17742     });
17743
17744     $dbh->do('SET FOREIGN_KEY_CHECKS=1');
17745
17746     SetVersion( $DBversion );
17747     print "Upgrade to $DBversion done (Bug 21846 - Using emoji as tags has broken weights)\n";
17748     my $maintenance_script = C4::Context->config("intranetdir") . "/misc/maintenance/fix_tags_weight.pl";
17749     print "WARNING: (Bug 21846) You need to manually run $maintenance_script to fix possible issues with tags.\n";
17750 }
17751
17752 $DBversion = '18.12.00.026';
17753 if( CheckVersion( $DBversion ) ) {
17754     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, explanation, type) VALUES ('IllLog', 0, 'If ON, log information about ILL requests', 'YesNo')" );
17755
17756     SetVersion( $DBversion );
17757     print "Upgrade to $DBversion done (Bug 20750 - Allow timestamped auditing of ILL request events)\n";
17758 }
17759
17760 $DBversion = '18.12.00.027';
17761 if( CheckVersion( $DBversion ) ) {
17762     $dbh->do(q{
17763 INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
17764        ('ILLModuleUnmediated','0','','If enabled, try to immediately progress newly placed ILL requests.','YesNo');
17765     });
17766     SetVersion( $DBversion );
17767     print "Upgrade to $DBversion done (Bug 18837: Add ILLModuleUnmediated Syspref)\n";
17768 }
17769
17770 $DBversion = '18.12.00.028';
17771 if( CheckVersion( $DBversion ) ) {
17772     $dbh->do(q{
17773         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Account Fee' );
17774     });
17775
17776     $dbh->do(q{
17777         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Hold Expired' );
17778     });
17779
17780     SetVersion( $DBversion );
17781     print "Upgrade to $DBversion done (Bug 21756 - Add 'Account Fee' and 'Hold Expired' to the account_offset_types table if missing)\n";
17782 }
17783
17784 $DBversion = '18.12.00.029';
17785 if( CheckVersion( $DBversion ) ) {
17786     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('OrderPriceRounding',NULL,'Local preference for rounding orders before calculations to ensure correct calculations','|nearest_cent','Choice')" );
17787
17788     SetVersion( $DBversion );
17789     print "Upgrade to $DBversion done (Bug 18736 - Add syspref to control order rounding)\n";
17790 }
17791
17792 $DBversion = '18.12.00.030';
17793 if( CheckVersion( $DBversion ) ) {
17794     if( column_exists( 'accountlines', 'accountno' ) ) {
17795         $dbh->do( "ALTER TABLE accountlines DROP COLUMN accountno" );
17796     }
17797     if( column_exists( 'statistics', 'proccode' ) ) {
17798         $dbh->do( "ALTER TABLE statistics DROP COLUMN proccode" );
17799     }
17800     SetVersion( $DBversion );
17801     print "Upgrade to $DBversion done (Bug 21683 - Remove accountlines.accountno and statistics.proccode fields)\n";
17802 }
17803
17804 $DBversion = '18.12.00.031';
17805 if( CheckVersion( $DBversion ) ) {
17806
17807     # Add constraint for manager_id
17808     unless( foreign_key_exists( 'accountlines', 'accountlines_ibfk_borrowers_2' ) ) {
17809         $dbh->do("ALTER TABLE accountlines CHANGE COLUMN manager_id manager_id INT(11) NULL DEFAULT NULL");
17810         $dbh->do("UPDATE accountlines a LEFT JOIN borrowers b ON ( a.manager_id = b.borrowernumber) SET a.manager_id = NULL WHERE b.borrowernumber IS NULL");
17811         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT `accountlines_ibfk_borrowers_2` FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE");
17812     }
17813
17814     # Rename accountlines_ibfk_2 to accountlines_ibfk_items
17815     if ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_2' ) ) {
17816         $dbh->do("ALTER TABLE accountlines DROP FOREIGN KEY accountlines_ibfk_2");
17817     }
17818     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_items' ) ) {
17819         $dbh->do("ALTER TABLE accountlines ADD CONSTRAINT `accountlines_ibfk_items` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE SET NULL ON UPDATE CASCADE");
17820     }
17821
17822     SetVersion( $DBversion );
17823     print "Upgrade to $DBversion done (Bug 22008 - Add missing constraints for accountlines.manager_id)\n";
17824 }
17825
17826 $DBversion = '18.12.00.032';
17827 if( CheckVersion( $DBversion ) ) {
17828     if( !column_exists( 'search_field', 'facet_order' ) ) {
17829         $dbh->do("ALTER TABLE search_field ADD COLUMN facet_order TINYINT(4) DEFAULT NULL AFTER weight");
17830     }
17831     $dbh->do("UPDATE search_field SET facet_order=1 WHERE name='author'");
17832     $dbh->do("UPDATE search_field SET facet_order=2 WHERE name='itype'");
17833     $dbh->do("UPDATE search_field SET facet_order=3 WHERE name='location'");
17834     $dbh->do("UPDATE search_field SET facet_order=4 WHERE name='su-geo'");
17835     $dbh->do("UPDATE search_field SET facet_order=5 WHERE name='title-series'");
17836     $dbh->do("UPDATE search_field SET facet_order=6 WHERE name='subject'");
17837     $dbh->do("UPDATE search_field SET facet_order=7 WHERE name='ccode'");
17838     $dbh->do("UPDATE search_field SET facet_order=8 WHERE name='holdingbranch'");
17839     $dbh->do("UPDATE search_field SET facet_order=9 WHERE name='homebranch'");
17840     SetVersion( $DBversion );
17841     print "Upgrade to $DBversion done (Bug 18235 - Elastic search - make facets configurable)\n";
17842 }
17843
17844 $DBversion = '18.12.00.033';
17845 if( CheckVersion( $DBversion ) ) {
17846     $dbh->do( "UPDATE search_field SET facet_order=10 WHERE name='ln'" );
17847     SetVersion( $DBversion );
17848     print "Upgrade to $DBversion done (Bug 18213 - Add language facets to Elasticsearch)\n";
17849 }
17850
17851 $DBversion = '18.12.00.034';
17852 if( CheckVersion( $DBversion ) ) {
17853
17854     if ( column_exists( 'accountlines', 'lastincrement' ) ) {
17855         $dbh->do("ALTER TABLE `accountlines` DROP COLUMN `lastincrement`");
17856     }
17857
17858     SetVersion( $DBversion );
17859     print "Upgrade to $DBversion done (Bug 22516 - Drop deprecated accountlines.lastincrement field)\n";
17860 }
17861
17862 $DBversion = '18.12.00.035';
17863 if( CheckVersion( $DBversion ) ) {
17864     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
17865                VALUES ('MaxItemsToDisplayForBatchMod','1000',NULL,'Display up to a given number of items in a single item modification batch.','Integer')"
17866             );
17867     SetVersion( $DBversion );
17868     print "Upgrade to $DBversion done (Bug 19722 - Add a MaxItemsToDisplayForBatchMod preference)\n";
17869 }
17870
17871 $DBversion = '18.12.00.036';
17872 if ( CheckVersion($DBversion) ) {
17873
17874     my $rows = $dbh->do(
17875         qq{
17876         UPDATE `accountlines`
17877         SET
17878           `accounttype` = 'FU'
17879         WHERE
17880           `accounttype` = 'O'
17881       }
17882     );
17883
17884     SetVersion($DBversion);
17885     printf "Upgrade to $DBversion done (Bug 22518 - Fix accounttype 'O' to 'FU' - %d updated)\n", $rows;
17886 }
17887
17888 $DBversion = '18.12.00.037';
17889 if( CheckVersion( $DBversion ) ) {
17890
17891     $dbh->do( "UPDATE issues SET renewals = 0 WHERE renewals IS NULL" );
17892     $dbh->do( "UPDATE old_issues SET renewals = 0 WHERE renewals IS NULL" );
17893
17894     $dbh->do( "ALTER TABLE issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17895     $dbh->do( "ALTER TABLE old_issues MODIFY COLUMN renewals tinyint(4) NOT NULL default 0");
17896
17897     # Always end with this (adjust the bug info)
17898     SetVersion( $DBversion );
17899     print "Upgrade to $DBversion done (Bug 22607 - Set default value of issues.renewals to 0)\n";
17900 }
17901
17902 $DBversion = '18.12.00.038';
17903 if ( CheckVersion($DBversion) ) {
17904
17905     if ( !column_exists( 'accountlines', 'status' ) ) {
17906         $dbh->do(
17907             qq{
17908             ALTER TABLE `accountlines`
17909             ADD
17910               `status` varchar(16) DEFAULT NULL
17911             AFTER
17912               `accounttype`
17913           }
17914         );
17915     }
17916
17917     SetVersion($DBversion);
17918     print "Upgrade to $DBversion done (Bug 22512 - Add status to accountlines)\n";
17919 }
17920
17921 $DBversion = '18.12.00.039';
17922 if ( CheckVersion($DBversion) ) {
17923
17924     if ( !column_exists( 'accountlines', 'interface' ) ) {
17925         $dbh->do(
17926             qq{
17927             ALTER TABLE `accountlines`
17928             ADD
17929               `interface` varchar(16)
17930             AFTER
17931               `manager_id`;
17932           }
17933         );
17934     }
17935
17936     $dbh->do(qq{
17937         UPDATE
17938           `accountlines`
17939         SET
17940           interface = 'opac'
17941         WHERE
17942           borrowernumber = manager_id;
17943     });
17944
17945     $dbh->do(qq{
17946         UPDATE
17947           `accountlines`
17948         SET
17949           interface = 'cron'
17950         WHERE
17951           manager_id IS NULL
17952         AND
17953           branchcode IS NULL;
17954     });
17955
17956     $dbh->do(qq{
17957         UPDATE
17958           `accountlines`
17959         SET
17960           interface = 'intranet'
17961         WHERE
17962           interface IS NULL;
17963     });
17964
17965     $dbh->do(qq{
17966         ALTER TABLE `accountlines`
17967         MODIFY COLUMN `interface` varchar(16) NOT NULL;
17968     });
17969
17970     SetVersion($DBversion);
17971     print "Upgrade to $DBversion done (Bug 22600 - Add interface to accountlines)\n";
17972 }
17973
17974 $DBversion = '18.12.00.040';
17975 if( CheckVersion( $DBversion ) ) {
17976     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Reserve Charge - ', '') WHERE description LIKE 'Reserve Charge - %'");
17977     SetVersion( $DBversion );
17978     print "Upgrade to $DBversion done (Bug 12166 - Remove 'Reserve Charge' text from accountlines description)\n";
17979 }
17980
17981 $DBversion = '18.12.00.041';
17982 if( CheckVersion( $DBversion ) ) {
17983     my $table_sth = $dbh->prepare('SHOW CREATE TABLE `search_marc_map`');
17984     $table_sth->execute();
17985     my @table = $table_sth->fetchrow_array();
17986     unless ( $table[1] =~ /`marc_field`.*COLLATE utf8mb4_bin/ ) { #catches utf8mb4 collated tables
17987         $dbh->do("ALTER TABLE `search_marc_map` MODIFY `marc_field` VARCHAR(255) NOT NULL COLLATE utf8mb4_bin COMMENT 'the MARC specifier for this field'");
17988     }
17989
17990     # Always end with this (adjust the bug info)
17991     SetVersion( $DBversion );
17992         print "Upgrade to $DBversion done (Bug 19670 - Change collation of marc_field to allow mixed case search field mappings)\n";
17993 }
17994
17995 $DBversion = '18.12.00.042';
17996 if( CheckVersion( $DBversion ) ) {
17997     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTDetailsDisplay' AND value = ''" );
17998     SetVersion( $DBversion );
17999     print "Upgrade to $DBversion done (Bug 29891 - Remove non-XSLT detail view in the staff client)\n";
18000 }
18001
18002 $DBversion = '18.12.00.043';
18003 if ( CheckVersion($DBversion) ) {
18004     $dbh->do("UPDATE accountlines SET description = REPLACE(description, 'Lost Item ', '') WHERE description LIKE 'Lost Item %'");
18005     SetVersion($DBversion);
18006     print "Upgrade to $DBversion done (Bug 21953 - Remove 'Lost Item' text from accountlines description)\n";
18007 }
18008
18009 $DBversion = '18.12.00.044';
18010 if( CheckVersion( $DBversion ) ) {
18011
18012     if ( !column_exists( 'categories', 'reset_password' ) ) {
18013         $dbh->do(q{
18014             ALTER TABLE categories
18015                 ADD COLUMN reset_password TINYINT(1) NULL DEFAULT NULL
18016                 AFTER checkprevcheckout
18017         });
18018     }
18019
18020     SetVersion( $DBversion );
18021     print "Upgrade to $DBversion done (Bug 21890 - Patron password reset by category)\n";
18022 }
18023
18024 $DBversion = '18.12.00.045';
18025 if( CheckVersion( $DBversion ) ) {
18026
18027     if ( !column_exists( 'categories', 'change_password' ) ) {
18028         $dbh->do(q{
18029             ALTER TABLE categories
18030                 ADD COLUMN change_password TINYINT(1) NULL DEFAULT NULL
18031                 AFTER reset_password
18032         });
18033     }
18034
18035     SetVersion( $DBversion );
18036     print "Upgrade to $DBversion done (Bug 10796 - Patron password change by category)\n";
18037 }
18038
18039 $DBversion = '18.12.00.046';
18040 if( CheckVersion( $DBversion ) ) {
18041     $dbh->do( "UPDATE systempreferences SET value = 'default' WHERE variable = 'XSLTResultsDisplay' AND value = ''" );
18042     SetVersion( $DBversion );
18043     print "Upgrade to $DBversion done (Bug 22695 - Remove non-XSLT search results view from the staff client)\n";
18044 }
18045
18046 $DBversion = '18.12.00.047';
18047 if( CheckVersion( $DBversion ) ) {
18048     $dbh->do(q|
18049         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('LibrisKey', '', 'This key must be obtained at http://api.libris.kb.se/. It is unique for the IP of the server.', NULL, 'Free');
18050     |);
18051     $dbh->do(q|
18052         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES ('LibrisURL', 'http://api.libris.kb.se/bibspell/', 'This is the base URL for the Libris spellchecking API.',NULL,'Free');
18053     |);
18054     SetVersion( $DBversion );
18055     print "Upgrade to $DBversion done (Bug 14557: Add Libris spellchecking system preferences)\n";
18056 }
18057
18058 $DBversion = '18.12.00.048';
18059 if( CheckVersion( $DBversion ) ) {
18060     $dbh->do( q{
18061         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
18062         VALUES ('NoRenewalBeforePrecision', 'exact_time', 'Calculate "No renewal before" based on date or exact time. Only relevant for loans calculated in days, hourly loans are not affected.', 'date|exact_time', 'Choice');
18063     });
18064     $dbh->do("UPDATE systempreferences SET value='exact_time' WHERE variable='NoRenewalBeforePrecision' AND value IS NULL;" );
18065     SetVersion( $DBversion );
18066     print "Upgrade to $DBversion done (Bug 22044 - Set a default value for NoRenewalBeforePrecision)\n";
18067 }
18068
18069 $DBversion = '18.12.00.049';
18070 if( CheckVersion( $DBversion ) ) {
18071
18072     $dbh->do(q{
18073         ALTER TABLE borrowers
18074             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18075             AFTER overdrive_auth_token
18076     }) if !column_exists('borrowers', 'flgAnonymized');
18077
18078     $dbh->do(q{
18079         ALTER TABLE deletedborrowers
18080             ADD COLUMN flgAnonymized tinyint DEFAULT 0
18081             AFTER overdrive_auth_token
18082     }) if !column_exists('deletedborrowers', 'flgAnonymized');
18083
18084     SetVersion( $DBversion );
18085     print "Upgrade to $DBversion done (Bug 21336 - Add field flgAnonymized)\n";
18086 }
18087
18088 $DBversion = '18.12.00.050';
18089 if( CheckVersion( $DBversion ) ) {
18090     $dbh->do( q|
18091 INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18092 VALUES
18093 ('UnsubscribeReflectionDelay','',NULL,'Delay for locking unsubscribers', 'Integer'),
18094 ('PatronAnonymizeDelay','',NULL,'Delay for anonymizing patrons', 'Integer'),
18095 ('PatronRemovalDelay','',NULL,'Delay for removing anonymized patrons', 'Integer')
18096     |);
18097     SetVersion( $DBversion );
18098     print "Upgrade to $DBversion done (Bug 21336 - Add preferences)\n";
18099 }
18100
18101 $DBversion = '18.12.00.051';
18102 if( CheckVersion( $DBversion ) ) {
18103     my $failed_attempts = C4::Context->preference('FailedLoginAttempts');
18104     $dbh->do( "UPDATE borrowers SET login_attempts = ? WHERE login_attempts > ?", undef, $failed_attempts, $failed_attempts ) if $failed_attempts && $failed_attempts > 0;
18105     SetVersion( $DBversion );
18106     print "Upgrade to $DBversion done (Bug 21336 - Reset login_attempts)\n";
18107 }
18108
18109 $DBversion = '18.12.00.052';
18110 if( CheckVersion( $DBversion ) ) {
18111     $dbh->do(q{
18112         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
18113         ('OpacMoreSearches', '', NULL, 'Add additional elements to the OPAC more searches bar', 'Textarea')
18114     } );
18115
18116     SetVersion( $DBversion );
18117     print "Upgrade to $DBversion done (Bug 22311 - Add a SysPref to allow adding content to the #moresearches div in the opac)\n";
18118 }
18119
18120 $DBversion = '18.12.00.053';
18121 if( CheckVersion( $DBversion ) ) {
18122     $dbh->do(q{
18123         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
18124         ('AutoReturnCheckedOutItems', '0', '', 'If disabled, librarian must confirm return of checked out item when checking out to another.', 'YesNo');
18125     });
18126
18127     SetVersion( $DBversion );
18128     print "Upgrade to $DBversion done (Bug 17171 - Add a syspref to allow currently issued items to be issued to a new patron without staff confirmation)\n";
18129 }
18130
18131 $DBversion = '18.12.00.054';
18132 if( CheckVersion( $DBversion ) ) {
18133     $dbh->do(q{
18134         INSERT IGNORE permissions (module_bit, code, description)
18135         VALUES
18136         (9,'advanced_editor','Use the advanced cataloging editor')
18137     });
18138     if( C4::Context->preference('EnableAdvancedCatalogingEditor') ){
18139         $dbh->do(q{
18140             INSERT INTO user_permissions (borrowernumber, module_bit, code)
18141             SELECT borrowernumber, 9, 'advanced_editor' FROM borrowers WHERE borrowernumber IN (SELECT DISTINCT borrowernumber FROM user_permissions WHERE code = 'edit_catalogue');
18142         });
18143     }
18144     SetVersion( $DBversion );
18145     print "Upgrade to $DBversion done (Bug 20128: Add permission for Advanced Cataloging Editor)\n";
18146 }
18147
18148 $DBversion = '18.12.00.055';
18149 if ( CheckVersion($DBversion) ) {
18150
18151     $dbh->do(qq{
18152         UPDATE
18153           `account_offset_types`
18154         SET
18155           type = 'OVERDUE'
18156         WHERE
18157           type = 'Fine';
18158     });
18159
18160     $dbh->do(qq{
18161         UPDATE
18162           `account_offset_types`
18163         SET
18164           type = 'OVERDUE_INCREASE'
18165         WHERE
18166           type = 'fine_increase';
18167     });
18168
18169     $dbh->do(qq{
18170         UPDATE
18171           `account_offset_types`
18172         SET
18173           type = 'OVERDUE_DECREASE'
18174         WHERE
18175           type = 'fine_decrease';
18176     });
18177
18178     if ( column_exists( 'accountlines', 'accounttype' ) ) {
18179         $dbh->do(
18180             qq{
18181             ALTER TABLE `accountlines`
18182             CHANGE COLUMN `accounttype`
18183               `accounttype` varchar(16) DEFAULT NULL;
18184           }
18185         );
18186     }
18187
18188     $dbh->do(qq{
18189         UPDATE
18190           accountlines
18191         SET
18192           accounttype = 'OVERDUE',
18193           status = 'UNRETURNED'
18194         WHERE
18195           accounttype = 'FU';
18196     });
18197
18198     $dbh->do(qq{
18199         UPDATE
18200           accountlines
18201         SET
18202           accounttype = 'OVERDUE',
18203           status = 'FORGIVEN'
18204         WHERE
18205           accounttype = 'FFOR';
18206     });
18207
18208     $dbh->do(qq{
18209         UPDATE
18210           accountlines
18211         SET
18212           accounttype = 'OVERDUE',
18213           status = 'RETURNED'
18214         WHERE
18215           accounttype = 'F';
18216     });
18217     SetVersion($DBversion);
18218     print "Upgrade to $DBversion done (Bug 22521 - Update accountlines.accounttype to varchar(16), and map new statuses)\n";
18219 }
18220
18221 $DBversion = '18.12.00.056';
18222 if( CheckVersion( $DBversion ) ) {
18223     $dbh->do( "UPDATE systempreferences SET explanation = 'This syspref allows to define custom rules for hiding specific items at the OPAC. See http://wiki.koha-community.org/wiki/OpacHiddenItems for more information.' WHERE variable = 'OpacHiddenItems'");
18224     SetVersion( $DBversion );
18225     print "Upgrade to $DBversion done (Bug 8701 - Update OpacHiddenItems system preference description)\n";
18226 }
18227
18228 $DBversion = '18.12.00.057';
18229 if( CheckVersion( $DBversion ) ) {
18230     if( column_exists('statistics', 'associatedborrower') ) {
18231         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN associatedborrower });
18232     }
18233     if( column_exists('statistics', 'usercode') ) {
18234         $dbh->do(q{ ALTER TABLE statistics DROP COLUMN usercode });
18235     }
18236
18237     SetVersion($DBversion);
18238     print "Upgrade to $DBversion done (Bug 13795 - Delete unused fields from statistics table)\n";
18239 }
18240
18241 $DBversion = '18.12.00.058';
18242 if( CheckVersion( $DBversion ) ) {
18243     my $opaclang = C4::Context->preference("opaclanguages");
18244     my @langs;
18245     push @langs, split ( '\,', $opaclang );
18246     # Get any existing value from the OpacNavRight system preference
18247     my ($OpacNavRight) = $dbh->selectrow_array( q|
18248         SELECT value FROM systempreferences WHERE variable='OpacNavRight';
18249     |);
18250     if( $OpacNavRight ){
18251         # If there is a value in the OpacNavRight preference, insert it into opac_news
18252         $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacNavRight_$langs[0]", $OpacNavRight);
18253     }
18254     # Remove the OpacNavRight system preference
18255     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacNavRight'");
18256     SetVersion ($DBversion);
18257     print "Upgrade to $DBversion done (Bug 22318: Move contents of OpacNavRight preference to Koha news system)\n";
18258 }
18259
18260 $DBversion = '18.12.00.059';
18261 if( CheckVersion( $DBversion ) ) {
18262     if( column_exists( 'import_records', 'z3950random' ) ) {
18263         $dbh->do( "ALTER TABLE import_records DROP COLUMN z3950random" );
18264     }
18265
18266     # Always end with this (adjust the bug info)
18267     SetVersion( $DBversion );
18268     print "Upgrade to $DBversion done (Bug 22532 - Remove import_records z3950random column)\n";
18269 }
18270
18271 $DBversion = '18.12.00.060';
18272 if ( CheckVersion($DBversion) ) {
18273
18274     my $rows = $dbh->do(
18275         qq{
18276         UPDATE `accountlines`
18277         SET
18278           `accounttype` = 'L',
18279           `status`      = 'REPLACED'
18280         WHERE
18281           `accounttype` = 'Rep'
18282       }
18283     );
18284
18285     SetVersion($DBversion);
18286     printf "Upgrade to $DBversion done (Bug 22564 - Fix accounttype 'Rep' - %d updated)\n", $rows;
18287 }
18288
18289 $DBversion = '18.12.00.061';
18290 if( CheckVersion( $DBversion ) ) {
18291
18292     if ( column_exists( 'borrowers', 'flgAnonymized' ) ) {
18293         $dbh->do(q{
18294             UPDATE borrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18295         });
18296         $dbh->do(q{
18297             ALTER TABLE borrowers
18298                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18299         });
18300     }
18301
18302     if ( column_exists( 'deletedborrowers', 'flgAnonymized' ) ) {
18303         $dbh->do(q{
18304             UPDATE deletedborrowers SET flgAnonymized = 0 WHERE flgAnonymized IS NULL
18305         });
18306         $dbh->do(q{
18307             ALTER TABLE deletedborrowers
18308                 CHANGE `flgAnonymized` `anonymized` TINYINT(1) NOT NULL DEFAULT 0
18309         });
18310     }
18311
18312     SetVersion( $DBversion );
18313     print "Upgrade to $DBversion done (Bug 21336 - (follow-up) Rename flgAnonymized column)\n";
18314 }
18315
18316 $DBversion = '18.12.00.062';
18317 if( CheckVersion( $DBversion ) ) {
18318     $dbh->do( q|
18319         UPDATE search_marc_map SET marc_field='007_/0'
18320           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1' AND id IN
18321             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18322               (SELECT id FROM search_field WHERE label='ff7-00')
18323             )
18324     |);
18325
18326     $dbh->do( q|
18327         UPDATE search_marc_map SET marc_field='007_/1'
18328           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/2' AND id IN
18329             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18330               (SELECT id FROM search_field WHERE label='ff7-01')
18331             )
18332     |);
18333
18334     $dbh->do( q|
18335         UPDATE search_marc_map SET marc_field='007_/2'
18336           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/3' AND id IN
18337             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18338               (SELECT id FROM search_field WHERE label='ff7-02')
18339             )
18340     |);
18341
18342     # N.B. ff7-01-02 really is 00-01!
18343     $dbh->do( q|
18344         UPDATE search_marc_map SET marc_field='007_/0-1'
18345           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='007_/1-2' AND id IN
18346             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18347               (SELECT id FROM search_field WHERE label='ff7-01-02')
18348             )
18349     |);
18350
18351     $dbh->do( q|
18352         UPDATE search_marc_map SET marc_field='008_/0-5'
18353           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='008_/1-5' AND id IN
18354             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18355               (SELECT id FROM search_field WHERE label='date-entered-on-file')
18356             )
18357     |);
18358
18359     $dbh->do( q|
18360         UPDATE search_marc_map SET marc_field='leader_/0-4'
18361           WHERE marc_type IN ('marc21', 'normarc') AND marc_field='leader_/1-5' AND id IN
18362             (SELECT search_marc_map_id FROM search_marc_to_field WHERE search_field_id IN
18363               (SELECT id FROM search_field WHERE label='llength')
18364             )
18365     |);
18366
18367     # Always end with this (adjust the bug info)
18368     SetVersion( $DBversion );
18369     print "Upgrade to $DBversion done (Bug 22339 - Fix search field mappings of MARC fixed fields)\n";
18370 }
18371
18372 $DBversion = '18.12.00.063';
18373 if ( CheckVersion($DBversion) ) {
18374
18375     my $types_map = {
18376         'Writeoff'      => 'W',
18377         'Payment'       => 'Pay',
18378         'Lost Item'     => 'CR',
18379         'Manual Credit' => 'C',
18380         'Forgiven'      => 'FOR'
18381     };
18382
18383     my $sth = $dbh->prepare( "SELECT accountlines_id FROM accountlines WHERE accounttype = 'VOID'" );
18384     my $sth2 = $dbh->prepare( "SELECT type FROM account_offsets WHERE credit_id = ? ORDER BY created_on LIMIT 1" );
18385     my $sth3 = $dbh->prepare( "UPDATE accountlines SET accounttype = ?, status = 'VOID' WHERE accountlines_id = ?" );
18386     $sth->execute();
18387     while (my $row = $sth->fetchrow_hashref) {
18388         $sth2->execute($row->{accountlines_id});
18389         my $result = $sth2->fetchrow_hashref;
18390         my $type = $types_map->{$result->{'type'}} // 'Pay';
18391         $sth3->execute($type,$row->{accountlines_id});
18392     }
18393
18394     SetVersion($DBversion);
18395     print "Upgrade to $DBversion done (Bug 22511 - Update existing VOID accountlines)\n";
18396 }
18397
18398 $DBversion = '18.12.00.064';
18399 if( CheckVersion( $DBversion ) ) {
18400     $dbh->do(q{
18401         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('UpdateItemLocationOnCheckin', 'PROC: _PERM_\n', 'NULL', 'This is a list of value pairs.\n Examples:\n PROC: FIC - causes an item in the Processing Center location to be updated into the Fiction location on check in.\n FIC: GEN - causes an item in the Fiction location to be updated into the General stacks location on check in.\n _BLANK_:FIC - causes an item that has no location to be updated into the Fiction location on check in.\nFIC: _BLANK_ - causes an item in location FIC to be updated to a blank location on check in.\n_ALL_:FIC - causes all items to be updated into the Fiction location on check in.\nPROC: _PERM_ - causes an item that is in the Processing Center to be updated to it''s permanent location.\nGeneral rule: if the location value on the left matches the item''s current location, it will be updated to match the location value on the right.\nNote: PROC and CART are special values, for these locations only can location and permanent_location differ, in all other cases an update will affect both. Items in the CART location will be returned to their permanent location on checkout.\nThe special term _BLANK_ may be used on either side of a value pair to update or remove the location from items with no location assigned. The special term _ALL_ is used on the left side of the colon (:) to affect all items.\nThe special term _PERM_ is used on the right side of the colon (:) to return items to their permanent location.', 'Free');
18402     });
18403     $dbh->do(q{
18404         UPDATE systempreferences s1, (SELECT IF(value,'PROC: CART\n','') AS p2c FROM systempreferences WHERE variable='InProcessingToShelvingCart') s2 SET s1.value= CONCAT(s2.p2c, REPLACE(s1.value,'PROC: _PERM_\n','') ) WHERE s1.variable='UpdateItemLocationOnCheckin' AND s1.value NOT LIKE '%PROC: CART%';
18405     });
18406     $dbh->do(q{
18407         DELETE FROM systempreferences WHERE variable='InProcessingToShelvingCart';
18408     });
18409     $dbh->do(q{
18410         UPDATE systempreferences s1, (SELECT IF(value,'_ALL_: CART\n','') AS rtc FROM systempreferences WHERE variable='ReturnToShelvingCart') s2 SET s1.value= CONCAT(s2.rtc,s1.value) WHERE s1.variable='UpdateItemLocationOnCheckin' AND s1.value NOT LIKE '%_ALL_: CART%';
18411     });
18412     $dbh->do(q{
18413         DELETE FROM systempreferences WHERE variable='ReturnToShelvingCart';
18414     });
18415     SetVersion( $DBversion );
18416     print "Upgrade to $DBversion done (Bug 14576: Add UpdateItemLocationOnCheckin syspref)\n";
18417 }
18418
18419 $DBversion = '18.12.00.065';
18420 if( CheckVersion( $DBversion ) ) {
18421     $dbh->do( q{
18422         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
18423         SELECT 'IndependentBranchesTransfers', value, NULL, 'Allow non-superlibrarians to transfer items between libraries','YesNo'
18424         FROM systempreferences WHERE variable = 'IndependentBranches'
18425     });
18426     SetVersion( $DBversion );
18427     print "Upgrade to $DBversion done (Bug 10300 - Allow transferring of items to be have separate IndependentBranches syspref)\n";
18428 }
18429
18430 $DBversion = '18.12.00.066';
18431 if ( CheckVersion($DBversion) ) {
18432     $dbh->do(q{
18433         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `explanation`, `options`, `type`) VALUES
18434           ('OpenURLResolverURL', '', 'URL of OpenURL Resolver', NULL, 'Free'),
18435           ('OpenURLText', '', 'Text of OpenURL links (or image title if OpenURLImageLocation is defined)', NULL, 'Free'),
18436           ('OpenURLImageLocation', '', 'Location of image for OpenURL links', NULL, 'Free'),
18437           ('OPACShowOpenURL', '', 'Enable display of OpenURL links in OPAC search results and detail page', NULL, 'YesNo'),
18438           ('OPACOpenURLItemTypes', '', 'Show the OpenURL link only for these item types', NULL, 'Free');
18439     });
18440
18441     SetVersion($DBversion);
18442     print
18443 "Upgrade to $DBversion done (Bug 8995 - Add new preferences for OpenURLResolvers)\n";
18444 }
18445
18446 $DBversion = '18.12.00.067';
18447 if ( CheckVersion($DBversion) ) {
18448     $dbh->do(q{
18449         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
18450         VALUES ('SendAllEmailsTo','',NULL,'All emails will be redirected to this email if it is not empty','free');
18451     });
18452     SetVersion($DBversion);
18453     print
18454 "Upgrade to $DBversion done (Bug 8000 - Add new preferences for SendAllEmailsTo)\n";
18455 }
18456
18457 $DBversion = '18.12.00.068';
18458 if ( CheckVersion($DBversion) ) {
18459     $dbh->do(q{
18460         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES
18461         ('AllowRenewalOnHoldOverride','0','','If on, allow items on hold to be renewed with a specified due date','YesNo');
18462     });
18463     SetVersion($DBversion);
18464     print "Upgrade to $DBversion done (Bug 7088: Cannot renew items on hold even with override)\n";
18465 }
18466
18467 $DBversion = '18.12.00.069';
18468 if( CheckVersion( $DBversion ) ) {
18469
18470     $dbh->do(q{
18471         INSERT INTO plugin_data
18472             (plugin_class, plugin_key, plugin_value)
18473         SELECT
18474             plugin_class,
18475             '__ENABLED__',
18476             1
18477         FROM plugin_data
18478         WHERE plugin_key='__INSTALLED_VERSION__'
18479     });
18480
18481     # Always end with this (adjust the bug info)
18482     SetVersion( $DBversion );
18483     print "Upgrade to $DBversion done (Bug 22053 - enable all plugins)\n";
18484 }
18485
18486 $DBversion = '18.12.00.070';
18487 if ( CheckVersion($DBversion) ) {
18488     $dbh->do(q{
18489         INSERT IGNORE INTO systempreferences
18490             ( `variable`, `value`, `options`, `explanation`, `type` )
18491         VALUES
18492         ('SelfCheckAllowByIPRanges','',NULL,'(Leave blank if not used. Use ranges or simple ip addresses separated by spaces, like <code>192.168.1.1 192.168.0.0/24</code>.)','Short');
18493     });
18494     SetVersion($DBversion);
18495     print "Upgrade to $DBversion done (Bug 14407 - Limit web-based self-checkout to specific IP addresses)\n";
18496 }
18497
18498 $DBversion = '18.12.00.071';
18499 if( CheckVersion( $DBversion ) ) {
18500     $dbh->do(q{
18501 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18502 ('circulation', 'ACCOUNT_CREDIT', '', 'Account payment', 0, 'Account payment', '<table>
18503 [% IF ( LibraryName ) %]
18504  <tr>
18505     <th colspan="4" class="centerednames">
18506         <h3>[% LibraryName | html %]</h3>
18507     </th>
18508  </tr>
18509 [% END %]
18510  <tr>
18511     <th colspan="4" class="centerednames">
18512         <h2><u>Fee receipt</u></h2>
18513     </th>
18514  </tr>
18515  <tr>
18516     <th colspan="4" class="centerednames">
18517         <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18518     </th>
18519  </tr>
18520  <tr>
18521     <th colspan="4">
18522         Received with thanks from  [% patron.firstname | html %] [% patron.surname | html %] <br />
18523         Card number: [% patron.cardnumber | html %]<br />
18524     </th>
18525  </tr>
18526   <tr>
18527     <th>Date</th>
18528     <th>Description of charges</th>
18529     <th>Note</th>
18530     <th>Amount</th>
18531  </tr>
18532
18533   [% FOREACH account IN accounts %]
18534     <tr class="highlight">
18535       <td>[% account.date | $KohaDates %]</td>
18536       <td>
18537         [% PROCESS account_type_description account=account %]
18538         [%- IF account.description %], [% account.description | html %][% END %]
18539       </td>
18540       <td>[% account.note | html %]</td>
18541       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18542     </tr>
18543
18544   [% END %]
18545 <tfoot>
18546   <tr>
18547     <td colspan="3">Total outstanding dues as on date: </td>
18548     [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18549   </tr>
18550 </tfoot>
18551 </table>', 'print', 'default');
18552     });
18553     SetVersion( $DBversion );
18554     print "Upgrade to $DBversion done (Bug 22809 - Move 'ACCOUNT_CREDIT' from template to a slip)\n";
18555 }
18556
18557 $DBversion = '18.12.00.072';
18558 if( CheckVersion( $DBversion ) ) {
18559     $dbh->do(q{
18560 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
18561 ('circulation', 'ACCOUNT_DEBIT', '', 'Account fee', 0, 'Account fee', '<table>
18562   [% IF ( LibraryName ) %]
18563     <tr>
18564       <th colspan="5" class="centerednames">
18565         <h3>[% LibraryName | html %]</h3>
18566       </th>
18567     </tr>
18568   [% END %]
18569
18570   <tr>
18571     <th colspan="5" class="centerednames">
18572       <h2><u>INVOICE</u></h2>
18573     </th>
18574   </tr>
18575   <tr>
18576     <th colspan="5" class="centerednames">
18577       <h2>[% Branches.GetName( patron.branchcode ) | html %]</h2>
18578     </th>
18579   </tr>
18580   <tr>
18581     <th colspan="5" >
18582       Bill to: [% patron.firstname | html %] [% patron.surname | html %] <br />
18583       Card number: [% patron.cardnumber | html %]<br />
18584     </th>
18585   </tr>
18586   <tr>
18587     <th>Date</th>
18588     <th>Description of charges</th>
18589     <th>Note</th>
18590     <th style="text-align:right;">Amount</th>
18591     <th style="text-align:right;">Amount outstanding</th>
18592   </tr>
18593
18594   [% FOREACH account IN accounts %]
18595     <tr class="highlight">
18596       <td>[% account.date | $KohaDates%]</td>
18597       <td>
18598         [% PROCESS account_type_description account=account %]
18599         [%- IF account.description %], [% account.description | html %][% END %]
18600       </td>
18601       <td>[% account.note | html %]</td>
18602       [% IF ( account.amountcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amount | $Price %]</td>
18603       [% IF ( account.amountoutstandingcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% account.amountoutstanding | $Price %]</td>
18604     </tr>
18605   [% END %]
18606
18607   <tfoot>
18608     <tr>
18609       <td colspan="4">Total outstanding dues as on date: </td>
18610       [% IF ( totalcredit ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% total | $Price %]</td>
18611     </tr>
18612   </tfoot>
18613 </table>', 'print', 'default');
18614     });
18615     SetVersion( $DBversion );
18616     print "Upgrade to $DBversion done (Bug 22809 - Move 'INVOICE' from template to a slip)\n";
18617 }
18618
18619 $DBversion = '18.12.00.073';
18620 if( CheckVersion( $DBversion ) ) {
18621     $dbh->do( q{
18622             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
18623             ('EmailPurchaseSuggestions','0','0|EmailAddressForSuggestions|BranchEmailAddress|KohaAdminEmailAddress','Choose email address that will be sent new purchase suggestions','Choice'),
18624             ('EmailAddressForSuggestions','','','If you choose EmailAddressForSuggestions you should enter a valid email address','free')
18625     });
18626
18627     $dbh->do( q{
18628             INSERT IGNORE INTO `letter` (module, code, name, title, content, is_html, message_transport_type) VALUES
18629             ('suggestions','NEW_SUGGESTION','New suggestion','New suggestion','<h3>Suggestion pending approval</h3>
18630                 <p><h4>Suggested by</h4>
18631                     <ul>
18632                         <li><<borrowers.firstname>> <<borrowers.surname>></li>
18633                         <li><<borrowers.cardnumber>></li>
18634                         <li><<borrowers.phone>></li>
18635                         <li><<borrowers.email>></li>
18636                     </ul>
18637                 </p>
18638                 <p><h4>Title suggested</h4>
18639                     <ul>
18640                         <li><b>Library:</b> <<branches.branchname>></li>
18641                         <li><b>Title:</b> <<suggestions.title>></li>
18642                         <li><b>Author:</b> <<suggestions.author>></li>
18643                         <li><b>Copyright date:</b> <<suggestions.copyrightdate>></li>
18644                         <li><b>Standard number (ISBN, ISSN or other):</b> <<suggestions.isbn>></li>
18645                         <li><b>Publisher:</b> <<suggestions.publishercode>></li>
18646                         <li><b>Collection title:</b> <<suggestions.collectiontitle>></li>
18647                         <li><b>Publication place:</b> <<suggestions.place>></li>
18648                         <li><b>Quantity:</b> <<suggestions.quantity>></li>
18649                         <li><b>Item type:</b> <<suggestions.itemtype>></li>
18650                         <li><b>Reason for suggestion:</b> <<suggestions.patronreason>></li>
18651                         <li><b>Notes:</b> <<suggestions.note>></li>
18652                     </ul>
18653                 </p>',1, 'email')
18654     });
18655
18656     SetVersion( $DBversion );
18657     print "Upgrade to $DBversion done (Bug 5770 - Email librarian when purchase suggestion made)\n";
18658 }
18659
18660 $DBversion = '18.12.00.074';
18661 if( CheckVersion( $DBversion ) ) {
18662     unless ( TableExists( 'keyboard_shortcuts' ) ) {
18663         $dbh->do(q|
18664             CREATE TABLE keyboard_shortcuts (
18665             shortcut_name varchar(80) NOT NULL,
18666             shortcut_keys varchar(80) NOT NULL,
18667             PRIMARY KEY (shortcut_name)
18668             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
18669         );
18670     }
18671     $dbh->do(q|
18672         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
18673         ("insert_copyright","Alt-C"),
18674         ("insert_copyright_sound","Alt-P"),
18675         ("insert_delimiter","Ctrl-D"),
18676         ("subfield_help","Ctrl-H"),
18677         ("link_authorities","Shift-Ctrl-L"),
18678         ("delete_field","Ctrl-X"),
18679         ("delete_subfield","Shift-Ctrl-X"),
18680         ("new_line","Enter"),
18681         ("line_break","Shift-Enter"),
18682         ("next_position","Tab"),
18683         ("prev_position","Shift-Tab")
18684         ;|
18685     );
18686     $dbh->do(q|
18687         INSERT IGNORE permissions (module_bit, code, description)
18688         VALUES
18689         (3,'manage_keyboard_shortcuts','Manage keyboard shortcuts for advanced cataloging editor')
18690         ;|
18691     );
18692     SetVersion( $DBversion );
18693     print "Upgrade to $DBversion done (Bug 21411 - Add keyboard_shortcuts table)\n";
18694 }
18695
18696 $DBversion = '18.12.00.075';
18697 if( CheckVersion( $DBversion ) ) {
18698     # you can use $dbh here like:
18699     unless ( foreign_key_exists( 'tmp_holdsqueue', 'tmp_holdsqueue_ibfk_1' ) ) {
18700         $dbh->do(q{
18701             DELETE t FROM tmp_holdsqueue t
18702             LEFT JOIN items i ON t.itemnumber=i.itemnumber
18703             WHERE i.itemnumber IS NULL
18704         });
18705         $dbh->do(q{
18706             ALTER TABLE tmp_holdsqueue
18707             ADD CONSTRAINT `tmp_holdsqueue_ibfk_1` FOREIGN KEY (`itemnumber`)
18708             REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
18709         });
18710     }
18711     SetVersion( $DBversion );
18712     print "Upgrade to $DBversion done (Bug 22899 - Add items constraint to tmp_holdsqueue)\n";
18713 }
18714
18715 $DBversion = '19.05.00.000';
18716 if( CheckVersion( $DBversion ) ) {
18717     SetVersion( $DBversion );
18718     print "Upgrade to $DBversion done (19.05.00 release)\n";
18719 }
18720
18721 $DBversion = '19.06.00.000';
18722 if( CheckVersion( $DBversion ) ) {
18723     SetVersion( $DBversion );
18724     print "Upgrade to $DBversion done (Wingardium Leviosa!)\n";
18725 }
18726
18727 $DBversion = '19.06.00.001'; 
18728 if( CheckVersion( $DBversion ) ) {
18729     $dbh->do( q{
18730         UPDATE systempreferences 
18731         SET explanation = 'This is a list of value pairs.\n Examples:\n PROC: FIC - causes an item in the Processing Center location to be updated into the Fiction location on check in.\n FIC: GEN - causes an item in the Fiction location to be updated into the General stacks location on check in.\n _BLANK_:FIC - causes an item that has no location to be updated into the Fiction location on check in.\nFIC: _BLANK_ - causes an item in location FIC to be updated to a blank location on check in.\n_ALL_:FIC - causes all items to be updated into the Fiction location on check in.\nPROC: _PERM_ - causes an item that is in the Processing Center to be updated to it''s permanent location.\nGeneral rule: if the location value on the left matches the item''s current location, it will be updated to match the location value on the right.\nNote: PROC and CART are special values, for these locations only can location and permanent_location differ, in all other cases an update will affect both. Items in the CART location will be returned to their permanent location on checkout.\nThe special term _BLANK_ may be used on either side of a value pair to update or remove the location from items with no location assigned. The special term _ALL_ is used on the left side of the colon (:) to affect all items.\nThe special term _PERM_ is used on the right side of the colon (:) to return items to their permanent location.' 
18732         WHERE variable = 'UpdateItemLocationOnCheckin'
18733     });
18734     SetVersion( $DBversion );
18735     print "Upgrade to $DBversion done (Bug 22960: Fix typo in syspref description)\n";
18736 }
18737
18738 $DBversion = '19.06.00.002';
18739 if ( CheckVersion($DBversion) ) {
18740
18741     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE opacnote opacnote LONGTEXT NULL});
18742     $dbh->do(q{ALTER TABLE subscriptionhistory CHANGE librariannote librariannote LONGTEXT NULL});
18743
18744     $dbh->do(q{UPDATE subscriptionhistory SET opacnote = NULL WHERE opacnote = ''});
18745     $dbh->do(q{UPDATE subscriptionhistory SET librariannote = NULL WHERE librariannote = ''});
18746
18747     SetVersion ($DBversion);
18748     print "Upgrade to $DBversion done (Bug 10215: Increase the size of opacnote and librariannote for table subscriptionhistory)\n";
18749 }
18750
18751 $DBversion = '19.06.00.003';
18752 if( CheckVersion( $DBversion ) ) {
18753     $dbh->do(q{UPDATE systempreferences SET value = REPLACE( value, ' ', '|' ) WHERE variable = 'UniqueItemFields'; });
18754
18755     SetVersion( $DBversion );
18756     print "Upgrade to $DBversion done (Bug 22867: UniqueItemFields preference value should be pipe-delimited)\n";
18757 }
18758
18759 $DBversion = '19.06.00.004';
18760 if( CheckVersion( $DBversion ) ) {
18761     $dbh->do( 'UPDATE language_descriptions SET description = "Griechisch (Modern 1453-)"
18762       WHERE subtag = "el" and type = "language" and lang ="de"' );
18763     SetVersion( $DBversion );
18764     print "Upgrade to $DBversion done (Bug 22770: Fix typo in language description for el in German)\n";
18765 }
18766
18767 $DBversion = '19.06.00.005';
18768 if( CheckVersion( $DBversion ) ) {
18769     unless ( column_exists( 'reserves', 'item_level_hold' ) ) {
18770         $dbh->do( "ALTER TABLE reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18771     }
18772     unless ( column_exists( 'old_reserves', 'item_level_hold' ) ) {
18773         $dbh->do( "ALTER TABLE old_reserves ADD COLUMN item_level_hold BOOLEAN NOT NULL DEFAULT 0 AFTER itemtype" );
18774     }
18775
18776     SetVersion( $DBversion );
18777     print "Upgrade to $DBversion done (Bug  9834: Add the reserves.item_level_hold column)\n";
18778 }
18779
18780 $DBversion = '19.06.00.006';
18781 if( CheckVersion( $DBversion ) ) {
18782
18783     unless ( TableExists('plugin_methods') ) {
18784         $dbh->do(q{
18785             CREATE TABLE plugin_methods (
18786               plugin_class varchar(255) NOT NULL,
18787               plugin_method varchar(255) NOT NULL,
18788               PRIMARY KEY ( `plugin_class` (191), `plugin_method` (191) )
18789             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
18790         });
18791     }
18792
18793     require Koha::Plugins;
18794     Koha::Plugins->new({ enable_plugins => 1 })->InstallPlugins;
18795
18796     SetVersion( $DBversion );
18797     print "Upgrade to $DBversion done (Bug 21073: Improve plugin performance)\n";
18798 }
18799
18800 $DBversion = '19.06.00.007';
18801 if( CheckVersion( $DBversion ) ) {
18802     $dbh->do( "DELETE FROM systempreferences WHERE variable = 'RotationPreventTransfers'" );
18803     SetVersion( $DBversion );
18804     print "Upgrade to $DBversion done (Bug 22653: Remove unimplemented RotationPreventTransfers system preference)\n";
18805 }
18806
18807 $DBversion = '19.06.00.008';
18808 if( CheckVersion( $DBversion ) ) {
18809     $dbh->do( "UPDATE userflags SET flagdesc = 'Allow staff members to modify permissions and passwords for other staff members' WHERE flag = 'staffaccess'" );
18810     SetVersion( $DBversion );
18811     print "Upgrade to $DBversion done (Bug 23109: Improve description of staffaccess permission)\n";
18812 }
18813
18814 $DBversion = '19.06.00.009';
18815 if( CheckVersion( $DBversion ) ) {
18816     $dbh->do(q{
18817         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys)
18818             VALUES ("toggle_keyboard", "Shift-Ctrl-K")
18819     });
18820
18821     SetVersion( $DBversion );
18822     print "Upgrade to $DBversion done (Bug 17178: add shortcut to keyboard_shortcuts)\n";
18823 }
18824
18825 $DBversion = '19.06.00.010';
18826 if( CheckVersion( $DBversion ) ) {
18827
18828     if ( TableExists('default_circ_rules') ) {
18829         if ( column_exists( 'default_circ_rules', 'holdallowed' ) ) {
18830             $dbh->do("
18831                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18832                 SELECT NULL, NULL, NULL, 'holdallowed', holdallowed
18833                 FROM default_circ_rules
18834             ");
18835             $dbh->do("
18836                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18837                 SELECT NULL, NULL, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18838                 FROM default_circ_rules
18839             ");
18840             $dbh->do("
18841                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18842                 SELECT NULL, NULL, NULL, 'returnbranch', returnbranch
18843                 FROM default_circ_rules
18844             ");
18845             $dbh->do("DROP TABLE default_circ_rules");
18846         }
18847     }
18848
18849     if ( TableExists('default_branch_circ_rules') ) {
18850         if ( column_exists( 'default_branch_circ_rules', 'holdallowed' ) ) {
18851             $dbh->do("
18852                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18853                 SELECT NULL, branchcode, NULL, 'holdallowed', holdallowed
18854                 FROM default_branch_circ_rules
18855             ");
18856             $dbh->do("
18857                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18858                 SELECT NULL, branchcode, NULL, 'hold_fulfillment_policy', hold_fulfillment_policy
18859                 FROM default_branch_circ_rules
18860             ");
18861             $dbh->do("
18862                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18863                 SELECT NULL, branchcode, NULL, 'returnbranch', returnbranch
18864                 FROM default_branch_circ_rules
18865             ");
18866             $dbh->do("DROP TABLE default_branch_circ_rules");
18867         }
18868     }
18869
18870     if ( TableExists('branch_item_rules') ) {
18871         if ( column_exists( 'branch_item_rules', 'holdallowed' ) ) {
18872             $dbh->do("
18873                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18874                 SELECT NULL, branchcode, itemtype, 'holdallowed', holdallowed
18875                 FROM branch_item_rules
18876             ");
18877             $dbh->do("
18878                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18879                 SELECT NULL, branchcode, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18880                 FROM branch_item_rules
18881             ");
18882             $dbh->do("
18883                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18884                 SELECT NULL, branchcode, itemtype, 'returnbranch', returnbranch
18885                 FROM branch_item_rules
18886             ");
18887             $dbh->do("DROP TABLE branch_item_rules");
18888         }
18889     }
18890
18891     if ( TableExists('default_branch_item_rules') ) {
18892         if ( column_exists( 'default_branch_item_rules', 'holdallowed' ) ) {
18893             $dbh->do("
18894                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18895                 SELECT NULL, NULL, itemtype, 'holdallowed', holdallowed
18896                 FROM default_branch_item_rules
18897             ");
18898             $dbh->do("
18899                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18900                 SELECT NULL, NULL, itemtype, 'hold_fulfillment_policy', hold_fulfillment_policy
18901                 FROM default_branch_item_rules
18902             ");
18903             $dbh->do("
18904                 INSERT IGNORE INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18905                 SELECT NULL, NULL, itemtype, 'returnbranch', returnbranch
18906                 FROM default_branch_item_rules
18907             ");
18908             $dbh->do("DROP TABLE default_branch_item_rules");
18909         }
18910     }
18911
18912     SetVersion( $DBversion );
18913     print "Upgrade to $DBversion done (Bug 18928: Move holdallowed, hold_fulfillment_policy, returnbranch to circulation_rules)\n";
18914 }
18915
18916 $DBversion = '19.06.00.011';
18917 if( CheckVersion( $DBversion ) ) {
18918
18919     if ( TableExists('refund_lost_item_fee_rules') ) {
18920         if ( column_exists( 'refund_lost_item_fee_rules', 'refund' ) ) {
18921             $dbh->do("
18922                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
18923                 SELECT NULL, IF(branchcode='*', NULL, branchcode), NULL, 'refund', refund
18924                 FROM refund_lost_item_fee_rules
18925             ");
18926             $dbh->do("DROP TABLE refund_lost_item_fee_rules");
18927         }
18928     }
18929
18930     SetVersion( $DBversion );
18931     print "Upgrade to $DBversion done (Bug 18930: Move lost item refund rules to circulation_rules table)\n";
18932 }
18933
18934 $DBversion = '19.06.00.012';
18935 if ( CheckVersion($DBversion) ) {
18936
18937     # Find and correct pathological cases of LR becoming a credit
18938     my $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'LR' AND amount < 0" );
18939     $sth->execute();
18940     while ( my $row = $sth->fetchrow_hashref ) {
18941         $dbh->do(
18942             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18943             {},
18944             (
18945                 'CR',                   $row->{issue_id},
18946                 $row->{borrowernumber}, $row->{itemnumber},
18947                 $row->{amount},         $row->{manager_id},
18948                 'upgrade'
18949             )
18950         );
18951         my $credit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18952         my $amount = $row->{amount} * -1;
18953         $dbh->do("INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",{},($credit_id, $row->{accountlines_id}, 'Lost Item', $amount));
18954         $dbh->do("UPDATE accountlines SET amount = '$amount' WHERE accountlines_id = '$row->{accountlines_id}';");
18955     }
18956
18957     $dbh->do(qq{
18958         UPDATE
18959           accountlines
18960         SET
18961           accounttype = 'LOST',
18962           status = 'RETURNED'
18963         WHERE
18964           accounttype = 'LR';
18965     });
18966
18967     # Find and correct pathalogical cases of L having been converted to W
18968     $sth = $dbh->prepare( "SELECT accountlines_id, issue_id, borrowernumber, itemnumber, amount, manager_id FROM accountlines WHERE accounttype = 'W' AND itemnumber IS NOT NULL" );
18969     $sth->execute();
18970     while ( my $row = $sth->fetchrow_hashref ) {
18971         my $amount = $row->{amount} * -1;
18972         $dbh->do(
18973             "INSERT INTO accountlines (accounttype, issue_id, borrowernumber, itemnumber, amount, manager_id, interface) VALUES ( ?, ?, ?, ?, ?, ?, ? );",
18974             {},
18975             (
18976                 'LOST', $row->{issue_id}, $row->{borrowernumber},
18977                 $row->{itemnumber}, $amount, $row->{manager_id},
18978                 'upgrade'
18979             )
18980         );
18981         my $debit_id = $dbh->last_insert_id(undef, undef, 'accountlines', undef);
18982         $dbh->do(
18983             "INSERT INTO account_offsets (credit_id, debit_id, type, amount) VALUES (?,?,?,?);",
18984             {},
18985             (
18986                 $row->{accountlines_id}, $debit_id,
18987                 'Lost Item',    $amount
18988             )
18989         );
18990     }
18991
18992     $dbh->do(qq{
18993         UPDATE
18994           accountlines
18995         SET
18996           accounttype = 'LOST'
18997         WHERE
18998           accounttype = 'L';
18999     });
19000
19001     $dbh->do(qq{
19002         UPDATE
19003           accountlines
19004         SET
19005           accounttype = 'LOST_RETURN'
19006         WHERE
19007           accounttype = 'CR';
19008     });
19009
19010     SetVersion($DBversion);
19011     print "Upgrade to $DBversion done (Bug 22563: Fix accounttypes for 'L', 'LR' and 'CR')\n";
19012 }
19013
19014 $DBversion = '19.06.00.013';
19015 if ( CheckVersion( $DBversion ) ) {
19016     unless ( column_exists( 'borrower_modifications', 'changed_fields' ) ) {
19017         $dbh->do("ALTER TABLE borrower_modifications ADD changed_fields MEDIUMTEXT AFTER verification_token;");
19018     }
19019     SetVersion( $DBversion );
19020     print "Upgrade to $DBversion done (Bug 23151: Add borrower_modifications.changed_fields column)\n";
19021 }
19022
19023 $DBversion = '19.06.00.014';
19024 if ( CheckVersion($DBversion) ) {
19025
19026     $dbh->do(qq{
19027         UPDATE
19028           accountlines
19029         SET
19030           accounttype = 'RENT_DAILY_RENEW'
19031         WHERE
19032           accounttype = 'Rent'
19033         AND
19034           description LIKE 'Renewal of Daily Rental Item%';
19035     });
19036
19037     $dbh->do(qq{
19038         UPDATE
19039           accountlines
19040         SET
19041           accounttype = 'RENT_DAILY'
19042         WHERE
19043           accounttype = 'Rent'
19044         AND
19045           description LIKE 'Daily rental';
19046     });
19047
19048
19049     $dbh->do(qq{
19050         UPDATE
19051           accountlines
19052         SET
19053           accounttype = 'RENT_RENEW'
19054         WHERE
19055           accounttype = 'Rent'
19056         AND
19057           description LIKE 'Renewal of Rental Item%';
19058     });
19059
19060     $dbh->do(qq{
19061         UPDATE
19062           accountlines
19063         SET
19064           accounttype = 'RENT'
19065         WHERE
19066           accounttype = 'Rent';
19067     });
19068
19069     SetVersion($DBversion);
19070     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'Rent')\n";
19071 }
19072
19073 $DBversion = '19.06.00.015';
19074 if( CheckVersion( $DBversion ) ) {
19075     $dbh->do( "UPDATE `search_field` SET `name` = 'date-time-last-modified', `label` = 'date-time-last-modified' WHERE `name` = 'date/time-last-modified'" );
19076
19077     SetVersion( $DBversion );
19078     print "Upgrade to $DBversion done (Bug 22524: Fix date/time-last-modified search with Elasticsearch)\n";
19079 }
19080
19081 $DBversion = '19.06.00.016';
19082 if( CheckVersion( $DBversion ) ) {
19083
19084     $dbh->do(q|
19085         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19086             ("insert_copyright","Alt-C"),
19087             ("insert_copyright_sound","Alt-P"),
19088             ("insert_delimiter","Ctrl-D"),
19089             ("subfield_help","Ctrl-H"),
19090             ("link_authorities","Shift-Ctrl-L"),
19091             ("delete_field","Ctrl-X"),
19092             ("delete_subfield","Shift-Ctrl-X"),
19093             ("new_line","Enter"),
19094             ("line_break","Shift-Enter"),
19095             ("next_position","Tab"),
19096             ("prev_position","Shift-Tab"),
19097             ("toggle_keyboard", "Shift-Ctrl-K")
19098     ;|);
19099
19100     SetVersion( $DBversion );
19101     print "Upgrade to $DBversion done (Bug 23396: Fix missing keyboard_shortcuts table)\n";
19102 }
19103
19104 $DBversion = '19.06.00.017';
19105 if ( CheckVersion($DBversion) ) {
19106
19107     $dbh->do(qq{
19108         INSERT INTO
19109           authorised_values (category,authorised_value,lib)
19110         VALUES
19111           ('PAYMENT_TYPE','SIP00','Cash via SIP2'),
19112           ('PAYMENT_TYPE','SIP01','VISA via SIP2'),
19113           ('PAYMENT_TYPE','SIP02','Creditcard via SIP2')
19114     });
19115
19116     $dbh->do(qq{
19117         UPDATE
19118           accountlines
19119         SET
19120           accounttype  = 'Pay',
19121           payment_type = 'SIP00'
19122         WHERE
19123           accounttype = 'Pay00';
19124     });
19125
19126     $dbh->do(qq{
19127         UPDATE
19128           accountlines
19129         SET
19130           accounttype  = 'Pay',
19131           payment_type = 'SIP01'
19132         WHERE
19133           accounttype = 'Pay01';
19134     });
19135
19136     $dbh->do(qq{
19137         UPDATE
19138           accountlines
19139         SET
19140           accounttype  = 'Pay',
19141           payment_type = 'SIP02'
19142         WHERE
19143           accounttype = 'Pay02';
19144     });
19145
19146     my $sth = $dbh->prepare( q{SELECT * FROM accountlines WHERE accounttype REGEXP '^Pay[[:digit:]]{2}$' } );
19147     $sth->execute();
19148     my $seen = {};
19149     while (my $row = $sth->fetchrow_hashref) {
19150         my $type = $row->{accounttype};
19151         my $sipcode = $type;
19152         $sipcode =~ s/Pay/SIP/g;
19153         unless ($seen->{$sipcode}) {
19154             $dbh->do(qq{
19155                 INSERT INTO
19156                   authorised_values (category,authorised_value,lib)
19157                 VALUES
19158                   ('PAYMENT_TYPE',"$sipcode",'Unrecognised SIP2 payment type')
19159             });
19160
19161              $dbh->do(qq{
19162                 UPDATE
19163                   accountlines
19164                 SET
19165                   accounttype  = 'Pay',
19166                   payment_type = "$sipcode"
19167                 WHERE
19168                   accounttype = "$type";
19169             });
19170
19171             $seen->{$sipcode} = 1;
19172         }
19173     }
19174
19175     SetVersion($DBversion);
19176     print "Upgrade to $DBversion done (Bug 22610: Fix accounttypes for SIP2 payments)\n";
19177 }
19178
19179 $DBversion = '19.06.00.018';
19180 if( CheckVersion( $DBversion ) ) {
19181     if( !column_exists( 'biblio', 'subtitle' ) ) {
19182         $dbh->do( "ALTER TABLE biblio ADD COLUMN medium LONGTEXT AFTER title" );
19183         $dbh->do( "ALTER TABLE biblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19184         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19185         $dbh->do( "ALTER TABLE biblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19186
19187         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN medium LONGTEXT AFTER title" );
19188         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN subtitle LONGTEXT AFTER medium" );
19189         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_number LONGTEXT AFTER subtitle" );
19190         $dbh->do( "ALTER TABLE deletedbiblio ADD COLUMN part_name LONGTEXT AFTER part_number" );
19191     }
19192
19193     $dbh->do( "UPDATE marc_subfield_structure SET kohafield='biblio.subtitle' WHERE kohafield='bibliosubtitle.subtitle'" );
19194
19195     my $marcflavour = C4::Context->preference('marcflavour');
19196
19197     if ( $marcflavour eq 'UNIMARC' ) {
19198         $dbh->do(qq{
19199             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19200             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='b'
19201         });
19202         $dbh->do(qq{
19203             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19204             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='e'
19205         });
19206         $dbh->do(qq{
19207             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19208             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='h'
19209         });
19210         $dbh->do(qq{
19211             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19212             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='200' AND tagsubfield='i'
19213         });
19214     } else {
19215         $dbh->do(qq{
19216             UPDATE marc_subfield_structure SET kohafield='biblio.medium'
19217             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='h'
19218         });
19219         $dbh->do(qq{
19220             UPDATE marc_subfield_structure SET kohafield='biblio.subtitle'
19221             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='b'
19222         });
19223         $dbh->do(qq{
19224             UPDATE marc_subfield_structure SET kohafield='biblio.part_number'
19225             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='n'
19226         });
19227         $dbh->do(qq{
19228             UPDATE marc_subfield_structure SET kohafield='biblio.part_name'
19229             WHERE (kohafield IS NULL OR kohafield='') AND frameworkcode='' AND tagfield='245' AND tagsubfield='p'
19230         });
19231     }
19232
19233     $sth = $dbh->prepare("SELECT * FROM fieldmapping");
19234     $sth->execute;
19235     my @fails_11529;
19236     if ( $sth->rows ) {
19237         while ( my $value = $sth->fetchrow_hashref() ) {
19238             my $framework =
19239               $value->{frameworkcode} eq ""
19240               ? "Default"
19241               : $value->{frameworkcode};
19242             push @fails_11529,
19243               {
19244                 field        => $value->{field},
19245                 fieldcode    => $value->{fieldcode},
19246                 subfieldcode => $value->{subfieldcode},
19247                 framework    => $framework
19248               };
19249         }
19250     }
19251
19252     $dbh->do( "DROP TABLE IF EXISTS fieldmapping" );
19253
19254     $dbh->do( "DELETE FROM user_permissions WHERE code='manage_keywords2koha_mappings'" );
19255
19256     $dbh->do( "DELETE FROM permissions WHERE code='manage_keywords2koha_mappings'" );
19257
19258     # Always end with this (adjust the bug info)
19259     SetVersion( $DBversion );
19260     print "Upgrade to $DBversion done (Bug 11529: Add medium, subtitle and part information to biblio table)\n";
19261     if ( @fails_11529 ) {
19262         print "WARNING: Keyword to MARC Mappings:\n";
19263         for my $fail_11529 ( @fails_11529 ) {
19264             print "    keyword: "
19265               . $fail_11529->{field}
19266               . " to field: "
19267               . $fail_11529->{fieldcode} . "\$"
19268               . $fail_11529->{subfieldcode} . " for "
19269               . $fail_11529->{framework}
19270               . " framework\n";
19271         }
19272         print "The keyword to marc mapping feature is no longer supported. Above find the\n";
19273         print "mappings that had been defined in your system. You will need to remap any\n";
19274         print "desired MARC fields to the Koha field you desire in the Koha to MARC mappings\n";
19275         print "page under Administration\n";
19276     }
19277     print "NOTE: misc/batchRebuildBiblioTables.pl should be run to populate the fields introduced in bug 11529. It may take some time for larger databases.\n\n"
19278 }
19279
19280 $DBversion = '19.06.00.019';
19281 if ( CheckVersion($DBversion) ) {
19282     $dbh->do(q{
19283         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
19284         VALUES
19285           (
19286             'FinePaymentAutoPopup',
19287             '0',
19288             NULL,
19289             'If enabled, automatically display a print dialog for a payment receipt when making a payment.',
19290             'YesNo'
19291           )
19292     });
19293
19294     SetVersion($DBversion);
19295     print
19296 "Upgrade to $DBversion done (Bug 23228: Add option to automatically display payment receipt for printing after making a payment)\n";
19297 }
19298
19299 $DBversion = '19.06.00.020';
19300 if( CheckVersion( $DBversion ) ) {
19301     $dbh->do(q|
19302         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19303         ('PreserveSerialNotes','1','','When a new "Expected" issue is generated, should it be prefilled with last created issue notes?','YesNo');
19304     |);
19305
19306     SetVersion( $DBversion );
19307     print "Upgrade to $DBversion done (Bug 23416: Add PreserveSerialNotes syspref)\n";
19308 }
19309
19310 $DBversion = '19.06.00.021';
19311 if( CheckVersion( $DBversion ) ) {
19312
19313     $dbh->do(q|
19314         ALTER TABLE marc_subfield_structure CHANGE COLUMN hidden hidden TINYINT(1) DEFAULT 8 NOT NULL;
19315     |);
19316     # Always end with this (adjust the bug info)
19317     SetVersion( $DBversion );
19318     print "Upgrade to $DBversion done (Bug 23309: Can't add new subfields to bibliographic frameworks in strict mode)\n";
19319 }
19320
19321 $DBversion = '19.06.00.022';
19322 if ( CheckVersion($DBversion) ) {
19323
19324     unless ( TableExists('borrower_relationships') ) {
19325         $dbh->do(q{
19326             CREATE TABLE `borrower_relationships` (
19327                   id INT(11) NOT NULL AUTO_INCREMENT,
19328                   guarantor_id INT(11) NOT NULL,
19329                   guarantee_id INT(11) NOT NULL,
19330                   relationship VARCHAR(100) NOT NULL,
19331                   PRIMARY KEY (id),
19332                   UNIQUE KEY `guarantor_guarantee_idx` ( `guarantor_id`, `guarantee_id` ),
19333                   CONSTRAINT r_guarantor FOREIGN KEY ( guarantor_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE,
19334                   CONSTRAINT r_guarantee FOREIGN KEY ( guarantee_id ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
19335             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19336         });
19337
19338         $dbh->do(q{
19339             UPDATE borrowers
19340             LEFT JOIN borrowers guarantor ON ( borrowers.guarantorid = guarantor.borrowernumber )
19341             SET borrowers.guarantorid = NULL WHERE guarantor.borrowernumber IS NULL;
19342         });
19343
19344         # Bad data handling: guarantorid IS NOT NULL AND relationship IS NULL
19345         $dbh->do(q{
19346             UPDATE borrowers
19347             SET relationship = '_bad_data'
19348             WHERE guarantorid IS NOT NULL AND
19349                   relationship IS NULL
19350         });
19351
19352         $dbh->do(q{
19353             INSERT INTO borrower_relationships ( guarantor_id, guarantee_id, relationship )
19354             SELECT guarantorid, borrowernumber, relationship FROM borrowers WHERE guarantorid IS NOT NULL;
19355         });
19356
19357         # Clean migrated guarantor data
19358         $dbh->do(q{
19359             UPDATE borrowers
19360             SET contactname=NULL,
19361                 contactfirstname=NULL,
19362                 relationship=NULL
19363             WHERE guarantorid IS NOT NULL
19364         });
19365     }
19366
19367     if ( column_exists( 'borrowers', 'guarantorid' ) ) {
19368         $dbh->do(q{
19369             ALTER TABLE borrowers DROP guarantorid;
19370         });
19371     }
19372
19373     if ( column_exists( 'deletedborrowers', 'guarantorid' ) ) {
19374         $dbh->do(q{
19375             ALTER TABLE deletedborrowers DROP guarantorid;
19376         });
19377     }
19378
19379     if ( column_exists( 'borrower_modifications', 'guarantorid' ) ) {
19380         $dbh->do(q{
19381             ALTER TABLE borrower_modifications DROP guarantorid;
19382         });
19383     }
19384
19385     SetVersion($DBversion);
19386     print "Upgrade to $DBversion done (Bug 14570: Make it possible to add multiple guarantors to a record)\n";
19387 }
19388
19389 $DBversion = '19.06.00.023';
19390 if( CheckVersion( $DBversion ) ) {
19391     $dbh->do(q{
19392         INSERT IGNORE INTO `systempreferences` (`variable`,`value`,`explanation`,`options`,`type`) VALUES
19393         ('ElasticsearchMARCFormat', 'ISO2709', 'ISO2709|ARRAY', 'Elasticsearch MARC format. ISO2709 format is recommended as it is faster and takes less space, whereas array is searchable.', 'Choice')
19394     });
19395
19396     SetVersion( $DBversion );
19397     print "Upgrade to $DBversion done (Bug 22258: Add ElasticsearchMARCFormat preference)\n";
19398 }
19399
19400 $DBversion = '19.06.00.024';
19401 if( CheckVersion( $DBversion ) ) {
19402     $dbh->do(q{ALTER TABLE accountlines CHANGE COLUMN accounttype accounttype varchar(80) default NULL});
19403
19404     SetVersion( $DBversion );
19405     print "Upgrade to $DBversion done (Bug 23539: accountlines.accounttype should match authorised_values.authorised_value in size)\n";
19406 }
19407
19408 $DBversion = '19.06.00.025';
19409 if( CheckVersion( $DBversion ) ) {
19410     $dbh->do( q/INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES (?, ?, ?, ?, ?)/, undef, 'BarcodeSeparators','\s\r\n','','Splitting characters for barcodes','Free' );
19411     SetVersion( $DBversion );
19412     print "Upgrade to $DBversion done (Bug 22996: Add pref BarcodeSeparators)\n";
19413 }
19414
19415 $DBversion = '19.06.00.026';
19416 if( CheckVersion( $DBversion ) ) {
19417
19418     unless ( column_exists( 'borrowers', 'privacy_guarantor_fines' ) ) {
19419         $dbh->do(q{
19420             ALTER TABLE borrowers
19421                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19422         });
19423     }
19424
19425     unless ( column_exists( 'deletedborrowers', 'privacy_guarantor_fines' ) ) {
19426         $dbh->do(q{
19427             ALTER TABLE deletedborrowers
19428                 ADD privacy_guarantor_fines TINYINT(1) NOT NULL DEFAULT '0' AFTER privacy;
19429         });
19430     }
19431
19432     $dbh->do(q{
19433         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type )
19434         VALUES (
19435             'AllowStaffToSetFinesVisibilityForGuarantor',  '0', NULL,
19436             'If enabled, library staff can set a patron''s fines to be visible to linked patrons from the opac.',  'YesNo'
19437         ), (
19438             'AllowPatronToSetFinesVisibilityForGuarantor',  '0', NULL,
19439             'If enabled, the patron can set fines to be visible to  his or her guarantor',  'YesNo'
19440         )
19441     });
19442
19443     SetVersion( $DBversion );
19444     print "Upgrade to $DBversion done (Bug 20691: Add ability for guarantors to view guarantee's fines in OPAC)\n";
19445 }
19446
19447 $DBversion = '19.06.00.027';
19448 if( CheckVersion( $DBversion ) ) {
19449
19450     if( !TableExists( 'itemtypes_branches' ) ) {
19451        $dbh->do( "
19452             CREATE TABLE itemtypes_branches( -- association table between authorised_values and branches
19453                 itemtype VARCHAR(10) NOT NULL,
19454                 branchcode VARCHAR(10) NOT NULL,
19455                 FOREIGN KEY (itemtype) REFERENCES itemtypes(itemtype) ON DELETE CASCADE,
19456                 FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19457             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19458         ");
19459     }
19460
19461     SetVersion( $DBversion );
19462     print "Upgrade to $DBversion done (Bug 15497: Add itemtypes_branches table)\n";
19463 }
19464
19465 $DBversion = '19.06.00.028';
19466 if ( CheckVersion($DBversion) ) {
19467
19468     $dbh->do(qq{
19469         UPDATE
19470           accountlines
19471         SET
19472           accounttype = 'ACCOUNT'
19473         WHERE
19474           accounttype = 'A';
19475     });
19476
19477     SetVersion($DBversion);
19478     print "Upgrade to $DBversion done (Bug 11573: Fix accounttypes for 'A')\n";
19479 }
19480
19481 $DBversion = '19.06.00.029';
19482 if ( CheckVersion($DBversion) ) {
19483
19484     unless ( TableExists( 'cash_registers' ) ) {
19485         $dbh->do(qq{
19486     CREATE TABLE `cash_registers` (
19487     `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register
19488     `name` varchar(24) NOT NULL, -- the user friendly identifier for each account register
19489     `description` longtext NOT NULL, -- the user friendly description for each account register
19490     `branch` varchar(10) NOT NULL, -- the foreign key the library this account register belongs
19491     `branch_default` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote that this till is the branch default
19492     `starting_float` decimal(28, 6), -- the starting float this account register should be assigned
19493     `archived` tinyint(1) NOT NULL DEFAULT 0, -- boolean flag to denote if this till is archived or not
19494     PRIMARY KEY (`id`),
19495     UNIQUE KEY `name` (`name`,`branch`),
19496     CONSTRAINT cash_registers_branch FOREIGN KEY (branch) REFERENCES branches (branchcode) ON UPDATE CASCADE ON DELETE CASCADE
19497     ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
19498         });
19499     }
19500
19501     unless ( column_exists( 'accountlines', 'register_id' ) ) {
19502         $dbh->do(qq{ALTER TABLE `accountlines` ADD `register_id` int(11) NULL DEFAULT NULL AFTER `manager_id`});
19503         $dbh->do(qq{
19504             ALTER TABLE `accountlines`
19505             ADD CONSTRAINT `accountlines_ibfk_registers` FOREIGN KEY (`register_id`)
19506             REFERENCES `cash_registers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
19507         });
19508     }
19509
19510     $dbh->do(qq{
19511         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
19512         VALUES (25, 'cash_management', 'Cash management', 0)
19513     });
19514
19515     $dbh->do(qq{
19516         INSERT IGNORE permissions (module_bit, code, description)
19517         VALUES
19518         (25, 'manage_cash_registers', 'Add and remove cash registers')
19519     });
19520
19521     $dbh->do(qq{
19522         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19523         ('UseCashRegisters','0','','Use cash registers with the accounting system and assign patron transactions to them.','YesNo')
19524     });
19525
19526     SetVersion($DBversion);
19527     print "Upgrade to $DBversion done (Bug 23321: Add cash_registers table, permissions and preferences)\n";
19528 }
19529
19530 $DBversion = '19.06.00.030';
19531 if( CheckVersion( $DBversion ) ) {
19532
19533     if ( !TableExists('club_holds') ) {
19534         $dbh->do(q|
19535             CREATE TABLE club_holds (
19536                 id        INT(11) NOT NULL AUTO_INCREMENT,
19537                 club_id   INT(11) NOT NULL, -- id for the club the hold was generated for
19538                 biblio_id INT(11) NOT NULL, -- id for the bibliographic record the hold has been placed against
19539                 item_id   INT(11) NULL DEFAULT NULL, -- If item-level, the id for the item the hold has been placed agains
19540                 date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Timestamp for the placed hold
19541                 PRIMARY KEY (id),
19542                 -- KEY club_id (club_id),
19543                 CONSTRAINT clubs_holds_ibfk_1 FOREIGN KEY (club_id)   REFERENCES clubs  (id) ON DELETE CASCADE ON UPDATE CASCADE,
19544                 CONSTRAINT clubs_holds_ibfk_2 FOREIGN KEY (biblio_id) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE,
19545                 CONSTRAINT clubs_holds_ibfk_3 FOREIGN KEY (item_id)   REFERENCES items  (itemnumber) ON DELETE CASCADE ON UPDATE CASCADE
19546             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19547         |);
19548     }
19549
19550     if ( !TableExists('club_holds_to_patron_holds') ) {
19551         $dbh->do(q|
19552             CREATE TABLE club_holds_to_patron_holds (
19553                 id              INT(11) NOT NULL AUTO_INCREMENT,
19554                 club_hold_id    INT(11) NOT NULL,
19555                 patron_id       INT(11) NOT NULL,
19556                 hold_id         INT(11),
19557                 error_code      ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
19558                                     'tooManyHoldsForThisRecord', 'tooManyReservesToday',
19559                                     'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
19560                                     'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred'
19561                                 ) NULL DEFAULT NULL,
19562                 error_message   varchar(100) NULL DEFAULT NULL,
19563                 PRIMARY KEY (id),
19564                 -- KEY club_hold_id (club_hold_id),
19565                 CONSTRAINT clubs_holds_paton_holds_ibfk_1 FOREIGN KEY (club_hold_id) REFERENCES club_holds (id) ON DELETE CASCADE ON UPDATE CASCADE,
19566                 CONSTRAINT clubs_holds_paton_holds_ibfk_2 FOREIGN KEY (patron_id) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
19567                 CONSTRAINT clubs_holds_paton_holds_ibfk_3 FOREIGN KEY (hold_id) REFERENCES reserves (reserve_id) ON DELETE CASCADE ON UPDATE CASCADE
19568             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
19569         |);
19570     }
19571
19572     # Always end with this (adjust the bug info)
19573     SetVersion( $DBversion );
19574     print "Upgrade to $DBversion done (Bug 19618: add club_holds tables)\n";
19575 }
19576
19577 $DBversion = '19.06.00.031';
19578 if( CheckVersion( $DBversion ) ) {
19579     $dbh->do(q|
19580         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19581         ('OPACDetailQRCode','0','','Enable the display of a QR Code on the OPAC detail page','YesNo');
19582     |);
19583
19584     SetVersion( $DBversion );
19585     print "Upgrade to $DBversion done (Bug 23566: Add OPACDetailQRCode system preference)\n";
19586 }
19587
19588 $DBversion = '19.06.00.032';
19589 if ( CheckVersion($DBversion) ) {
19590     if ( !column_exists( 'search_marc_to_field', 'search' ) ) {
19591         $dbh->do(q|
19592             ALTER TABLE `search_marc_to_field` ADD COLUMN `search` tinyint(1) NOT NULL DEFAULT 1
19593         |);
19594     }
19595     if ( !column_exists( 'search_field', 'staff_client' ) ) {
19596         $dbh->do(q|
19597             ALTER TABLE `search_field` ADD COLUMN `staff_client` tinyint(1) NOT NULL DEFAULT 1
19598         |);
19599     }
19600     if ( !column_exists( 'search_field', 'opac' ) ) {
19601         $dbh->do(q|
19602             ALTER TABLE `search_field` ADD COLUMN `opac` tinyint(1) NOT NULL DEFAULT 1
19603         |);
19604     }
19605
19606     SetVersion($DBversion);
19607     print
19608 "Upgrade to $DBversion done (Bug 20589: Add field boosting and use elastic query fields parameter instead of depricated _all)\n";
19609 }
19610
19611 $DBversion = '19.06.00.033';
19612 if( CheckVersion( $DBversion ) ) {
19613
19614     $dbh->do(qq{
19615         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19616         ('OnSiteCheckoutAutoCheck','0','','Enable/Do not enable onsite checkout by default if last checkout was an onsite checkout','YesNo')
19617     });
19618     SetVersion( $DBversion );
19619     print "Upgrade to $DBversion done (Bug 23686: Add OnSiteCheckoutAutoCheck system preference)\n";
19620 }
19621
19622 $DBversion = '19.06.00.034';
19623 if( CheckVersion( $DBversion ) ) {
19624     $dbh->do(q{
19625         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
19626         ('TransfersBlockCirc','1',NULL,'Should the transfer modal block circulation staff from continuing scanning items','YesNo')
19627     });
19628     SetVersion( $DBversion );
19629     print "Upgrade to $DBversion done (Bug 23007: Make transfer modals optionally block circ)\n";
19630 }
19631
19632 $DBversion = '19.06.00.035';
19633 if( CheckVersion( $DBversion ) ) {
19634
19635     $dbh->do(q{
19636         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
19637         ( 'IntranetCoce','0', NULL, 'If on, enables cover retrieval from the configured Coce server in the staff client', 'YesNo')
19638     });
19639
19640     $dbh->do(qq{
19641         UPDATE systempreferences SET 
19642           variable = 'OpacCoce', 
19643           explanation = 'If on, enables cover retrieval from the configured Coce server in the OPAC'
19644         WHERE 
19645           variable = 'Coce'
19646     });
19647
19648     SetVersion( $DBversion );
19649     print "Upgrade to $DBversion done (Bug 18421: Add Coce image cache to the Intranet)\n";
19650 }
19651
19652 $DBversion = '19.06.00.036';
19653 if( CheckVersion( $DBversion ) ) {
19654
19655     $dbh->do(q{
19656         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES  
19657         ('QueryRegexEscapeOptions', 'escape', 'dont_escape|escape|unescape_escaped', 'Escape option for regexps delimiters in Elasicsearch queries.', 'Choice')
19658     });
19659
19660     SetVersion( $DBversion );
19661     print "Upgrade to $DBversion done (Bug 20334: Add elasticsearch escape options preference)\n";
19662 }
19663
19664 $DBversion = '19.06.00.037';
19665 if( CheckVersion( $DBversion ) ) {
19666     $dbh->do(q{
19667         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
19668         VALUES ('PayPalReturnURL','BaseURL','BaseURL|OPACAlias','Specify whether PayPal will return to the url specified in the OPACBaseURL option or to the OPAC\'s alias url.','Choice')
19669     });
19670
19671     SetVersion( $DBversion );
19672     print "Upgrade to $DBversion done (Bug 21701: PayPal return URL option)\n";
19673 }
19674
19675 $DBversion = '19.06.00.038';
19676 if( CheckVersion( $DBversion ) ) {
19677     $dbh->do( "UPDATE systempreferences SET variable='PatronAutoComplete' WHERE variable='CircAutocompl' LIMIT 1" );
19678     SetVersion( $DBversion );
19679     print "Upgrade to $DBversion done (Bug 23697: Rename CircAutocompl system preference to PatronAutoComplete)\n";
19680 }
19681
19682 $DBversion = '19.06.00.039';
19683 if( CheckVersion( $DBversion ) ) {
19684     $dbh->do(q|
19685         INSERT IGNORE INTO keyboard_shortcuts (shortcut_name, shortcut_keys) VALUES
19686         ("copy_line","Ctrl-C"),
19687         ("copy_subfield","Shift-Ctrl-C"),
19688         ("paste_line","Ctrl-P"),
19689         ("insert_line","Ctrl-I")
19690         ;
19691     |);
19692     SetVersion( $DBversion );
19693     print "Upgrade to $DBversion done (Bug 17179: Add additional keyboard_shortcuts)\n";
19694 }
19695
19696 $DBversion = '19.06.00.040';
19697 if( CheckVersion( $DBversion ) ) {
19698     $dbh->do(q|
19699         INSERT IGNORE INTO systempreferences
19700         (variable,value,explanation,options,type)
19701         VALUES
19702         ('RoundFinesAtPayment','0','If enabled any fines with fractions of a cent will be rounded to the nearest cent when payments are collected. e.g. 1.004 will be paid off by a 1.00 payment','0','YesNo')
19703     |);
19704
19705     SetVersion( $DBversion );
19706     print "Upgrade to $DBversion done (Bug 17140: Add pref to allow rounding fines at payment)\n";
19707 }
19708
19709 $DBversion = '19.06.00.041';
19710 if( CheckVersion( $DBversion ) ) {
19711     my ($socialnetworks) = $dbh->selectrow_array( q|
19712         SELECT value FROM systempreferences WHERE variable='socialnetworks';
19713     |);
19714     if( $socialnetworks ){
19715         # If the socialnetworks preference is enabled, enable all social networks
19716         $dbh->do("UPDATE systempreferences SET value = 'email,facebook,linkedin,twitter', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19717     } else {
19718         $dbh->do("UPDATE systempreferences SET value = '', explanation = 'email|facebook|linkedin|twitter', type = 'multiple'  WHERE variable = 'SocialNetworks'");
19719     }
19720     SetVersion ($DBversion);
19721     print "Upgrade to $DBversion done (Bug 22880: Allow granular control of socialnetworks preference)\n";
19722 }
19723
19724 $DBversion = '19.06.00.042';
19725 if( CheckVersion( $DBversion ) ) {
19726     $dbh->do(q{
19727         INSERT IGNORE INTO systempreferences
19728             ( variable, value, options, explanation, type )
19729         VALUES
19730             ('CustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed in the staff client. CustomCoverImagesURL must be defined.','YesNo'),
19731             ('OPACCustomCoverImages','0',NULL,'If enabled, the custom cover images will be displayed at the OPAC. CustomCoverImagesURL must be defined.','YesNo'),
19732             ('CustomCoverImagesURL','',NULL,'Define an URL serving book cover images, using the following patterns: {issn}, {isbn}, {normalized_isbn}, {field$subfield} (use it with CustomCoverImages and/or OPACCustomCoverImages)','free')
19733     });
19734
19735     SetVersion( $DBversion );
19736     print "Upgrade to $DBversion done (Bug 22445: Add new pref *CustomCoverImages*)\n";
19737 }
19738
19739 $DBversion = '19.06.00.043';
19740 if ( CheckVersion($DBversion) ) {
19741
19742     # Adding account_debit_types
19743     if ( !TableExists('account_debit_types') ) {
19744         $dbh->do(
19745             qq{
19746                 CREATE TABLE account_debit_types (
19747                   code varchar(80) NOT NULL,
19748                   description varchar(200) NULL,
19749                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19750                   default_amount decimal(28, 6) NULL,
19751                   is_system tinyint(1) NOT NULL DEFAULT 0,
19752                   archived tinyint(1) NOT NULL DEFAULT 0,
19753                   PRIMARY KEY (code)
19754                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19755               }
19756         );
19757     }
19758
19759     # Adding account_debit_types_branches
19760     if ( !TableExists('account_debit_types_branches') ) {
19761         $dbh->do(
19762             qq{
19763                 CREATE TABLE account_debit_types_branches (
19764                     debit_type_code VARCHAR(80),
19765                     branchcode VARCHAR(10),
19766                     FOREIGN KEY (debit_type_code) REFERENCES account_debit_types(code) ON DELETE CASCADE,
19767                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19768                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19769             }
19770         );
19771     }
19772
19773     # Populating account_debit_types
19774     $dbh->do(
19775         qq{
19776             INSERT IGNORE INTO account_debit_types (
19777               code,
19778               description,
19779               can_be_added_manually,
19780               default_amount,
19781               is_system
19782             )
19783             VALUES
19784               ('ACCOUNT', 'Account creation fee', 0, NULL, 1),
19785               ('ACCOUNT_RENEW', 'Account renewal fee', 0, NULL, 1),
19786               ('RESERVE_EXPIRED', 'Hold waiting too long', 0, NULL, 1),
19787               ('LOST', 'Lost item', 1, NULL, 1),
19788               ('MANUAL', 'Manual fee', 1, NULL, 0),
19789               ('NEW_CARD', 'New card fee', 1, NULL, 1),
19790               ('OVERDUE', 'Overdue fine', 0, NULL, 1),
19791               ('PROCESSING', 'Lost item processing fee', 0, NULL, 1),
19792               ('RENT', 'Rental fee', 0, NULL, 1),
19793               ('RENT_DAILY', 'Daily rental fee', 0, NULL, 1),
19794               ('RENT_RENEW', 'Renewal of rental item', 0, NULL, 1),
19795               ('RENT_DAILY_RENEW', 'Renewal of daily rental item', 0, NULL, 1),
19796               ('RESERVE', 'Hold fee', 0, NULL, 1)
19797         }
19798     );
19799
19800     # Update accountype 'Res' to 'RESERVE'
19801     $dbh->do(
19802         qq{
19803           UPDATE accountlines SET accounttype = 'RESERVE' WHERE accounttype = 'Res'
19804         }
19805     );
19806
19807     # Update accountype 'PF' to 'PROCESSING'
19808     $dbh->do(
19809         qq{
19810           UPDATE accountlines SET accounttype = 'PROCESSING' WHERE accounttype = 'PF'
19811         }
19812     );
19813
19814     # Update accountype 'HE' to 'RESERVE_EXPIRED'
19815     $dbh->do(
19816         qq{
19817           UPDATE accountlines SET accounttype = 'RESERVE_EXPIRED' WHERE accounttype = 'HE'
19818         }
19819     );
19820
19821     # Update accountype 'N' to 'NEW_CARD'
19822     $dbh->do(
19823         qq{
19824           UPDATE accountlines SET accounttype = 'NEW_CARD' WHERE accounttype = 'N'
19825         }
19826     );
19827
19828     # Update accountype 'M' to 'MANUAL'
19829     $dbh->do(
19830         qq{
19831           UPDATE accountlines SET accounttype = 'MANUAL' WHERE accounttype = 'M'
19832         }
19833     );
19834
19835     # Catch 'F' cases introduced since bug 22521
19836     $dbh->do(qq{
19837         UPDATE
19838           accountlines
19839         SET
19840           accounttype = 'OVERDUE',
19841           status = 'RETURNED'
19842         WHERE
19843           accounttype = 'F';
19844     });
19845
19846     # Moving MANUAL_INV to account_debit_types
19847     $dbh->do(
19848         qq{
19849             INSERT IGNORE INTO account_debit_types (
19850               code,
19851               default_amount,
19852               description,
19853               can_be_added_manually,
19854               is_system
19855             )
19856             SELECT
19857               authorised_value,
19858               lib,
19859               authorised_value,
19860               1,
19861               0
19862             FROM
19863               authorised_values
19864             WHERE
19865               category = 'MANUAL_INV'
19866           }
19867     );
19868
19869     # Update uncaught partial accounttypes left behind after bugs 23539 and 22521
19870     my $sth = $dbh->prepare( "SELECT code, SUBSTR(code, 1,5) AS subcode FROM account_debit_types" );
19871     $sth->execute();
19872     while ( my $row = $sth->fetchrow_hashref ) {
19873         $dbh->do(
19874             qq{
19875               UPDATE accountlines SET accounttype = ? WHERE accounttype = ?
19876             },
19877             {},
19878             (
19879                 $row->{code},
19880                 $row->{subcode}
19881             )
19882         );
19883     }
19884
19885     # Add any unexpected accounttype codes to debit_types as appropriate
19886     $dbh->do(
19887         qq{
19888           INSERT IGNORE INTO account_debit_types (
19889             code,
19890             description,
19891             can_be_added_manually,
19892             default_amount,
19893             is_system
19894           )
19895           SELECT
19896             DISTINCT(accounttype),
19897             "Unexpected type found during upgrade",
19898             1,
19899             NULL,
19900             0
19901           FROM
19902             accountlines
19903           WHERE
19904             amount >= 0
19905         }
19906     );
19907
19908     # Adding debit_type_code to accountlines
19909     unless ( column_exists('accountlines', 'debit_type_code') ) {
19910         $dbh->do(
19911             qq{
19912                 ALTER TABLE accountlines
19913                 ADD
19914                   debit_type_code varchar(80) DEFAULT NULL
19915                 AFTER
19916                   accounttype
19917               }
19918         );
19919     }
19920
19921     # Linking debit_type_code in accountlines to code in account_debit_types
19922     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_debit_type' ) ) {
19923         $dbh->do(
19924             qq{
19925             ALTER TABLE accountlines ADD CONSTRAINT `accountlines_ibfk_debit_type` FOREIGN KEY (`debit_type_code`) REFERENCES `account_debit_types` (`code`) ON DELETE RESTRICT ON UPDATE CASCADE
19926               }
19927         );
19928     }
19929
19930     # Populating debit_type_code
19931     $dbh->do(
19932         qq{
19933         UPDATE accountlines SET debit_type_code = accounttype, accounttype = NULL WHERE accounttype IN (SELECT code from account_debit_types) AND amount >= 0
19934         }
19935     );
19936
19937     # Remove MANUAL_INV
19938     $dbh->do(
19939         qq{
19940         DELETE FROM authorised_values WHERE category = 'MANUAL_INV'
19941         }
19942     );
19943     $dbh->do(
19944         qq{
19945         DELETE FROM authorised_value_categories WHERE category_name = 'MANUAL_INV'
19946         }
19947     );
19948
19949     # Add new permission
19950     $dbh->do(
19951         q{
19952             INSERT IGNORE INTO permissions (module_bit, code, description)
19953             VALUES
19954               (
19955                 3,
19956                 'manage_accounts',
19957                 'Manage Account Debit and Credit Types'
19958               )
19959         }
19960     );
19961
19962     SetVersion($DBversion);
19963     print "Upgrade to $DBversion done (Bug 23049: Add account debit_types)\n";
19964 }
19965
19966 $DBversion = '19.06.00.044';
19967 if ( CheckVersion($DBversion) ) {
19968
19969     # Adding account_credit_types
19970     if ( !TableExists('account_credit_types') ) {
19971         $dbh->do(
19972             qq{
19973                 CREATE TABLE account_credit_types (
19974                   code varchar(80) NOT NULL,
19975                   description varchar(200) NULL,
19976                   can_be_added_manually tinyint(4) NOT NULL DEFAULT 1,
19977                   is_system tinyint(1) NOT NULL DEFAULT 0,
19978                   PRIMARY KEY (code)
19979                 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
19980               }
19981         );
19982     }
19983
19984     # Adding account_credit_types_branches
19985     if ( !TableExists('account_credit_types_branches') ) {
19986         $dbh->do(
19987             qq{
19988                 CREATE TABLE account_credit_types_branches (
19989                     credit_type_code VARCHAR(80),
19990                     branchcode VARCHAR(10),
19991                     FOREIGN KEY (credit_type_code) REFERENCES account_credit_types(code) ON DELETE CASCADE,
19992                     FOREIGN KEY (branchcode) REFERENCES branches(branchcode) ON DELETE CASCADE
19993                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
19994             }
19995         );
19996     }
19997
19998     # Populating account_credit_types
19999     $dbh->do(
20000         qq{
20001             INSERT IGNORE INTO account_credit_types (
20002               code,
20003               description,
20004               can_be_added_manually,
20005               is_system
20006             )
20007             VALUES
20008               ('PAYMENT', 'Payment', 0, 1),
20009               ('WRITEOFF', 'Writeoff', 0, 1),
20010               ('FORGIVEN', 'Forgiven', 1, 1),
20011               ('CREDIT', 'Credit', 1, 1),
20012               ('LOST_RETURN', 'Lost item fee refund', 0, 1)
20013         }
20014     );
20015
20016     # Adding credit_type_code to accountlines
20017     unless ( column_exists('accountlines', 'credit_type_code') ) {
20018         $dbh->do(
20019             qq{
20020                 ALTER TABLE accountlines
20021                 ADD
20022                   credit_type_code varchar(80) DEFAULT NULL
20023                 AFTER
20024                   accounttype
20025               }
20026         );
20027     }
20028
20029     # Catch LOST_RETURNED cases from original bug 22563 update
20030     $dbh->do(
20031         qq{
20032             UPDATE accountlines
20033             SET accounttype = 'LOST_RETURN'
20034             WHERE accounttype = 'LOST_RETURNED'
20035     });
20036
20037     # Linking credit_type_code in accountlines to code in account_credit_types
20038     unless ( foreign_key_exists( 'accountlines', 'accountlines_ibfk_credit_type' ) ) {
20039         $dbh->do(
20040             qq{
20041                 ALTER TABLE accountlines
20042                 ADD CONSTRAINT
20043                   `accountlines_ibfk_credit_type`
20044                 FOREIGN KEY (`credit_type_code`) REFERENCES `account_credit_types` (`code`)
20045                 ON DELETE RESTRICT
20046                 ON UPDATE CASCADE
20047               }
20048         );
20049     }
20050
20051     # Update accountype 'C' to 'CREDIT'
20052     $dbh->do(
20053         qq{
20054           UPDATE accountlines SET accounttype = 'CREDIT' WHERE accounttype = 'C' OR accounttype = 'CR'
20055         }
20056     );
20057
20058     # Update accountype 'FOR' to 'FORGIVEN'
20059     $dbh->do(
20060         qq{
20061           UPDATE accountlines SET accounttype = 'FORGIVEN' WHERE accounttype = 'FOR' OR accounttype = 'FORW'
20062         }
20063     );
20064
20065     # Update accountype 'Pay' to 'PAYMENT'
20066     $dbh->do(
20067         qq{
20068           UPDATE accountlines SET accounttype = 'PAYMENT' WHERE accounttype = 'Pay' OR accounttype = 'PAY'
20069         }
20070     );
20071
20072     # Update accountype 'W' to 'WRITEOFF'
20073     $dbh->do(
20074         qq{
20075           UPDATE accountlines SET accounttype = 'WRITEOFF' WHERE accounttype = 'W' OR accounttype = 'WO'
20076         }
20077     );
20078
20079     # Add any unexpected accounttype codes to credit_types as appropriate
20080     $dbh->do(
20081         qq{
20082           INSERT IGNORE INTO account_credit_types (
20083             code,
20084             description,
20085             can_be_added_manually,
20086             is_system
20087           )
20088           SELECT
20089             DISTINCT(accounttype),
20090             "Unexpected type found during upgrade",
20091             1,
20092             0
20093           FROM
20094             accountlines
20095           WHERE
20096             amount < 0
20097         }
20098     );
20099
20100     # Populating credit_type_code
20101     $dbh->do(
20102         qq{
20103           UPDATE
20104             accountlines 
20105           SET
20106             credit_type_code = accounttype, accounttype = NULL
20107           WHERE accounttype IN (SELECT code from account_credit_types)
20108         }
20109     );
20110
20111     # Drop accounttype field
20112     $dbh->do(
20113         qq{
20114           ALTER TABLE accountlines
20115           DROP COLUMN `accounttype`
20116         }
20117     );
20118
20119     SetVersion($DBversion);
20120     print "Upgrade to $DBversion done (Bug 23805: Add account credit_types)\n";
20121 }
20122
20123 $DBversion = '19.06.00.045';
20124 if( CheckVersion( $DBversion ) ) {
20125     $dbh->do( "UPDATE systempreferences SET value = '2' WHERE value = '0' AND variable = 'UsageStats'" );
20126
20127     SetVersion( $DBversion );
20128     print "Upgrade to $DBversion done (Bug 23866: Set HEA syspref to prompt for review)\n";
20129 }
20130
20131 $DBversion = '19.06.00.046';
20132 if( CheckVersion( $DBversion ) ) {
20133     $dbh->do(qq{
20134         UPDATE systempreferences
20135         SET 
20136           options = "Calendar|Days|Datedue|Dayweek", 
20137           explanation = "Choose the method for calculating due date: select Calendar, Datedue or Dayweek to use the holidays module, and Days to ignore the holidays module"
20138         WHERE
20139           variable = "useDaysMode"
20140     });
20141
20142     # Always end with this (adjust the bug info)
20143     SetVersion( $DBversion );
20144     print "Upgrade to $DBversion done (Bug 15260: Option for extended loan with useDaysMode)\n";
20145 }
20146
20147 $DBversion = '19.06.00.047';
20148 if ( CheckVersion($DBversion) ) {
20149     if ( !TableExists('return_claims') ) {
20150         $dbh->do(
20151             q{
20152             CREATE TABLE return_claims (
20153                 id int(11) auto_increment,                             -- Unique ID of the return claim
20154                 itemnumber int(11) NOT NULL,                           -- ID of the item
20155                 issue_id int(11) NULL DEFAULT NULL,                    -- ID of the checkout that triggered the claim
20156                 borrowernumber int(11) NOT NULL,                       -- ID of the patron
20157                 notes MEDIUMTEXT DEFAULT NULL,                         -- Notes about the claim
20158                 created_on TIMESTAMP NULL,                             -- Time and date the claim was created
20159                 created_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that registered the claim
20160                 updated_on TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP, -- Time and date of the latest change on the claim (notes)
20161                 updated_by int(11) NULL DEFAULT NULL,                  -- ID of the staff member that updated the claim
20162                 resolution  varchar(80) NULL DEFAULT NULL,             -- Resolution code (RETURN_CLAIM_RESOLUTION AVs)
20163                 resolved_on TIMESTAMP NULL DEFAULT NULL,               -- Time and date the claim was resolved
20164                 resolved_by int(11) NULL DEFAULT NULL,                 -- ID of the staff member that resolved the claim
20165                 PRIMARY KEY (`id`),
20166                 KEY `itemnumber` (`itemnumber`),
20167                 CONSTRAINT UNIQUE `issue_id` ( issue_id ),
20168                 CONSTRAINT `issue_id` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`issue_id`) ON DELETE SET NULL ON UPDATE CASCADE,
20169                 CONSTRAINT `rc_items_ibfk` FOREIGN KEY (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20170                 CONSTRAINT `rc_borrowers_ibfk` FOREIGN KEY (`borrowernumber`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
20171                 CONSTRAINT `rc_created_by_ibfk` FOREIGN KEY (`created_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20172                 CONSTRAINT `rc_updated_by_ibfk` FOREIGN KEY (`updated_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE,
20173                 CONSTRAINT `rc_resolved_by_ibfk` FOREIGN KEY (`resolved_by`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
20174             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
20175         }
20176         );
20177     }
20178
20179     $dbh->do(
20180         q{
20181         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
20182         ('ClaimReturnedChargeFee', 'ask', 'ask|charge|no_charge', 'Controls whether or not a lost item fee is charged for return claims', 'Choice'),
20183         ('ClaimReturnedLostValue', '', '', 'Sets the LOST AV value that represents "Claims returned" as a lost value', 'Free'),
20184         ('ClaimReturnedWarningThreshold', '', '', 'Sets the number of return claims past which the librarian will be warned the patron has many return claims', 'Integer');
20185     }
20186     );
20187
20188     $dbh->do(
20189         q{
20190         INSERT IGNORE INTO authorised_value_categories ( category_name ) VALUES
20191             ('RETURN_CLAIM_RESOLUTION');
20192     }
20193     );
20194
20195     $dbh->do(
20196         q{
20197         INSERT IGNORE INTO `authorised_values` ( category, authorised_value, lib )
20198         VALUES
20199           ('RETURN_CLAIM_RESOLUTION', 'RET_BY_PATRON', 'Returned by patron'),
20200           ('RETURN_CLAIM_RESOLUTION', 'FOUND_IN_LIB', 'Found in library');
20201     }
20202     );
20203
20204     SetVersion($DBversion);
20205     print
20206 "Upgrade to $DBversion done (Bug 14697: Extend and enhance 'Claims returned' lost status)\n";
20207 }
20208
20209 $DBversion = '19.06.00.048';
20210 if( CheckVersion( $DBversion ) ) {
20211     # you can use $dbh here like:
20212     $dbh->do( qq{
20213         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
20214         VALUES  ('OPACShowMusicalInscripts','0','','Display musical inscripts on the OPAC record details page when available.','YesNo'),
20215                 ('OPACPlayMusicalInscripts','0','','If displayed musical inscripts, play midi conversion on the OPAC record details page.','YesNo')
20216     } );
20217
20218     SetVersion( $DBversion );
20219     print "Upgrade to $DBversion done (Bug 22581: add new OPACShowMusicalInscripts and OPACPlayMusicalInscripts system preferences)\n";
20220 }
20221
20222 $DBversion = '19.06.00.049';
20223 if( CheckVersion( $DBversion ) ) {
20224
20225     $dbh->do(q{
20226         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20227         SELECT
20228             'SuspensionsCalendar',
20229             IF( value='noFinesWhenClosed', 'noSuspensionsWhenClosed', 'ignoreCalendar'),
20230             'ignoreCalendar|noSuspensionsWhenClosed',
20231             'Specify whether to use the Calendar in calculating suspensions',
20232             'Choice'
20233         FROM systempreferences
20234         WHERE variable='finesCalendar';
20235     });
20236
20237     SetVersion( $DBversion );
20238     print "Upgrade to $DBversion done (Bug 13958: Add a SuspensionsCalendar syspref)\n";
20239 }
20240
20241 $DBversion = '19.06.00.050';
20242 if( CheckVersion( $DBversion ) ) {
20243     $dbh->do( q{
20244             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20245             VALUES ('OPACFineNoRenewalsIncludeCredits','1',NULL,'If enabled the value specified in OPACFineNoRenewals should include any unapplied account credits in the calculation','YesNo')
20246     });
20247
20248     SetVersion( $DBversion );
20249     print "Upgrade to $DBversion done (Bug 23293: Add 'OPACFineNoRenewalsIncludeCredits' system preference)\n";
20250 }
20251
20252 $DBversion = '19.11.00.000';
20253 if( CheckVersion( $DBversion ) ) {
20254     NewVersion( $DBversion, undef, '19.11.00 release' );
20255 }
20256
20257 $DBversion = '19.12.00.000';
20258 if( CheckVersion( $DBversion ) ) {
20259     NewVersion( $DBversion, undef, 'Dobbie is a free elf...' );
20260 }
20261
20262 $DBversion = '19.12.00.001';
20263 if( CheckVersion( $DBversion ) ) {
20264     $dbh->do( "UPDATE marc_subfield_structure SET kohafield = NULL WHERE kohafield = 'bibliosubject.subject';" );
20265     NewVersion( $DBversion, 17831, 'Remove non-existing bibliosubject.subject from frameworks' );
20266 }
20267
20268 $DBversion = '19.12.00.002';
20269 if( CheckVersion( $DBversion ) ) {
20270     $dbh->do(q{
20271         UPDATE systempreferences SET
20272         variable = 'AllowItemsOnHoldCheckoutSIP',
20273         explanation = 'Do not generate RESERVE_WAITING and RESERVED warning when checking out items reserved to someone else via SIP. This allows self checkouts for those items.'
20274         WHERE variable = 'AllowItemsOnHoldCheckout'
20275     });
20276
20277     NewVersion( $DBversion, 23233, 'Rename AllowItemsOnHoldCheckout syspref' );
20278 }
20279
20280 $DBversion = '19.12.00.003';
20281 if( CheckVersion( $DBversion ) ) {
20282
20283     if( !column_exists( 'library_groups', 'ft_local_hold_group' ) ) {
20284         $dbh->do( "ALTER TABLE library_groups ADD COLUMN ft_local_hold_group tinyint(1) NOT NULL DEFAULT 0 AFTER ft_search_groups_staff" );
20285     }
20286
20287     NewVersion( $DBversion, 22284, 'Add ft_local_hold_group column to library_groups' );
20288 }
20289
20290 $DBversion = '19.12.00.004';
20291 if ( CheckVersion($DBversion) ) {
20292
20293     $dbh->do(
20294         qq{
20295             INSERT IGNORE INTO account_debit_types (
20296               code,
20297               description,
20298               can_be_added_manually,
20299               default_amount,
20300               is_system
20301             )
20302             VALUES
20303               ('PAYOUT', 'Payment from library to patron', 0, NULL, 1)
20304         }
20305     );
20306
20307     $dbh->do(qq{
20308         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('PAYOUT');
20309     });
20310
20311     $dbh->do(qq{
20312         INSERT IGNORE permissions (module_bit, code, description)
20313         VALUES
20314         (10, 'payout', 'Perform account payout action')
20315     });
20316
20317     NewVersion( $DBversion, 24080, ['Add PAYOUT account_debit_type', 'Add PAYOUT account_offset_type', 'Add accounts payout permission'] );
20318 }
20319
20320 $DBversion = '19.12.00.005';
20321 if( CheckVersion( $DBversion ) ) {
20322     $dbh->do( "ALTER TABLE action_logs MODIFY COLUMN `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP" );
20323
20324     NewVersion( $DBversion, 24329, 'Do not update action_log.timestamp' );
20325 }
20326
20327 $DBversion = '19.12.00.006';
20328 if( CheckVersion( $DBversion ) ) {
20329     $dbh->do( q|
20330         UPDATE borrowers SET relationship = NULL
20331         WHERE relationship = ""
20332     |);
20333
20334     NewVersion( $DBversion, 24263, 'Replace relationship with NULL when empty string' );
20335 }
20336
20337 $DBversion = '19.12.00.007';
20338 if ( CheckVersion($DBversion) ) {
20339
20340     $dbh->do(
20341         qq{
20342             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
20343             VALUES
20344               ('REFUND', 'A refund applied to a patrons fine', 0, 1)
20345         }
20346     );
20347
20348     $dbh->do(qq{
20349         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('REFUND');
20350     });
20351
20352     $dbh->do(qq{
20353         INSERT IGNORE permissions (module_bit, code, description)
20354         VALUES
20355         (10, 'refund', 'Perform account refund action')
20356     });
20357
20358     NewVersion( $DBversion, 23442, ['Add REFUND to account_credit_types', 'Add REFUND to account_offset_types', 'Add accounts refund permission'] );
20359 }
20360
20361 $DBversion = '19.12.00.008';
20362 if( CheckVersion( $DBversion ) ) {
20363     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://worldcat.org", "https://worldcat.org") WHERE variable = "OPACSearchForTitleIn"' );
20364     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "http://www.bookfinder.com", "https://www.bookfinder.com") WHERE variable = "OPACSearchForTitleIn"' );
20365     $dbh->do( 'UPDATE systempreferences SET value = REPLACE(value, "https://openlibrary.org/search/?", "https://openlibrary.org/search?") WHERE variable = "OPACSearchForTitleIn"' );
20366
20367     NewVersion( $DBversion, 24206, 'Update OpacSearchForTitleIn system preference' );
20368 }
20369
20370 $DBversion = '19.12.00.009';
20371 if( CheckVersion( $DBversion ) ) {
20372
20373     $dbh->do(q{
20374         INSERT IGNORE INTO account_offset_types ( type ) VALUES ( 'Purchase' );
20375     });
20376
20377     $dbh->do(q{
20378         INSERT IGNORE INTO account_credit_types ( code, description, can_be_added_manually, is_system )
20379         VALUES ('PURCHASE', 'Purchase', 0, 1);
20380     });
20381
20382     my $sth = $dbh->prepare(q{
20383         SELECT COUNT(*) FROM authorised_values WHERE category = 'PAYMENT_TYPE' AND authorised_value = 'CASH'
20384     });
20385     $sth->execute;
20386     my $already_exists = $sth->fetchrow;
20387     if ( not $already_exists ) {
20388         $dbh->do(q{
20389            INSERT INTO authorised_values (category,authorised_value,lib) VALUES ('PAYMENT_TYPE','CASH','Cash')
20390         });
20391     }
20392
20393     # Updating field in account_debit_types
20394     unless ( column_exists('account_debit_types', 'can_be_invoiced') ) {
20395         $dbh->do(
20396             qq{
20397                 ALTER TABLE account_debit_types
20398                 CHANGE COLUMN
20399                   can_be_added_manually can_be_invoiced tinyint(1) NOT NULL DEFAULT 1
20400               }
20401         );
20402     }
20403     unless ( column_exists('account_debit_types', 'can_be_sold') ) {
20404         $dbh->do(
20405             qq{
20406                 ALTER TABLE account_debit_types
20407                 ADD
20408                   can_be_sold tinyint(1) DEFAULT 0
20409                 AFTER
20410                   can_be_invoiced
20411               }
20412         );
20413     }
20414
20415     $dbh->do(q{
20416 INSERT IGNORE INTO `letter` (`module`, `code`, `branchcode`, `name`, `is_html`, `title`, `content`, `message_transport_type`, `lang`) VALUES
20417 ('pos', 'RECEIPT', '', 'Point of sale receipt', 0, 'Receipt', '[% PROCESS "accounts.inc" %]
20418 <table>
20419 [% IF ( LibraryName ) %]
20420  <tr>
20421     <th colspan="2" class="centerednames">
20422         <h3>[% LibraryName | html %]</h3>
20423     </th>
20424  </tr>
20425 [% END %]
20426  <tr>
20427     <th colspan="2" class="centerednames">
20428         <h2>[% Branches.GetName( payment.branchcode ) | html %]</h2>
20429     </th>
20430  </tr>
20431 <tr>
20432     <th colspan="2" class="centerednames">
20433         <h3>[% payment.date | $KohaDates %]</h3>
20434 </tr>
20435 <tr>
20436   <td>Transaction ID: </td>
20437   <td>[% payment.accountlines_id %]</td>
20438 </tr>
20439 <tr>
20440   <td>Operator ID: </td>
20441   <td>[% payment.manager_id %]</td>
20442 </tr>
20443 <tr>
20444   <td>Payment type: </td>
20445   <td>[% payment.payment_type %]</td>
20446 </tr>
20447  <tr></tr>
20448  <tr>
20449     <th colspan="2" class="centerednames">
20450         <h2><u>Fee receipt</u></h2>
20451     </th>
20452  </tr>
20453  <tr></tr>
20454  <tr>
20455     <th>Description of charges</th>
20456     <th>Amount</th>
20457   </tr>
20458
20459   [% FOREACH offset IN offsets %]
20460     <tr>
20461         <td>[% PROCESS account_type_description account=offset.debit %]</td>
20462         <td>[% offset.amount * -1 | $Price %]</td>
20463     </tr>
20464   [% END %]
20465
20466 <tfoot>
20467   <tr class="highlight">
20468     <td>Total: </td>
20469     <td>[% payment.amount * -1| $Price %]</td>
20470   </tr>
20471   <tr>
20472     <td>Tendered: </td>
20473     <td>[% collected | $Price %]</td>
20474   </tr>
20475   <tr>
20476     <td>Change: </td>
20477     <td>[% change | $Price %]</td>
20478     </tr>
20479 </tfoot>
20480 </table>', 'print', 'default');
20481     });
20482
20483     $dbh->do(qq{
20484         INSERT IGNORE permissions (module_bit, code, description)
20485         VALUES
20486         (25, 'takepayment', 'Access the point of sale page and take payments')
20487     });
20488
20489     NewVersion( $DBversion, 23354, [q|Add 'Purchase' account offset type|, q|Add 'RECEIPT' notice for Point of Sale|, q|Add point of sale permissions|] );
20490 }
20491
20492 $DBversion = '19.12.00.010';
20493 if( CheckVersion( $DBversion ) ) {
20494     if( !column_exists( 'oai_sets_mappings', 'rule_order' ) ) {
20495         $dbh->do( "ALTER TABLE oai_sets_mappings ADD COLUMN rule_order INT AFTER set_id, ADD COLUMN rule_operator VARCHAR(3) AFTER rule_order" );
20496         $dbh->do( "UPDATE oai_sets_mappings SET rule_operator='or'" );
20497         my $sets = $dbh->selectall_arrayref("SELECT * from oai_sets_mappings ORDER BY set_id", { Slice => {} });
20498         my $i = 0;
20499         my $previous_set_id;
20500         for my $set ( @{$sets}) {
20501             my $set_id = $set->{set_id};
20502     
20503             if ($previous_set_id && $previous_set_id != $set_id) {
20504                 $i = 0;
20505             }
20506     
20507             if ($i == 0) {
20508                 $dbh->do("UPDATE oai_sets_mappings SET rule_operator=NULL WHERE set_id=? LIMIT 1", {}, $set_id);
20509             }
20510     
20511             $dbh->do("UPDATE oai_sets_mappings SET rule_order=? WHERE set_id=? AND rule_order IS NULL LIMIT 1", {}, $i, $set_id);
20512     
20513             $i++;
20514             $previous_set_id = $set_id;
20515         }
20516     }
20517
20518     NewVersion( $DBversion, 21520, 'Add rule_order and rule_operator fields to oai_sets_mappings table' );
20519 }
20520
20521 $DBversion = '19.12.00.011';
20522 if( CheckVersion( $DBversion ) ) {
20523     if( !foreign_key_exists( 'repeatable_holidays', 'repeatable_holidays_ibfk_1' ) ) {
20524         $dbh->do(q|
20525             DELETE h
20526             FROM repeatable_holidays h
20527             LEFT JOIN branches b ON h.branchcode=b.branchcode
20528             WHERE b.branchcode IS NULL;
20529         |);
20530         $dbh->do(q|
20531             ALTER TABLE repeatable_holidays
20532             ADD FOREIGN KEY repeatable_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20533         |);
20534     }
20535
20536     if( !foreign_key_exists( 'special_holidays', 'special_holidays_ibfk_1' ) ) {
20537         $dbh->do(q|
20538             DELETE h
20539             FROM special_holidays h
20540             LEFT JOIN branches b ON h.branchcode=b.branchcode
20541             WHERE b.branchcode IS NULL;
20542         |);
20543         $dbh->do(q|
20544             ALTER TABLE special_holidays
20545             ADD FOREIGN KEY special_holidays_ibfk_1 (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
20546         |);
20547     }
20548
20549     NewVersion( $DBversion, 24289, 'Adding foreign keys on *_holidays.branchcode tables' );
20550 }
20551
20552 $DBversion = '19.12.00.012';
20553 if( CheckVersion( $DBversion ) ) {
20554
20555     $dbh->do(qq{
20556         UPDATE
20557           `permissions`
20558         SET
20559           `module_bit` = 3
20560         WHERE
20561           `code` = 'manage_cash_registers'
20562     });
20563
20564     NewVersion( $DBversion, 24481, 'Move permission to correct module_bit' );
20565 }
20566
20567 $DBversion = '19.12.00.013';
20568 if( CheckVersion( $DBversion ) ) {
20569     $dbh->do(qq{
20570         INSERT IGNORE INTO 
20571           systempreferences (variable,value,options,explanation,type)
20572         VALUES
20573           ('EnablePointOfSale','0',NULL,'Enable the point of sale feature to allow anonymous transactions with the accounting system. (Requires UseCashRegisters)','YesNo')
20574     });
20575
20576     NewVersion( $DBversion, 24478, 'Add `EnablePointOfSale` system preference to allow disabling the point of sale feature)' );
20577 }
20578
20579 $DBversion = '19.12.00.014';
20580 if( CheckVersion( $DBversion ) ) {
20581     unless ( column_exists('branchtransfers', 'reason') ) {
20582         $dbh->do(
20583             qq{
20584                 ALTER TABLE branchtransfers
20585                 ADD
20586                   `reason` enum('Manual')
20587                 AFTER
20588                   comments
20589               }
20590         );
20591     }
20592
20593     NewVersion( $DBversion, 24287, q|Add 'reason' field to transfers table| );
20594 }
20595
20596 $DBversion = '19.12.00.015';
20597 if( CheckVersion( $DBversion ) ) {
20598
20599     # Add stockrotation states to reason enum
20600     $dbh->do(
20601         qq{
20602             ALTER TABLE
20603                 `branchtransfers`
20604             MODIFY COLUMN
20605                 `reason` enum(
20606                     'Manual',
20607                     'StockrotationAdvance',
20608                     'StockrotationRepatriation'
20609                 )
20610             AFTER `comments`
20611           }
20612     );
20613
20614     # Move stockrotation states to reason field
20615     $dbh->do(
20616         qq{
20617             UPDATE
20618               `branchtransfers`
20619             SET
20620               `reason` = 'StockrotationAdvance',
20621               `comments` = NULL
20622             WHERE
20623               `comments` = 'StockrotationAdvance'
20624           }
20625     );
20626     $dbh->do(
20627         qq{
20628             UPDATE
20629               `branchtransfers`
20630             SET
20631               `reason` = 'StockrotationRepatriation',
20632               `comments` = NULL
20633             WHERE
20634               `comments` = 'StockrotationRepatriation'
20635           }
20636     );
20637
20638     NewVersion( $DBversion, 24296, q|Update stockrotation to use 'reason' field in transfers table| );
20639 }
20640
20641 $DBversion = '19.12.00.016';
20642 if( CheckVersion( $DBversion ) ) {
20643     $dbh->do(q{
20644         INSERT IGNORE INTO `userflags` (`bit`, `flag`, `flagdesc`, `defaulton`)
20645         VALUES (12, 'suggestions', 'Suggestion management', 0)
20646     });
20647
20648     $dbh->do(q{
20649         UPDATE permissions SET module_bit=12
20650         WHERE code="suggestions_manage"
20651     });
20652
20653     $dbh->do(q{
20654         UPDATE borrowers SET flags = flags | (1<<12) WHERE flags & (1 << 11)
20655     });
20656
20657     NewVersion( $DBversion, 22868, 'Move suggestions_manage subpermission out of acquisition permission' );
20658 }
20659
20660 $DBversion = '19.12.00.017';
20661 if( CheckVersion( $DBversion ) ) {
20662     if( !index_exists( 'library_groups', 'library_groups_uniq_2' ) ) {
20663         $dbh->do(q|
20664             DELETE FROM library_groups
20665             WHERE id NOT IN (
20666                 SELECT MIN(id)
20667                 FROM ( SELECT * FROM library_groups ) AS lg
20668                 GROUP BY parent_id, branchcode
20669             )
20670             AND NOT(parent_id IS NULL OR branchcode IS NULL);
20671         |);
20672         $dbh->do(q|
20673             ALTER TABLE library_groups
20674             ADD UNIQUE KEY library_groups_uniq_2 (parent_id, branchcode)
20675         |);
20676     }
20677
20678     NewVersion( $DBversion, 21674, 'Add unique key (parent_id, branchcode) to library_group' );
20679 }
20680
20681 $DBversion = '19.12.00.018';
20682 if( CheckVersion( $DBversion ) ) {
20683     my @columns = qw(
20684         restrictedtype
20685         rentaldiscount
20686         fine
20687         finedays
20688         maxsuspensiondays
20689         suspension_chargeperiod
20690         firstremind
20691         chargeperiod
20692         chargeperiod_charge_at
20693         accountsent
20694         issuelength
20695         lengthunit
20696         hardduedate
20697         hardduedatecompare
20698         renewalsallowed
20699         renewalperiod
20700         norenewalbefore
20701         auto_renew
20702         no_auto_renewal_after
20703         no_auto_renewal_after_hard_limit
20704         reservesallowed
20705         holds_per_record
20706         holds_per_day
20707         onshelfholds
20708         opacitemholds
20709         overduefinescap
20710         cap_fine_to_replacement_price
20711         article_requests
20712         note
20713     );
20714
20715     $dbh->do(q|
20716         DELETE i FROM issuingrules i
20717         LEFT JOIN itemtypes it ON i.itemtype=it.itemtype
20718         WHERE it.itemtype IS NULL AND i.itemtype!='*'
20719     |);
20720     $dbh->do(q|
20721         DELETE i FROM issuingrules i
20722         LEFT JOIN branches b ON i.branchcode=b.branchcode
20723         WHERE b.branchcode IS NULL AND i.branchcode!='*'
20724     |);
20725     $dbh->do(q|
20726         DELETE i FROM issuingrules i
20727         LEFT JOIN categories c ON i.categorycode=c.categorycode
20728         WHERE c.categorycode IS NULL AND i.categorycode!='*'
20729     |);
20730     if ( column_exists( 'issuingrules', 'categorycode' ) ) {
20731         foreach my $column ( @columns ) {
20732             $dbh->do("
20733                 INSERT INTO circulation_rules ( categorycode, branchcode, itemtype, rule_name, rule_value )
20734                 SELECT IF(categorycode='*', NULL, categorycode), IF(branchcode='*', NULL, branchcode), IF(itemtype='*', NULL, itemtype), \'$column\', COALESCE( $column, '' )
20735                 FROM issuingrules
20736             ");
20737         }
20738         $dbh->do("
20739             DELETE FROM circulation_rules WHERE rule_name='holdallowed' AND rule_value='';
20740         ");
20741         $dbh->do("DROP TABLE issuingrules");
20742     }
20743
20744     NewVersion( $DBversion, 18936, 'Convert issuingrules fields to circulation_rules' );
20745 }
20746
20747 $DBversion = '19.12.00.019';
20748 if( CheckVersion( $DBversion ) ) {
20749
20750     $dbh->do("ALTER TABLE message_queue MODIFY time_queued timestamp NULL");
20751
20752     if( !column_exists( 'message_queue', 'updated_on' ) ) {
20753         $dbh->do("ALTER TABLE message_queue ADD COLUMN updated_on timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER time_queued");
20754         $dbh->do("UPDATE message_queue SET updated_on=time_queued");
20755     }
20756
20757     NewVersion( $DBversion, 23673, 'modify time_queued and add updated_on to message_queue' );
20758 }
20759
20760 $DBversion = '19.12.00.020';
20761 if ( CheckVersion($DBversion) ) {
20762     if ( !column_exists( 'marc_subfield_structure', 'important') ){
20763         $dbh->do("ALTER TABLE marc_subfield_structure ADD COLUMN important TINYINT(4) NOT NULL DEFAULT 0  AFTER mandatory");
20764     }
20765     if ( !column_exists( 'marc_tag_structure', 'important') ){
20766         $dbh->do("ALTER TABLE marc_tag_structure ADD COLUMN important TINYINT(4) NOT NULL DEFAULT 0  AFTER mandatory");
20767     }
20768
20769     NewVersion( $DBversion, 8643, 'Add important constraint to marc subfields' );
20770 }
20771
20772 $DBversion = '19.12.00.021';
20773 if( CheckVersion( $DBversion ) ) {
20774
20775     # Add LOST_FOUND debit type
20776     $dbh->do(qq{
20777         INSERT IGNORE INTO
20778           account_credit_types ( code, description, can_be_added_manually, is_system )
20779         VALUES
20780           ('LOST_FOUND', 'Lost item fee refund', 0, 1)
20781     });
20782
20783     # Migrate LOST_RETURN to LOST_FOUND
20784     $dbh->do(qq{
20785         UPDATE
20786           accountlines
20787         SET
20788           credit_type_code = 'LOST_FOUND'
20789         WHERE
20790           credit_type_code = 'LOST_RETURN'
20791         OR
20792           credit_type_code = 'LOST_RETURNED'
20793     });
20794
20795     # Migrate LOST + RETURNED to LOST + FOUND
20796     $dbh->do(qq{
20797         UPDATE
20798           accountlines
20799         SET
20800           status = 'FOUND'
20801         WHERE
20802           debit_type_code = 'LOST'
20803         AND
20804           status = 'RETURNED'
20805     });
20806
20807     # Drop LOST_RETURNED credit type
20808     $dbh->do(qq{
20809         DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
20810     });
20811
20812     # Drop LOST_RETURN credit type
20813     $dbh->do(qq{
20814         DELETE FROM account_credit_types WHERE code = 'LOST_RETURN'
20815     });
20816
20817     # Add Lost Item Found offset type
20818     $dbh->do(qq{
20819         INSERT IGNORE INTO
20820           account_offset_types ( type )
20821         VALUES
20822           ( 'Lost Item Found' )
20823     });
20824
20825     NewVersion( $DBversion, 24592, 'Update LOST_RETURN to LOST_FOUND');
20826 }
20827
20828 $DBversion = '19.12.00.022';
20829 if( CheckVersion( $DBversion ) ) {
20830     $dbh->do( "ALTER TABLE items MODIFY COLUMN uri MEDIUMTEXT" );
20831     $dbh->do( "ALTER TABLE deleteditems MODIFY COLUMN uri MEDIUMTEXT" );
20832
20833     NewVersion( $DBversion, 20882, 'items.uri to MEDIUMTEXT');
20834 }
20835
20836 $DBversion = '19.12.00.023';
20837 if( CheckVersion( $DBversion ) ) {
20838     $dbh->do( "ALTER TABLE quotes MODIFY timestamp datetime NULL" );
20839
20840     NewVersion( $DBversion, 24640, 'Allow quotes.timestamp to be NULL');
20841 }
20842
20843 $DBversion = '19.12.00.024';
20844 if( CheckVersion( $DBversion ) ) {
20845     $dbh->do(q{
20846         UPDATE systempreferences SET value = 'off'
20847         WHERE variable = 'finesMode' AND (value <> 'production' OR value IS NULL)
20848     });
20849     $dbh->do(q{
20850         UPDATE systempreferences SET options = 'off|production',
20851         explanation = "Choose the fines mode, 'off' (do not accrue fines) or 'production' (accrue overdue fines).  Requires accruefines cronjob or CalculateFinesOnReturn system preference."
20852         WHERE variable = 'finesMode'
20853     });
20854
20855     NewVersion( $DBversion, 21633, 'Remove finesMode "test"');
20856 }
20857
20858 $DBversion = '19.12.00.025';
20859 if( CheckVersion( $DBversion ) ) {
20860     $dbh->do(q{
20861         INSERT IGNORE INTO `systempreferences` (variable,value,options,explanation,type)
20862         VALUES ('DumpSearchQueryTemplate',0,'','Add the search query being passed to the search engine into the template for debugging','YesNo')
20863     });
20864
20865     NewVersion( $DBversion, 24103, 'add DumpSearchQueryTemplate syspref');
20866 }
20867
20868 $DBversion = '19.12.00.026';
20869 if( CheckVersion( $DBversion ) ) {
20870     if( !column_exists( 'z3950servers', 'attributes' ) ) {
20871         $dbh->do( "ALTER TABLE z3950servers ADD COLUMN attributes VARCHAR(255) after add_xslt" );
20872     }
20873
20874     NewVersion( $DBversion, 11297, 'Add support for custom PQF attributes for Z39.50 server searches');
20875 }
20876
20877 $DBversion = '19.12.00.027';
20878 if( CheckVersion( $DBversion ) ) {
20879
20880     # Add any pathalogical incorrect debit_types as credit_types as appropriate
20881     $dbh->do(
20882         qq{
20883           INSERT IGNORE INTO account_credit_types (
20884             code,
20885             description,
20886             can_be_added_manually,
20887             is_system
20888           )
20889           SELECT
20890             DISTINCT(debit_type_code),
20891             "Unexpected type found during upgrade",
20892             1,
20893             0
20894           FROM
20895             accountlines
20896           WHERE
20897             amount < 0
20898           AND
20899             debit_type_code IS NOT NULL
20900         }
20901     );
20902
20903     # Correct any pathalogical cases
20904     $dbh->do( qq{
20905       UPDATE
20906         accountlines
20907       SET
20908         credit_type_code = debit_type_code,
20909         debit_type_code = NULL
20910       WHERE
20911         amount < 0
20912       AND
20913         debit_type_code IS NOT NULL
20914     });
20915
20916     NewVersion( $DBversion, 24532, 'Fix pathological cases of negative debits');
20917 }
20918
20919 $DBversion = '19.12.00.028';
20920 if( CheckVersion( $DBversion ) ) {
20921     $dbh->do(q{
20922         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
20923         VALUES
20924         ('OpacBrowseSearch', '0',NULL, "Elasticsearch only: add a page allowing users to 'browse' all items in the collection",'YesNo')
20925     });
20926
20927     NewVersion( $DBversion, 14567, 'Add OpacBrowseSearch syspref');
20928 }
20929
20930 $DBversion = '19.12.00.029';
20931 if( CheckVersion( $DBversion ) ) {
20932     if (!column_exists('account_credit_types', 'archived')) {
20933         $dbh->do('ALTER TABLE account_credit_types ADD COLUMN archived tinyint(1) NOT NULL DEFAULT 0 AFTER is_system');
20934     }
20935
20936     NewVersion( $DBversion, 17702, 'Add column account_credit_types.archived');
20937 }
20938
20939 $DBversion = '19.12.00.030';
20940 if( CheckVersion( $DBversion ) ) {
20941
20942     # get list of installed translations
20943     require C4::Languages;
20944     my @langs;
20945     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
20946
20947     foreach my $language ( @$tlangs ) {
20948         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
20949             push @langs, $sublanguage->{'rfc4646_subtag'};
20950         }
20951     }
20952
20953     # Get any existing value from the opacheader system preference
20954     my ($opacheader) = $dbh->selectrow_array( q|
20955         SELECT value FROM systempreferences WHERE variable='opacheader';
20956     |);
20957
20958     my @detail;
20959     if( $opacheader ){
20960         foreach my $lang ( @langs ) {
20961             # If there is a value in the opacheader preference, insert it into opac_news
20962             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "opacheader_$lang", $opacheader);
20963             push @detail, "Inserted opacheader contents into $lang news item...";
20964         }
20965     }
20966     # Remove the opacheader system preference
20967     $dbh->do("DELETE FROM systempreferences WHERE variable='opacheader'");
20968
20969     unshift @detail, 'Move contents of opacheader preference to Koha news system';
20970     NewVersion( $DBversion, 22880, \@detail);
20971 }
20972
20973 $DBversion = '19.12.00.031';
20974 if( CheckVersion( $DBversion ) ) {
20975     $dbh->do( q|
20976 ALTER TABLE article_requests MODIFY COLUMN created_on timestamp NULL, MODIFY COLUMN updated_on timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
20977     |);
20978
20979     NewVersion( $DBversion, 22273, "Column article_requests.created_on should not be updated" );
20980 }
20981
20982 $DBversion = '19.12.00.032';
20983 if( CheckVersion( $DBversion ) ) {
20984     $dbh->do( q|
20985         DELETE FROM systempreferences WHERE variable="UseQueryParser"
20986     |);
20987
20988     NewVersion( $DBversion, 24735, "Remove UseQueryParser system preference" );
20989 }
20990
20991 $DBversion = '19.12.00.033';
20992 if ( CheckVersion($DBversion) ) {
20993
20994     # Add cash_register_actions table
20995     if ( !TableExists('cash_register_actions') ) {
20996         $dbh->do(qq{
20997             CREATE TABLE `cash_register_actions` (
20998               `id` int(11) NOT NULL auto_increment, -- unique identifier for each account register action
20999               `code` varchar(24) NOT NULL, -- action code denoting the type of action recorded (enum),
21000               `register_id` int(11) NOT NULL, -- id of cash_register this action belongs to,
21001               `manager_id` int(11) NOT NULL, -- staff member performing the action
21002               `amount` decimal(28,6) DEFAULT NULL, -- amount recorded in action (signed)
21003               `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
21004               PRIMARY KEY (`id`),
21005               CONSTRAINT `cash_register_actions_manager` FOREIGN KEY (`manager_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE CASCADE ON UPDATE CASCADE,
21006               CONSTRAINT `cash_register_actions_register` FOREIGN KEY (`register_id`) REFERENCES `cash_registers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
21007             ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
21008         });
21009     }
21010
21011     # Add cashup permission
21012     $dbh->do(qq{
21013         INSERT IGNORE permissions (module_bit, code, description)
21014         VALUES
21015         (25, 'cashup', 'Perform cash register cashup action')
21016     });
21017
21018     NewVersion( $DBversion, 23355, [ "Add cash_register_actions table", "Add cash register cashup permissions" ] );
21019 }
21020
21021 $DBversion = '19.12.00.034';
21022 if ( CheckVersion($DBversion) ) {
21023
21024     $dbh->do(
21025         qq{
21026             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
21027             VALUES
21028               ('DISCOUNT', 'A discount applied to a patrons fine', 0, 1)
21029         }
21030     );
21031
21032     $dbh->do(
21033         qq{
21034         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('DISCOUNT');
21035     }
21036     );
21037
21038     $dbh->do(
21039         qq{
21040         INSERT IGNORE permissions (module_bit, code, description)
21041         VALUES
21042         (10, 'discount', 'Perform account discount action')
21043     }
21044     );
21045
21046     NewVersion( $DBversion, 24081, "Add DISCOUNT to account_credit_types and account_offset_types, Add accounts discount permission");
21047 }
21048
21049 $DBversion = '19.12.00.035';
21050 if ( CheckVersion($DBversion) ) {
21051
21052     $dbh->do(qq{
21053         INSERT IGNORE permissions (module_bit, code, description)
21054         VALUES
21055         (25, 'anonymous_refund', 'Perform refund actions from cash registers')
21056     });
21057
21058     NewVersion( $DBversion, 23442, "Add a refund option to the point of sale system" );
21059 }
21060
21061 $DBversion = '19.12.00.036';
21062 if( CheckVersion( $DBversion ) ) {
21063     $dbh->do(q{
21064         INSERT IGNORE INTO `systempreferences`
21065             (`variable`, `value`, `options`, `explanation`, `type`)
21066         VALUES
21067             ('AccessControlAllowOrigin', '', NULL, 'Set the Access-Control-Allow-Origin header to the specified value', 'Free');
21068     });
21069
21070     NewVersion( $DBversion, 24369, "Add CORS support to Koha");
21071 }
21072
21073 $DBversion = '19.12.00.037';
21074 if( CheckVersion( $DBversion ) ) {
21075
21076     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('RenewAccruingItemInOpac', '0', 'If enabled, when the fines on an item accruing is paid off in the OPAC via a payment plugin, attempt to renew that item. If the syspref "RenewalPeriodBase" is set to "due date", renewed items may still be overdue', '', 'YesNo'); | );
21077     
21078     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('RenewAccruingItemWhenPaid', '0', 'If enabled, when the fines on an item accruing is paid off, attempt to renew that item. If the syspref "RenewalPeriodBase" is set to "due date", renewed items may still be overdue', '', 'YesNo'); | );
21079
21080     NewVersion( $DBversion, 23051, [ "Add RenewAccruingItemInOpac syspref", "Add RenewAccruingItemWhenPaid syspref" ]);
21081 }
21082
21083 $DBversion = '19.12.00.038';
21084 if( CheckVersion( $DBversion ) ) {
21085     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('CirculateILL', '0', 'If enabled, it is possible to circulate ILL requested items from within ILL', '', 'YesNo'); | );
21086
21087     NewVersion( $DBversion, 23112, "Add CirculateILL syspref");
21088 }
21089
21090 $DBversion = '19.12.00.039';
21091 if( CheckVersion( $DBversion ) ) {
21092     $dbh->do( "DROP TABLE IF EXISTS printers" );
21093
21094     if( column_exists( 'branches', 'branchprinter' ) ) {
21095         $dbh->do( "ALTER TABLE branches DROP COLUMN branchprinter" );
21096     }
21097
21098     $dbh->do(qq{ DELETE FROM systempreferences WHERE variable = "printcirculationslips"} );
21099
21100     NewVersion( $DBversion, 17845, "Drop unused table printers and branchprinter column");
21101 }
21102
21103 $DBversion = '19.12.00.040';
21104 if( CheckVersion( $DBversion ) ) {
21105     $dbh->do( "UPDATE systempreferences SET  explanation = 'Comma separated list defining the default fields to be used during a patron search using the \"standard\" option. If empty Koha will default to \"surname,firstname,othernames,cardnumber,userid\". Additional fields added to this preference will be added as search options in the dropdown menu on the patron search page.' WHERE variable='DefaultPatronSearchFields' " );
21106
21107     NewVersion( $DBversion, 17374, "Update description of DefaultPatronSearchFields");
21108 }
21109
21110 $DBversion = '19.12.00.041';
21111 if( CheckVersion( $DBversion ) ) {
21112
21113     # Update existing NULL priorities
21114     $dbh->do(q|
21115         UPDATE reserves SET priority = 1 WHERE priority IS NULL
21116     |);
21117
21118     $dbh->do(q|
21119         ALTER TABLE reserves MODIFY priority SMALLINT(6) NOT NULL DEFAULT 1
21120     |);
21121
21122     $dbh->do(q|
21123         UPDATE old_reserves SET priority = 1 WHERE priority IS NULL
21124     |);
21125
21126     $dbh->do(q|
21127         ALTER TABLE old_reserves MODIFY priority SMALLINT(6) NOT NULL DEFAULT 1
21128     |);
21129
21130     NewVersion( $DBversion, 24722, "Enforce NOT NULL constraint for reserves.priority");
21131 }
21132
21133 $DBversion = '19.12.00.042';
21134 if( CheckVersion( $DBversion ) ) {
21135     if (!column_exists('message_queue', 'reply_address')) {
21136         $dbh->do('ALTER TABLE message_queue ADD COLUMN reply_address LONGTEXT AFTER from_address');
21137     }
21138
21139     NewVersion( $DBversion, 22821, "Add reply_address to message_queue");
21140 }
21141
21142 $DBversion = '19.12.00.043';
21143 if( CheckVersion( $DBversion ) ) {
21144
21145     # Add return reasons to enum
21146     $dbh->do(
21147         qq{
21148             ALTER TABLE
21149                 `branchtransfers`
21150             MODIFY COLUMN
21151                 `reason` enum(
21152                     'Manual',
21153                     'StockrotationAdvance',
21154                     'StockrotationRepatriation',
21155                     'ReturnToHome',
21156                     'ReturnToHolding'
21157                 )
21158             AFTER `comments`
21159           }
21160     );
21161
21162     NewVersion( $DBversion, 24296, "Add 'return' reasons to branchtransfers enum");
21163 }
21164
21165 $DBversion = '19.12.00.044';
21166 if( CheckVersion( $DBversion ) ) {
21167     $dbh->do(qq{
21168         INSERT IGNORE permissions (module_bit, code, description)
21169         VALUES
21170         (13, 'batch_extend_due_dates', 'Perform batch extend due dates')
21171     });
21172
21173     NewVersion( $DBversion, 24846, "Add a new permission for new tool batch extend due dates");
21174 }
21175
21176 $DBversion = '19.12.00.045';
21177 if( CheckVersion( $DBversion ) ) {
21178     $dbh->do(q{
21179         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) 
21180         VALUES
21181         ('CollapseFieldsPatronAddForm','',NULL,'Collapse these fields by default when adding a new patron. These fields can still be expanded.','Multiple') 
21182     });
21183
21184     NewVersion( $DBversion, 4461, "Add CollapseFieldsPatronAddForm system preference");
21185 }
21186
21187 $DBversion = '19.12.00.046';
21188 if( CheckVersion( $DBversion ) ) {
21189
21190     $dbh->do( "ALTER TABLE accountlines MODIFY COLUMN date TIMESTAMP NULL" );
21191
21192     NewVersion( $DBversion, 24818, "Update 'accountlines.date' from DATE to TIMESTAMP");
21193 }
21194
21195 $DBversion = '19.12.00.047';
21196 if( CheckVersion( $DBversion ) ) {
21197     $dbh->do(q{
21198         ALTER TABLE biblioimages
21199         ADD `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
21200         AFTER `thumbnail`;
21201     });
21202
21203     NewVersion( $DBversion, 22987, "Add biblioimages.timestamp");
21204 }
21205
21206 $DBversion = '19.12.00.048';
21207 if( CheckVersion( $DBversion ) ) {
21208
21209     # Add rotating collection states to reason enum
21210     $dbh->do(
21211         qq{
21212             ALTER TABLE
21213                 `branchtransfers`
21214             MODIFY COLUMN
21215                 `reason` enum(
21216                     'Manual',
21217                     'StockrotationAdvance',
21218                     'StockrotationRepatriation',
21219                     'ReturnToHome',
21220                     'ReturnToHolding',
21221                     'RotatingCollection'
21222                 )
21223             AFTER `comments`
21224           }
21225     );
21226
21227     NewVersion( $DBversion, 24299, "Add 'collection' reasons to branchtransfers enum");
21228 }
21229
21230 $DBversion = '19.12.00.049';
21231 if( CheckVersion( $DBversion ) ) {
21232
21233     # Add reserve reasons enum
21234     $dbh->do(
21235         qq{
21236             ALTER TABLE
21237                 `branchtransfers`
21238             MODIFY COLUMN
21239                 `reason` enum(
21240                     'Manual',
21241                     'StockrotationAdvance',
21242                     'StockrotationRepatriation',
21243                     'ReturnToHome',
21244                     'ReturnToHolding',
21245                     'RotatingCollection',
21246                     'Reserve',
21247                     'LostReserve',
21248                     'CancelReserve'
21249                 )
21250             AFTER `comments`
21251           }
21252     );
21253
21254     NewVersion( $DBversion, 24299, "Add 'reserve' reasons to branchtransfers enum");
21255 }
21256
21257 $DBversion = '19.12.00.050';
21258 if( CheckVersion( $DBversion ) ) {
21259     $dbh->do( "DELETE FROM systempreferences WHERE variable in ('IDreamBooksReadometer','IDreamBooksResults','IDreamBooksReviews')" );
21260
21261     NewVersion( $DBversion, 24854, "Remove IDreamBooks* system preferences");
21262 }
21263
21264 $DBversion = '19.12.00.051';
21265 if( CheckVersion( $DBversion ) ) {
21266     $dbh->do(q{
21267         UPDATE systempreferences SET options = 'itemhomebranch|patronhomebranch|checkoutbranch|none' WHERE variable='OpacRenewalBranch'
21268     });
21269     $dbh->do(q{
21270         UPDATE systempreferences SET value = "none" WHERE variable='OpacRenewalBranch'
21271         AND value = 'NULL'
21272     });
21273     $dbh->do(q{
21274         UPDATE systempreferences SET value = 'opacrenew' WHERE variable='OpacRenewalBranch'
21275         AND value NOT IN ('checkoutbranch','itemhomebranch','opacrenew','patronhomebranch','none')
21276     });
21277
21278     NewVersion( $DBversion, 24759, "Cleanup OpacRenewalBranch");
21279 }
21280
21281 $DBversion = '19.12.00.052';
21282 if( CheckVersion( $DBversion ) ) {
21283     my $finesCalendar = C4::Context->preference('finesCalendar');
21284     my $value = $finesCalendar eq 'noFinesWhenClosed' ? 1 : 0;
21285
21286     if( !column_exists( 'itemtypes', 'rentalcharge_daily_calendar' ) ) {
21287         $dbh->do(q{
21288             ALTER TABLE itemtypes ADD COLUMN
21289             rentalcharge_daily_calendar tinyint(1) NOT NULL DEFAULT 1
21290             AFTER rentalcharge_daily;
21291         });
21292
21293         $dbh->do("UPDATE itemtypes SET rentalcharge_daily_calendar = $value");
21294     }
21295
21296     if( !column_exists( 'itemtypes', 'rentalcharge_hourly_calendar' ) ) {
21297         $dbh->do(q{
21298             ALTER TABLE itemtypes ADD COLUMN
21299             rentalcharge_hourly_calendar tinyint(1) NOT NULL DEFAULT 1
21300             AFTER rentalcharge_hourly;
21301         });
21302
21303         $dbh->do("UPDATE itemtypes SET rentalcharge_hourly_calendar = $value");
21304     }
21305
21306     NewVersion( $DBversion, 21443, "Add ability to exclude holidays when calculating rentals fees by time period");
21307 }
21308
21309 $DBversion = '19.12.00.053';
21310 if( CheckVersion( $DBversion ) ) {
21311     unless( column_exists('borrowers','autorenew_checkouts') ){
21312         $dbh->do( "ALTER TABLE borrowers ADD COLUMN autorenew_checkouts TINYINT(1) NOT NULL DEFAULT 1 AFTER anonymized" );
21313     }
21314     unless( column_exists('deletedborrowers','autorenew_checkouts') ){
21315         $dbh->do( "ALTER TABLE deletedborrowers ADD COLUMN autorenew_checkouts TINYINT(1) NOT NULL DEFAULT 1 AFTER anonymized" );
21316     }
21317     $dbh->do(q{
21318         INSERT IGNORE INTO systempreferences
21319         ( `variable`, `value`, `options`, `explanation`, `type` )
21320         VALUES
21321         ('AllowPatronToControlAutorenewal','0',NULL,'If enabled, patrons will have a field in their account to choose whether their checkouts are auto renewed or not','YesNo')
21322     });
21323
21324     NewVersion( $DBversion, 24476, "Allow patrons to opt-out of autorenewal");
21325 }
21326
21327 $DBversion = '19.12.00.054';
21328 if( CheckVersion( $DBversion ) ) {
21329
21330     if ( !TableExists('desks') ) {
21331         $dbh->do(qq{
21332              CREATE TABLE `desks` ( -- desks available in a library
21333                `desk_id` int(11) NOT NULL auto_increment, -- unique identifier added by Koha
21334                `desk_name` varchar(100) NOT NULL default '', -- name of the desk
21335                `branchcode` varchar(10) NOT NULL,       -- library the desk is located at
21336                PRIMARY KEY (`desk_id`),
21337                KEY `fk_desks_branchcode` (`branchcode`),
21338                CONSTRAINT `fk_desks_branchcode` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE
21339              ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
21340         });
21341     }
21342
21343     NewVersion( $DBversion, 13881, "Add desk management");
21344 }
21345
21346 $DBversion = '19.12.00.055';
21347 if( CheckVersion( $DBversion ) ) {
21348     if( !column_exists( 'suggestions', 'lastmodificationby' ) ) {
21349         $dbh->do(q|
21350             ALTER TABLE suggestions ADD COLUMN lastmodificationby INT(11) DEFAULT NULL AFTER rejecteddate
21351         |);
21352
21353         $dbh->do(q|
21354             ALTER TABLE suggestions ADD CONSTRAINT `suggestions_ibfk_lastmodificationby` FOREIGN KEY (`lastmodificationby`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE
21355         |);
21356     }
21357
21358     if( !column_exists( 'suggestions', 'lastmodificationdate' ) ) {
21359         $dbh->do(q|
21360             ALTER TABLE suggestions ADD COLUMN lastmodificationdate DATE DEFAULT NULL AFTER lastmodificationby
21361         |);
21362
21363         my $suggestions = $dbh->selectall_arrayref(q|
21364             SELECT suggestionid, managedby, manageddate, acceptedby, accepteddate, rejectedby, rejecteddate
21365             FROM suggestions
21366         |, { Slice => {} });
21367         for my $suggestion ( @$suggestions ) {
21368             my ( $max_date ) = sort ( $suggestion->{manageddate} || (), $suggestion->{accepteddate} || (), $suggestion->{rejecteddate} || () );
21369             next unless $max_date;
21370             my $last_modif_by = ( defined $suggestion->{manageddate} and $max_date eq $suggestion->{manageddate} )
21371               ? $suggestion->{managedby}
21372               : ( defined $suggestion->{accepteddate} and $max_date eq $suggestion->{accepteddate} )
21373               ? $suggestion->{acceptedby}
21374               : ( defined $suggestion->{rejecteddate} and $max_date eq $suggestion->{rejecteddate} )
21375               ? $suggestion->{rejectedby}
21376               : undef;
21377             next unless $last_modif_by;
21378             $dbh->do(q|
21379                 UPDATE suggestions
21380                 SET lastmodificationdate = ?, lastmodificationby = ?
21381                 WHERE suggestionid = ?
21382             |, undef, $max_date, $last_modif_by, $suggestion->{suggestionid});
21383         }
21384
21385     }
21386
21387     $dbh->do( q|
21388         INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('suggestions', 'NOTIFY_MANAGER', '', 'Notify manager of a suggestion', 0, "A suggestion has been assigned to you", "Dear [% borrower.firstname %] [% borrower.surname %],\nA suggestion has been assigned to you: [% suggestion.title %].\nThank you,\n[% branch.branchname %]", 'email', 'default');
21389     | );
21390
21391     NewVersion( $DBversion, 23590, "Add lastmodificationby and lastmodificationdate to the suggestions table");
21392 }
21393
21394 $DBversion = '19.12.00.056';
21395 if( CheckVersion( $DBversion ) ) {
21396
21397     $dbh->do( "DELETE FROM systempreferences WHERE variable='UseKohaPlugins'" );
21398
21399     NewVersion( $DBversion, 20415, "Remove UseKohaPlugins preference");
21400 }
21401
21402 $DBversion = '19.12.00.057';
21403 if( CheckVersion( $DBversion ) ) {
21404
21405     $dbh->do( "DELETE FROM systempreferences WHERE variable='INTRAdidyoumean'" );
21406
21407     NewVersion( $DBversion, 20399, "Remove INTRAdidyoumean preference");
21408 }
21409
21410 $DBversion = '19.12.00.058';
21411 if( CheckVersion( $DBversion ) ) {
21412     $dbh->do(q{
21413         INSERT IGNORE INTO systempreferences (`variable`, `value`, `options`, `explanation`,`type`) VALUES
21414         ('OPACnumSearchResultsDropdown', 0, NULL, 'Enable option list of number of results per page to show in OPAC search results','YesNo'),
21415         ('numSearchResultsDropdown', 0, NULL, 'Enable option list of number of results per page to show in staff client search results','YesNo')
21416     });
21417
21418     NewVersion( $DBversion, 14715, "Add sysprefs numSearchResultsDropdown and OPACnumSearchResultsDropdown");
21419 }
21420
21421 $DBversion = '19.12.00.059';
21422 if( CheckVersion( $DBversion ) ) {
21423
21424     for my $column ( qw(othersupplier booksellerfax booksellerurl bookselleremail currency) ) {
21425         if( column_exists( 'aqbooksellers', $column ) ) {
21426             my ($count) = $dbh->selectrow_array(qq|
21427                 SELECT COUNT(*)
21428                 FROM aqbooksellers
21429                 WHERE $column IS NOT NULL AND $column <> ""
21430             |);
21431             if ( $count ) {
21432                 warn "Warning - Cannot remove column aqbooksellers.$column. At least one value exists";
21433             } else {
21434                 $dbh->do(qq|
21435                     ALTER TABLE aqbooksellers
21436                     DROP COLUMN $column
21437                 |);
21438             }
21439         }
21440     }
21441
21442     NewVersion( $DBversion, 18177, "Remove some unused columns from aqbooksellers");
21443 }
21444
21445 $DBversion = '19.12.00.060';
21446 if( CheckVersion( $DBversion ) ) {
21447     $dbh->do(q{
21448         ALTER TABLE search_marc_map CHANGE marc_type `marc_type` enum('marc21','normarc','unimarc') COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'what MARC type this map is for';
21449     });
21450     NewVersion( $DBversion, 23204, "Change enum order for marc_type in search_marc_map to fix sorting");
21451 }
21452
21453 $DBversion = '19.12.00.061';
21454 if ( CheckVersion($DBversion) ) {
21455     $dbh->do(q{
21456         UPDATE
21457           systempreferences
21458         SET
21459           options = "batchmod|moredetail|cronjob|additem|pendingreserves|onpayment"
21460         WHERE
21461           variable = "MarkLostItemsAsReturned"
21462     });
21463
21464     my $lost_item_returned = C4::Context->preference("MarkLostItemsAsReturned");
21465     my @set = split( ",", $lost_item_returned );
21466     push @set, 'onpayment';
21467     $lost_item_returned = join( ",", @set );
21468
21469     $dbh->do(qq{
21470         UPDATE
21471           systempreferences
21472         SET
21473           value = "$lost_item_returned"
21474         WHERE
21475           variable = "MarkLostItemsAsReturned"
21476     });
21477
21478     NewVersion( $DBversion, 24474, "Add `onpayment` option to MarkLostItemsAsReturned");
21479 }
21480
21481 $DBversion = '19.12.00.062';
21482 if( CheckVersion( $DBversion ) ) {
21483     $dbh->do( "UPDATE account_debit_types SET description = REPLACE(description,'Rewewal','Renewal') WHERE description like '%Rewewal%'" );
21484
21485     NewVersion( $DBversion, 25010, "Fix typo in account_debit_type description");
21486 }
21487
21488 $DBversion = '19.12.00.063';
21489 if( CheckVersion( $DBversion ) ) {
21490     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('PrefillGuaranteeField', 'phone,email,streetnumber,address,city,state,zipcode,country', NULL, 'Prefill these fields in guarantee member entry form from guarantor patron record', 'Multiple') });
21491
21492     NewVersion( $DBversion, 22534, "Add PreFillGuaranteeField syspref");
21493 }
21494
21495 $DBversion = '19.12.00.064';
21496 if( CheckVersion( $DBversion ) ) {
21497
21498     $dbh->do( q|
21499         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
21500             SELECT 'OpacNoItemTypeImages', value, NULL, 'If ON, disables itemtype images in the OPAC','YesNo'
21501             FROM (SELECT value FROM systempreferences WHERE variable="NoItemTypeImages") tmp
21502     | );
21503     $dbh->do( "UPDATE systempreferences SET explanation = 'If ON, disables itemtype images in the staff interface'
21504         WHERE variable = 'noItemTypeImages' ");
21505
21506     NewVersion( $DBversion, 4944, "Add new system preference OpacNoItemTypeImages");
21507 }
21508
21509 $DBversion = '19.12.00.065';
21510 if( CheckVersion( $DBversion ) ) {
21511
21512     $dbh->do( q| 
21513         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) 
21514         VALUES ('ILLCheckAvailability', '0', 'If enabled, during the ILL request process third party sources will be checked for current availability', '', 'YesNo')
21515     | );
21516
21517     NewVersion( $DBversion, 23173, "Add ILLCheckAvailability syspref");
21518 }
21519
21520 $DBversion = '19.12.00.066';
21521 if ( CheckVersion($DBversion) ) {
21522     $dbh->do(
21523 q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('OPACReportProblem', 0, NULL, 'Allow patrons to submit problem reports for OPAC pages to the library or Koha Administrator', 'YesNo') }
21524     );
21525     $dbh->do(
21526 q{INSERT IGNORE INTO letter (module, code, name, title, content, message_transport_type) VALUES ('members', 'PROBLEM_REPORT','OPAC Problem Report','OPAC Problem Report','Username: <<problem_reports.username>>\n\nProblem page: <<problem_reports.problempage>>\n\nTitle: <<problem_reports.title>>\n\nMessage: <<problem_reports.content>>','email') }
21527     );
21528     if ( !TableExists('problem_reports') ) {
21529         $dbh->do(
21530             q{ CREATE TABLE problem_reports (
21531             reportid int(11) NOT NULL auto_increment, -- unique identifier assigned by Koha
21532             title varchar(40) NOT NULL default '', -- report subject line
21533             content varchar(255) NOT NULL default '', -- report message content
21534             borrowernumber int(11) NOT NULL default 0, -- the user who created the problem report
21535             branchcode varchar(10) NOT NULL default '', -- borrower's branch
21536             username varchar(75) default NULL, -- OPAC username
21537             problempage TEXT default NULL, -- page the user triggered the problem report form from
21538             recipient enum('admin','library') NOT NULL default 'library', -- the 'to-address' of the problem report
21539             created_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of report submission
21540             status varchar(6) NOT NULL default 'New', -- status of the report. New, Viewed, Closed
21541             PRIMARY KEY (reportid),
21542             CONSTRAINT problem_reports_ibfk1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON DELETE CASCADE ON UPDATE CASCADE,
21543             CONSTRAINT problem_reports_ibfk2 FOREIGN KEY (branchcode) REFERENCES branches (branchcode) ON DELETE CASCADE ON UPDATE CASCADE
21544         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci }
21545         );
21546     }
21547     $dbh->do(
21548 q{INSERT IGNORE INTO userflags (bit, flag, flagdesc, defaulton) VALUES (26, 'problem_reports', 'Manage problem reports', 0) }
21549     );
21550     $dbh->do(
21551 q{INSERT IGNORE INTO permissions (module_bit, code, description) VALUES (26, 'manage_problem_reports', 'Manage OPAC problem reports') }
21552     );
21553
21554     NewVersion(
21555         $DBversion,
21556         4461,
21557         [
21558             "Add OPACReportProblem system preference",
21559             "Adding PROBLEM_REPORT notice",
21560             "Add problem reports table",
21561             "Add user permissions for managing OPAC problem reports"
21562         ]
21563     );
21564 }
21565
21566 $DBversion = '19.12.00.067';
21567 if( CheckVersion( $DBversion ) ) {
21568     # From: https://stackoverflow.com/questions/3311903/remove-duplicate-rows-in-mysql
21569     $dbh->do(q|
21570         DELETE a
21571         FROM virtualshelfshares as a, virtualshelfshares as b
21572         WHERE
21573           a.id < b.id 
21574         AND
21575           a.borrowernumber IS NOT NULL
21576         AND
21577           a.borrowernumber=b.borrowernumber
21578         AND
21579           a.shelfnumber=b.shelfnumber
21580     |);
21581
21582     NewVersion( $DBversion, 20754, "Remove double accepted list shares" );
21583 }
21584
21585 $DBversion = '19.12.00.068';
21586 if( CheckVersion( $DBversion ) ) {
21587     $dbh->do(q|
21588         INSERT IGNORE INTO systempreferences
21589           (variable,value,explanation,options,type)
21590         VALUES
21591           ('AuthFailureLog','','If enabled, log authentication failures',NULL,'YesNo'),
21592           ('AuthSuccessLog','','If enabled, log successful authentications',NULL,'YesNo')
21593     |);
21594
21595     NewVersion( $DBversion, 21190, "Add prefs AuthFailureLog and AuthSuccessLog");
21596 }
21597
21598 $DBversion = '19.12.00.069';
21599 if( CheckVersion( $DBversion ) ) {
21600     if( !column_exists( 'suggestions', 'archived' ) ) {
21601         $dbh->do(q|
21602             ALTER TABLE suggestions ADD COLUMN archived TINYINT(1) NOT NULL DEFAULT 0 AFTER `STATUS`;
21603         |);
21604     }
21605
21606     NewVersion( $DBversion, 22784, "Add a new suggestions.archived column");
21607 }
21608
21609 $DBversion = '19.12.00.070';
21610 if( CheckVersion( $DBversion ) ) {
21611
21612     $dbh->do( q{
21613             INSERT IGNORE INTO systempreferences (variable,value,explanation,type) VALUES
21614                 ('MaxTotalSuggestions','','Number of total suggestions used for time limit with NumberOfSuggestionDays','Free'),
21615                 ('NumberOfSuggestionDays','','Number of days that will be used to determine the MaxTotalSuggestions limit','Free')
21616             });
21617
21618     NewVersion( $DBversion, 22774, "Limit purchase suggestion in a specified time period");
21619 }
21620
21621 $DBversion = '19.12.00.071';
21622 if( CheckVersion( $DBversion ) ) {
21623     my @description = ("Add unique constraint to authorised_values");
21624     unless ( index_exists('authorised_values', 'av_uniq') ) {
21625         $dbh->do(q|
21626             DELETE FROM authorised_values
21627             WHERE category="COUNTRY" AND authorised_value="CC" AND lib="Keeling"
21628         |);
21629         my $duplicates = $dbh->selectall_arrayref(q|
21630             SELECT category, authorised_value, COUNT(concat(category, ':', authorised_value)) AS c
21631             FROM authorised_values
21632             GROUP BY category, authorised_value
21633             HAVING COUNT(concat(category, ':', authorised_value)) > 1
21634         |, { Slice => {} });
21635         if ( @$duplicates ) {
21636             push @description, "WARNING - Cannot create unique constraint on authorised_value(category, authorised_value)";
21637             push @description, "The following entries are duplicated: " . join(
21638                 ', ',
21639                 map {
21640                     sprintf "%s:%s (%s)", $_->{category},
21641                       $_->{authorised_value}, $_->{c}
21642                 } @$duplicates
21643             );
21644             for my $warning (@description) {
21645                 warn $warning;
21646             }
21647         } else {
21648             $dbh->do( q{ALTER TABLE `authorised_values` ADD CONSTRAINT `av_uniq` UNIQUE (category, authorised_value)} );
21649         }
21650     }
21651
21652     NewVersion( $DBversion, 22887, \@description );
21653 }
21654
21655 $DBversion = '19.12.00.072';
21656 if( CheckVersion( $DBversion ) ) {
21657     $dbh->do(q{
21658         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
21659             SELECT 'CalculateFinesOnBackdate',value,'','Switch to control if overdue fines are calculated on return when backdating','YesNo'
21660             FROM ( SELECT value FROM systempreferences WHERE variable = 'CalculateFinesOnReturn' ) tmp
21661     });
21662
21663     NewVersion( $DBversion, 24380, "Add syspref CalculateFinesOnBackdate");
21664 }
21665
21666 $DBversion = '19.12.00.073';
21667 if( CheckVersion( $DBversion ) ) {
21668     $dbh->do( "ALTER TABLE subscription MODIFY COLUMN closed tinyint(1) not null default 0" );
21669
21670     NewVersion( $DBversion, 25152, "Update subscription.closed to tinyint(1) as per guidelines");
21671 }
21672
21673 $DBversion = '19.12.00.074';
21674 if( CheckVersion( $DBversion ) ) {
21675     $dbh->do( "UPDATE systempreferences SET variable = 'SCOAllowCheckin' WHERE variable = 'AllowSelfCheckReturns'" );
21676
21677     # Always end with this (adjust the bug info)
21678     NewVersion( $DBversion, 25147, "Rename AllowSelfCheckReturns to SCOAllowCheckin for consistency");
21679 }
21680
21681 $DBversion = '19.12.00.075';
21682 if( CheckVersion( $DBversion ) ) {
21683
21684     $dbh->do( "ALTER TABLE borrower_modifications MODIFY changed_fields MEDIUMTEXT DEFAULT NULL" );
21685
21686     NewVersion( $DBversion, 25086, "Set changed_fields column of borrower_modifications as nullable");
21687 }
21688
21689 $DBversion = '19.12.00.076';
21690 if( CheckVersion( $DBversion ) ) {
21691     my @warnings;
21692
21693     sanitize_zero_date('serial', 'planneddate');
21694     sanitize_zero_date('serial', 'publisheddate');
21695     sanitize_zero_date('serial', 'claimdate');
21696
21697     $dbh->do(q|
21698         ALTER TABLE serial
21699         MODIFY COLUMN biblionumber INT(11) NOT NULL
21700     |);
21701
21702     unless ( foreign_key_exists( 'serial', 'serial_ibfk_1' ) ) {
21703         my $serials = $dbh->selectall_arrayref(q|
21704             SELECT serialid FROM serial JOIN subscription USING (subscriptionid) WHERE serial.biblionumber != subscription.biblionumber
21705         |, { Slice => {} });
21706         if ( @$serials ) {
21707             push @warnings, q|WARNING - The following serials will be updated, they were attached to a different biblionumber than their related subscription: | . join ", ", map { $_->{serialid} } @$serials;
21708             $dbh->do(q|
21709                 UPDATE serial JOIN subscription USING (subscriptionid) SET serial.biblionumber = subscription.biblionumber WHERE serial.biblionumber != subscription.biblionumber
21710             |);
21711         }
21712         $serials = $dbh->selectall_arrayref(q|
21713             SELECT serialid FROM serial WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21714         |, { Slice => {} });
21715         if ( @$serials ) {
21716             push @warnings, q|WARNING - The following serials are deleted, they were not attached to an existing bibliographic record (serialid): | . join ", ", map { $_->{serialid} } @$serials;
21717             $dbh->do(q|
21718                 DELETE FROM serial WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21719             |);
21720         }
21721         $dbh->do(q|
21722             ALTER TABLE serial
21723             ADD CONSTRAINT serial_ibfk_1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21724         |);
21725     }
21726
21727     $dbh->do(q|
21728         ALTER TABLE serial
21729         MODIFY COLUMN subscriptionid INT(11) NOT NULL
21730     |);
21731
21732     unless ( foreign_key_exists( 'serial', 'serial_ibfk_2' ) ) {
21733         my $serials = $dbh->selectall_arrayref(q|
21734             SELECT serialid FROM serial WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21735         |, { Slice => {} });
21736         if ( @$serials ) {
21737             push @warnings, q|WARNING - The following serials are deleted, they were not attached to an existing subscription (serialid): | . join ", ", map { $_->{serialid} } @$serials;
21738             $dbh->do(q|
21739                 DELETE FROM serial WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21740             |);
21741         }
21742         $dbh->do(q|
21743             ALTER TABLE serial
21744             ADD CONSTRAINT serial_ibfk_2 FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE
21745         |);
21746     }
21747
21748     $dbh->do(q|
21749         ALTER TABLE subscriptionhistory
21750         MODIFY COLUMN biblionumber int(11) NOT NULL,
21751         MODIFY COLUMN subscriptionid int(11) NOT NULL
21752     |);
21753
21754     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_1' ) ) {
21755         $dbh->do(q|
21756             UPDATE subscriptionhistory JOIN subscription USING (subscriptionid) SET subscriptionhistory.biblionumber = subscription.biblionumber WHERE subscriptionhistory.biblionumber != subscription.biblionumber
21757         |);
21758         $dbh->do(q|
21759             DELETE FROM subscriptionhistory WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21760         |);
21761         $dbh->do(q|
21762             ALTER TABLE subscriptionhistory
21763             ADD CONSTRAINT subscription_history_ibfk_1 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21764         |);
21765     }
21766
21767     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_2' ) ) {
21768         $dbh->do(q|
21769             DELETE FROM subscriptionhistory WHERE subscriptionid NOT IN (SELECT subscriptionid FROM subscription)
21770         |);
21771         $dbh->do(q|
21772             ALTER TABLE subscriptionhistory
21773             ADD CONSTRAINT subscription_history_ibfk_2 FOREIGN KEY (subscriptionid) REFERENCES subscription (subscriptionid) ON DELETE CASCADE ON UPDATE CASCADE
21774         |);
21775     }
21776
21777     $dbh->do(q|
21778         ALTER TABLE subscription
21779         MODIFY COLUMN biblionumber int(11) NOT NULL
21780     |);
21781
21782     unless ( foreign_key_exists( 'subscription', 'subscription_ibfk_3' ) ) {
21783         my $subscriptions = $dbh->selectall_arrayref(q|
21784             SELECT subscriptionid FROM subscription WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21785         |, { Slice => {} });
21786         if ( @$subscriptions ) {
21787             push @warnings, q|WARNING - The following subscriptions are deleted, they were not attached to an existing bibliographic record (subscriptionid): | . join ", ", map { $_->{subscriptionid} } @$subscriptions;
21788
21789             $dbh->do(q|
21790                 DELETE FROM subscription WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
21791             |);
21792         }
21793         $dbh->do(q|
21794             ALTER TABLE subscription
21795             ADD CONSTRAINT subscription_ibfk_3 FOREIGN KEY (biblionumber) REFERENCES biblio (biblionumber) ON DELETE CASCADE ON UPDATE CASCADE
21796         |);
21797     }
21798
21799     for my $warning (@warnings) {
21800         warn $warning;
21801     }
21802
21803     my $description = [ "Add foreign key constraints on serial", @warnings ];
21804     NewVersion( $DBversion, 21901, $description);
21805 }
21806
21807 $DBversion = '19.12.00.077';
21808 if( CheckVersion( $DBversion ) ) {
21809     if ( !column_exists( 'course_items', 'itype_enabled' ) ) {
21810         $dbh->do(q{
21811             ALTER TABLE course_items
21812             ADD COLUMN itype_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER itype,
21813             ADD COLUMN ccode_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER ccode,
21814             ADD COLUMN holdingbranch_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER holdingbranch,
21815             ADD COLUMN location_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER location,
21816             ADD COLUMN itype_storage varchar(10) DEFAULT NULL AFTER itype_enabled,
21817             ADD COLUMN ccode_storage varchar(80) DEFAULT NULL AFTER ccode_enabled,
21818             ADD COLUMN holdingbranch_storage varchar(10) DEFAULT NULL AFTER ccode_enabled,
21819             ADD COLUMN location_storage varchar(80) DEFAULT NULL AFTER location_enabled
21820         });
21821
21822         my $item_level_items = C4::Context->preference('item-level_itypes');
21823         my $itype_field = $item_level_items ? 'i.itype' : 'bi.itemtype';
21824         $dbh->do(qq{
21825             UPDATE course_items ci
21826             LEFT JOIN items i USING ( itemnumber )
21827             LEFT JOIN biblioitems bi USING ( biblioitemnumber )
21828             SET
21829
21830             -- Assume the column is enabled if the course item is active and i.itype/bi.itemtype is set,
21831             -- or if the course item is not enabled and ci.itype is set
21832             ci.itype_enabled = IF( ci.enabled = 'yes', IF( $itype_field IS NULL, 0, 1 ), IF(  ci.itype IS NULL, 0, 1  ) ),
21833             ci.ccode_enabled = IF( ci.enabled = 'yes', IF( i.ccode IS NULL, 0, 1 ), IF(  ci.ccode IS NULL, 0, 1  ) ),
21834             ci.holdingbranch_enabled = IF( ci.enabled = 'yes', IF( i.holdingbranch IS NULL, 0, 1 ), IF(  ci.holdingbranch IS NULL, 0, 1  ) ),
21835             ci.location_enabled = IF( ci.enabled = 'yes', IF( i.location IS NULL, 0, 1 ), IF(  ci.location IS NULL, 0, 1  ) ),
21836
21837             -- If the course item is enabled, copy the value from the item.
21838             -- If the course item is not enabled, keep the existing value
21839             ci.itype = IF( ci.enabled = 'yes', $itype_field, ci.itype ),
21840             ci.ccode = IF( ci.enabled = 'yes', i.ccode, ci.ccode ),
21841             ci.holdingbranch = IF( ci.enabled = 'yes', i.holdingbranch, ci.holdingbranch ),
21842             ci.location = IF( ci.enabled = 'yes', i.location, ci.location ),
21843
21844             -- If the course is enabled, copy the value from the item to storage.
21845             -- If it is not enabled, copy the value from the course item to storage
21846             ci.itype_storage = IF( ci.enabled = 'no', $itype_field, ci.itype ),
21847             ci.ccode_storage = IF( ci.enabled = 'no', i.ccode, ci.ccode ),
21848             ci.holdingbranch_storage = IF( ci.enabled = 'no', i.holdingbranch, ci.holdingbranch ),
21849             ci.location_storage = IF( ci.enabled = 'no', i.location, ci.location );
21850         });
21851
21852         # Clean up the storage columns
21853         $dbh->do(q{
21854             UPDATE course_items SET
21855                 itype_storage = NULL,
21856                 ccode_storage = NULL,
21857                 holdingbranch_storage = NULL,
21858                 location_storage = NULL
21859             WHERE enabled = 'no';
21860         });
21861
21862         # Clean up the course enabled value columns
21863         $dbh->do(q{
21864             UPDATE course_items SET
21865                 itype = IF( itype_enabled = 'no', NULL, itype ),
21866                 ccode = IF( ccode_enabled = 'no', NULL, ccode ),
21867                 holdingbranch = IF( holdingbranch_enabled = 'no', NULL, holdingbranch ),
21868                 location = IF( location_enabled = 'no', NULL, location )
21869             WHERE enabled = 'no';
21870         });
21871     }
21872
21873     NewVersion( $DBversion, 23727, "Editing course reserve items is broken");
21874 }
21875
21876 $DBversion = '19.12.00.078';
21877 if( CheckVersion( $DBversion ) ) {
21878     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('PatronSelfRegistrationConfirmEmail', '0', NULL, 'Require users to confirm their email address by entering it twice.', 'YesNo') });
21879
21880     NewVersion( $DBversion, 24913, "Add PatronSelfRegistrationConfirmEmail syspref");
21881 }
21882
21883 $DBversion = '19.12.00.079';
21884 if( CheckVersion( $DBversion ) ) {
21885
21886     # Default to the homologous OpacPublic syspref
21887     my $opac_public = C4::Context->preference('OpacPublic') ? 1 : 0;
21888
21889     $dbh->do(qq{
21890         INSERT IGNORE INTO `systempreferences`
21891             (`variable`,`value`,`explanation`,`options`,`type`)
21892         VALUES
21893             ('RESTPublicAnonymousRequests', $opac_public, NULL,'If enabled, the API will allow anonymous access to public routes that do not require authenticated access.','YesNo');
21894     });
21895
21896     NewVersion( $DBversion, 25045, "Add a way to restrict anonymous access to public routes (OpacPublic behaviour)");
21897 }
21898
21899 $DBversion = '19.12.00.080';
21900 if( CheckVersion( $DBversion ) ) {
21901      $dbh->do( "UPDATE items set issues=0 where issues is null" );
21902      $dbh->do( "UPDATE deleteditems set issues=0 where issues is null" );
21903      $dbh->do( "ALTER TABLE items ALTER issues set default 0" );
21904      $dbh->do( "ALTER TABLE deleteditems ALTER issues set default 0" );
21905
21906     NewVersion( $DBversion, 23081, "Set default to 0 for items.issues");
21907 }
21908
21909 $DBversion = '19.12.00.081';
21910 if (CheckVersion($DBversion)) {
21911     if (!column_exists('course_items', 'homebranch')) {
21912         $dbh->do(q{
21913             ALTER TABLE course_items
21914             ADD COLUMN homebranch VARCHAR(10) NULL DEFAULT NULL AFTER ccode_storage
21915         });
21916     }
21917
21918     if (!foreign_key_exists('course_items', 'fk_course_items_homebranch')) {
21919         $dbh->do(q{
21920             ALTER TABLE course_items
21921             ADD CONSTRAINT fk_course_items_homebranch
21922               FOREIGN KEY (homebranch) REFERENCES branches (branchcode)
21923               ON DELETE CASCADE ON UPDATE CASCADE
21924         });
21925     }
21926
21927     if (!column_exists('course_items', 'homebranch_enabled')) {
21928         $dbh->do(q{
21929             ALTER TABLE course_items
21930             ADD COLUMN homebranch_enabled tinyint(1) NOT NULL DEFAULT 0 AFTER homebranch
21931         });
21932     }
21933
21934     if (!column_exists('course_items', 'homebranch_storage')) {
21935         $dbh->do(q{
21936             ALTER TABLE course_items
21937             ADD COLUMN homebranch_storage VARCHAR(10) NULL DEFAULT NULL AFTER homebranch_enabled
21938         });
21939     }
21940
21941     if (!foreign_key_exists('course_items', 'fk_course_items_homebranch_storage')) {
21942         $dbh->do(q{
21943             ALTER TABLE course_items
21944             ADD CONSTRAINT fk_course_items_homebranch_storage
21945               FOREIGN KEY (homebranch_storage) REFERENCES branches (branchcode)
21946               ON DELETE CASCADE ON UPDATE CASCADE
21947         });
21948     }
21949
21950     NewVersion( $DBversion, 22630, "Add course_items.homebranch");
21951 }
21952
21953 $DBversion = '19.12.00.082';
21954 if( CheckVersion( $DBversion ) ) {
21955
21956     # get list of installed translations
21957     require C4::Languages;
21958     my @langs;
21959     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
21960
21961     foreach my $language ( @$tlangs ) {
21962         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
21963             push @langs, $sublanguage->{'rfc4646_subtag'};
21964         }
21965     }
21966
21967     # Get any existing value from the OpacMainUserBlock system preference
21968     my ($opacmainuserblock) = $dbh->selectrow_array( q|
21969         SELECT value FROM systempreferences WHERE variable='OpacMainUserBlock';
21970     |);
21971
21972     my @detail;
21973     if( $opacmainuserblock ){
21974         foreach my $lang ( @langs ) {
21975             # If there is a value in the OpacMainUserBlock preference, insert it into opac_news
21976             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacMainUserBlock_$lang", $opacmainuserblock);
21977             push @detail, "Inserting OpacMainUserBlock contents into $lang news item...";
21978         }
21979     }
21980     # Remove the OpacMainUserBlock system preference
21981     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacMainUserBlock'");
21982
21983     unshift @detail, "Move contents of OpacMainUserBlock preference to Koha news system";
21984     NewVersion( $DBversion, 23794, \@detail);
21985 }
21986
21987 $DBversion = '19.12.00.083';
21988 if( CheckVersion( $DBversion ) ) {
21989
21990     unless ( column_exists( 'authorised_value_categories', 'is_system' ) ) {
21991         $dbh->do(q|
21992             ALTER TABLE authorised_value_categories
21993             ADD COLUMN is_system TINYINT(1) DEFAULT 0 AFTER category_name
21994         |);
21995     }
21996
21997     $dbh->do(q|
21998         UPDATE authorised_value_categories
21999         SET is_system = 1
22000         WHERE category_name IN ('LOC', 'LOST', 'WITHDRAWN', 'Bsort1', 'Bsort2', 'Asort1', 'Asort2', 'SUGGEST', 'DAMAGED', 'LOST', 'BOR_NOTES', 'CCODE', 'NOT_LOAN')
22001     |);
22002
22003     $dbh->do(q|
22004         UPDATE authorised_value_categories
22005         SET is_system = 1
22006         WHERE category_name IN ('branches', 'itemtypes', 'cn_source')
22007     |);
22008
22009     NewVersion( $DBversion, 17355, "Add is_system to authorised_value_categories table");
22010 }
22011
22012 $DBversion = '19.12.00.084';
22013 if( CheckVersion( $DBversion ) ) {
22014     unless ( TableExists('advanced_editor_macros') ) {
22015         $dbh->do(q|
22016             CREATE TABLE advanced_editor_macros (
22017             id INT(11) NOT NULL AUTO_INCREMENT,
22018             name varchar(80) NOT NULL,
22019             macro longtext NULL,
22020             borrowernumber INT(11) default NULL,
22021             shared TINYINT(1) default 0,
22022             PRIMARY KEY (id),
22023             CONSTRAINT borrower_macro_fk FOREIGN KEY ( borrowernumber ) REFERENCES borrowers ( borrowernumber ) ON UPDATE CASCADE ON DELETE CASCADE
22024             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;|
22025         );
22026     }
22027     $dbh->do(q|
22028         INSERT IGNORE INTO permissions (module_bit, code, description)
22029         VALUES (9, 'create_shared_macros', 'Create public macros')
22030     |);
22031     $dbh->do(q|
22032         INSERT IGNORE INTO permissions (module_bit, code, description)
22033         VALUES (9, 'delete_shared_macros', 'Delete public macros')
22034     |);
22035
22036     NewVersion( $DBversion, 17682, "Add macros db table and permissions");
22037 }
22038
22039 $DBversion = '19.12.00.085';
22040 if( CheckVersion( $DBversion ) ) {
22041     unless ( TableExists( 'aqorders_claims' ) ) {
22042         $dbh->do(q|
22043             CREATE TABLE aqorders_claims (
22044                 id int(11) AUTO_INCREMENT,
22045                 ordernumber INT(11) NOT NULL,
22046                 claimed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
22047                 PRIMARY KEY (id),
22048                 CONSTRAINT aqorders_claims_ibfk_1 FOREIGN KEY (ordernumber) REFERENCES aqorders (ordernumber) ON DELETE CASCADE ON UPDATE CASCADE
22049             ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci
22050         |);
22051
22052         my $orders = $dbh->selectall_arrayref(q|
22053             SELECT ordernumber, claims_count, claimed_date
22054             FROM aqorders
22055             WHERE claims_count > 0
22056         |, { Slice => {} });
22057         my $insert_claim_sth = $dbh->prepare(q|
22058             INSERT INTO aqorders_claims (ordernumber, claimed_on)
22059             VALUES (?,?)
22060         |);
22061
22062         for my $order ( @$orders ) {
22063             for my $claim (1..$order->{claims_count}) {
22064                 $insert_claim_sth->execute($order->{ordernumber}, $order->{claimed_on});
22065             }
22066         }
22067
22068         $dbh->do(q|ALTER TABLE aqorders DROP COLUMN claims_count, DROP COLUMN claimed_date|);
22069     }
22070
22071     NewVersion( $DBversion, 24161, "Add new join table aqorders_claims to keep track of claims");
22072 }
22073
22074 $DBversion = '19.12.00.086';
22075 if( CheckVersion( $DBversion ) ) {
22076     $dbh->do(q{
22077         INSERT IGNORE INTO export_format( profile, description, content, csv_separator, type, used_for ) VALUES
22078         ("Late orders (CSV profile)", "Default CSV export for late orders", 'Title[% separator %]Author[% separator %]Publication year[% separator %]ISBN[% separator %]Quantity[% separator %]Number of claims
22079         [% FOR order IN orders ~%]
22080         [%~ SET biblio = order.biblio ~%]
22081         "[% biblio.title %]"[% separator ~%]
22082         "[% biblio.author %]"[% separator ~%]
22083         "[% bibio.biblioitem.publicationyear %]"[% separator ~%]
22084         "[% biblio.biblioitem.isbn %]"[% separator ~%]
22085         "[% order.quantity%]"[% separator ~%]
22086         "[% order.claims.count%][% IF order.claims.count %]([% FOR c IN order.claims %][% c.claimed_on | $KohaDates %][% UNLESS loop.last %], [% END %][% END %])[% END %]"
22087         [% END %]', ",", "sql", "late_orders")
22088     });
22089
22090     NewVersion( $DBversion, 24163, "Define a default CSV profile for late orders");
22091 }
22092
22093 $DBversion = '19.12.00.087';
22094 if( CheckVersion( $DBversion ) ) {
22095     $dbh->do(q{
22096         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22097         ('TrapHoldsOnOrder','1',NULL,'If enabled, Koha will trap holds for on order items ( notforloan < 0 )','YesNo')
22098     });
22099
22100     NewVersion( $DBversion, 25184, "Items with a negative notforloan status should not be captured for holds");
22101 }
22102
22103 $DBversion = '19.12.00.088';
22104 if( CheckVersion( $DBversion ) ) {
22105
22106     $dbh->do(q{
22107         UPDATE letter SET
22108         name = REPLACE(name, "notification on auto renewing", "Notification of automatic renewal"),
22109         title = REPLACE(title, "Auto renewals", "Automatic renewal notice"),
22110         content = REPLACE(content, "You have reach the maximum of checkouts possible.", "You have reached the maximum number of checkouts possible.")
22111         WHERE code = 'AUTO_RENEWALS';
22112     });
22113     $dbh->do(q{
22114         UPDATE letter SET
22115         content = REPLACE(content, "You have overdues.", "You have overdue items.")
22116         WHERE code = 'AUTO_RENEWALS';
22117     });
22118     $dbh->do(q{
22119         UPDATE letter SET
22120         content = REPLACE(content, "It's too late to renew this checkout.", "It's too late to renew this item.")
22121         WHERE code = 'AUTO_RENEWALS';
22122     });
22123     $dbh->do(q{
22124         UPDATE letter SET
22125         content = REPLACE(content, "You have too much unpaid fines.", "Your total unpaid fines are too high.")
22126         WHERE code = 'AUTO_RENEWALS';
22127     });
22128     $dbh->do(q{
22129         UPDATE letter SET
22130         content = REPLACE(content, "The following item [% biblio.title %] has correctly been renewed and is now due [% checkout.date_due %]", "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]
22131 ")
22132         WHERE code = 'AUTO_RENEWALS';
22133     });
22134
22135     NewVersion( $DBversion, 24378, "Fix some grammatical errors in default auto renewal notice");
22136 }
22137
22138 $DBversion = '19.12.00.089';
22139 if( CheckVersion( $DBversion ) ) {
22140
22141     # Migrate LOST_RETURNED to LOST_FOUND
22142     $dbh->do(qq{
22143         UPDATE
22144           accountlines
22145         SET
22146           credit_type_code = 'LOST_FOUND'
22147         WHERE
22148           credit_type_code = 'LOST_RETURNED'
22149     });
22150
22151     # Drop LOST_RETURNED credit type
22152     $dbh->do(qq{
22153         DELETE FROM account_credit_types WHERE code = 'LOST_RETURNED'
22154     });
22155
22156     NewVersion( $DBversion, 25389, "Catch errant cases of LOST_RETURNED");
22157 }
22158
22159 $DBversion = '19.12.00.090';
22160 if ( CheckVersion($DBversion) ) {
22161
22162     $dbh->do(
22163         qq{
22164           INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
22165           ('UseIssueDesks','0','','Use issue desks with circulation.','YesNo')
22166       }
22167     );
22168
22169     NewVersion( $DBversion, 13881, "Add issue desks system preference");
22170 }
22171
22172 $DBversion = '19.12.00.091';
22173 if ( CheckVersion($DBversion) ) {
22174
22175     $dbh->do(qq{
22176         UPDATE systempreferences SET variable = 'UseCirculationDesks' WHERE variable = 'UseIssueDesks'
22177     });
22178
22179     NewVersion( $DBversion, 13881, "Correction to preference terminology");
22180 }
22181
22182 $DBversion = '20.05.00.000';
22183 if( CheckVersion( $DBversion ) ) {
22184     NewVersion( $DBversion, undef, '20.05.00 alpha release' );
22185 }
22186
22187 $DBversion = '20.06.00.000';
22188 if( CheckVersion( $DBversion ) ) {
22189     NewVersion( $DBversion, undef, 'All our codebase are belong to everybody' );
22190 }
22191
22192 $DBversion = '20.06.00.001';
22193 if( CheckVersion( $DBversion ) ) {
22194     for my $f (qw( streetnumber streettype zipcode mobile B_streetnumber B_streettype B_zipcode ) ) {
22195         $dbh->do(qq|
22196             ALTER TABLE borrowers MODIFY $f TINYTEXT DEFAULT NULL
22197         |);
22198         $dbh->do(qq|
22199             ALTER TABLE deletedborrowers MODIFY $f TINYTEXT DEFAULT NULL
22200         |);
22201     }
22202     for my $f ( qw( B_address altcontactfirstname altcontactsurname altcontactaddress1 altcontactaddress2 altcontactaddress3 altcontactzipcode altcontactphone ) ) {
22203         $dbh->do(qq|
22204             ALTER TABLE borrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
22205         |);
22206         $dbh->do(qq|
22207             ALTER TABLE deletedborrowers MODIFY $f MEDIUMTEXT DEFAULT NULL
22208         |);
22209     }
22210
22211     NewVersion( $DBversion, 24986, "Switch borrowers address related fields to TINYTEXT or MEDIUMTEXT");
22212 }
22213
22214 $DBversion = '20.06.00.002';
22215 if( CheckVersion( $DBversion ) ) {
22216     $dbh->do(q{
22217         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22218         ('SkipHoldTrapOnNotForLoanValue','',NULL,'If set, Koha will never trap items for hold with this notforloan value','Integer')
22219     });
22220
22221     NewVersion( $DBversion, 25184, "Items with a negative notforloan status should not be captured for holds");
22222 }
22223
22224 $DBversion = '20.06.00.003';
22225 if( CheckVersion( $DBversion ) ) {
22226     unless ( TableExists( 'tables_settings' ) ) {
22227         $dbh->do(q|
22228             CREATE TABLE tables_settings (
22229                 module varchar(255) NOT NULL,
22230                 page varchar(255) NOT NULL,
22231                 tablename varchar(255) NOT NULL,
22232                 default_display_length smallint(6) NOT NULL DEFAULT 20,
22233                 default_sort_order varchar(255),
22234                 PRIMARY KEY(module (191), page (191), tablename (191) )
22235             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22236         |);
22237     }
22238
22239     NewVersion( $DBversion, 24156, "Add new table tables_settings" );
22240 }
22241
22242 $DBversion = '20.06.00.004';
22243 if( CheckVersion( $DBversion ) ) {
22244     $dbh->do("
22245         DELETE FROM circulation_rules WHERE rule_name='holdallowed' AND rule_value='';
22246     ");
22247     NewVersion( $DBversion, 25851, "Remove holdallowed rule if value is an empty string");
22248 }
22249
22250 $DBversion = '20.06.00.005';
22251 if( CheckVersion( $DBversion ) ) {
22252     $dbh->do( "UPDATE borrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
22253     $dbh->do( "ALTER TABLE borrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
22254     $dbh->do( "UPDATE deletedborrowers SET login_attempts=0 WHERE login_attempts IS NULL" );
22255     $dbh->do( "ALTER TABLE deletedborrowers MODIFY COLUMN login_attempts int(4) NOT NULL DEFAULT 0" );
22256     NewVersion( $DBversion, 24379, "Set login_attempts NOT NULL" );
22257 }
22258
22259 $DBversion = '20.06.00.006';
22260 if( CheckVersion( $DBversion ) ) {
22261     unless( TableExists( 'pseudonymized_transactions' ) ) {
22262         $dbh->do(q|
22263             CREATE TABLE `pseudonymized_transactions` (
22264               `id` INT(11) NOT NULL AUTO_INCREMENT,
22265               `hashed_borrowernumber` VARCHAR(60) NOT NULL,
22266               `has_cardnumber` TINYINT(1) NOT NULL DEFAULT 0,
22267               `title` LONGTEXT,
22268               `city` LONGTEXT,
22269               `state` MEDIUMTEXT default NULL,
22270               `zipcode` varchar(25) default NULL,
22271               `country` MEDIUMTEXT,
22272               `branchcode` varchar(10) NOT NULL default '',
22273               `categorycode` varchar(10) NOT NULL default '',
22274               `dateenrolled` date default NULL,
22275               `sex` varchar(1) default NULL,
22276               `sort1` varchar(80) default NULL,
22277               `sort2` varchar(80) default NULL,
22278               `datetime` datetime default NULL,
22279               `transaction_branchcode` varchar(10) default NULL,
22280               `transaction_type` varchar(16) default NULL,
22281               `itemnumber` int(11) default NULL,
22282               `itemtype` varchar(10) default NULL,
22283               `holdingbranch` varchar(10) default null,
22284               `homebranch` varchar(10) default null,
22285               `location` varchar(80) default NULL,
22286               `itemcallnumber` varchar(255) default NULL,
22287               `ccode` varchar(80) default NULL,
22288               PRIMARY KEY (`id`),
22289               CONSTRAINT `pseudonymized_transactions_ibfk_1` FOREIGN KEY (`categorycode`) REFERENCES `categories` (`categorycode`),
22290               CONSTRAINT `pseudonymized_transactions_borrowers_ibfk_2` FOREIGN KEY (`branchcode`) REFERENCES `branches` (`branchcode`),
22291               CONSTRAINT `pseudonymized_transactions_borrowers_ibfk_3` FOREIGN KEY (`transaction_branchcode`) REFERENCES `branches` (`branchcode`)
22292             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22293         |);
22294     }
22295
22296     $dbh->do(q|
22297         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22298         VALUES ('Pseudonymization','0',NULL,'If enabled patrons and transactions will be copied in a separate table for statistics purpose','YesNo')
22299     |);
22300     $dbh->do(q|
22301         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22302         VALUES ('PseudonymizationPatronFields','','title,city,state,zipcode,country,branchcode,categorycode,dateenrolled,sex,sort1,sort2','Patron fields to copy to the pseudonymized_transactions table','multiple')
22303     |);
22304     $dbh->do(q|
22305         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22306         VALUES ('PseudonymizationTransactionFields','','datetime,transaction_branchcode,transaction_type,itemnumber,itemtype,holdingbranch,homebranch,location,itemcallnumber,ccode','Transaction fields to copy to the pseudonymized_transactions table','multiple')
22307     |);
22308
22309     unless( TableExists( 'pseudonymized_borrower_attributes' ) ) {
22310         $dbh->do(q|
22311             CREATE TABLE pseudonymized_borrower_attributes (
22312               `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, -- Row id field
22313               `transaction_id` int(11) NOT NULL,
22314               `code` varchar(10) NOT NULL,
22315               `attribute` varchar(255) default NULL,
22316               CONSTRAINT `pseudonymized_borrower_attributes_ibfk_1` FOREIGN KEY (`transaction_id`) REFERENCES `pseudonymized_transactions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
22317               CONSTRAINT `anonymized_borrower_attributes_ibfk_2` FOREIGN KEY (`code`) REFERENCES `borrower_attribute_types` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
22318             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22319         |);
22320     }
22321
22322     unless( column_exists('borrower_attribute_types', 'keep_for_pseudonymization') ) {
22323         $dbh->do(q|
22324             ALTER TABLE borrower_attribute_types ADD COLUMN `keep_for_pseudonymization` TINYINT(1) NOT NULL DEFAULT 0 AFTER `class`
22325         |);
22326     }
22327
22328     NewVersion( $DBversion, 24151, "Add pseudonymized_transactions tables and sysprefs for Pseudonymization" );
22329 }
22330
22331 $DBversion = '20.06.00.007';
22332 if( CheckVersion( $DBversion ) ) {
22333     if( !column_exists( 'borrower_attribute_types', 'mandatory' ) ) {
22334         $dbh->do(q|
22335             ALTER TABLE borrower_attribute_types
22336             ADD COLUMN mandatory TINYINT(1) NOT NULL DEFAULT 0
22337             AFTER keep_for_pseudonymization
22338         |);
22339     }
22340
22341     NewVersion( $DBversion, 22844, "Add borrower_attribute_types.mandatory" );
22342 }
22343
22344 $DBversion = '20.06.00.008';
22345 if( CheckVersion( $DBversion ) ) {
22346     $dbh->do( "UPDATE itemtypes SET imageurl = REPLACE (imageurl, '.gif', '.png') WHERE imageurl LIKE 'bridge/%'" );
22347
22348     NewVersion( $DBversion, 23148, "Replace Bridge icons with transparent PNG files" );
22349 }
22350
22351 $DBversion = '20.06.00.009';
22352 if( CheckVersion( $DBversion ) ) {
22353     $dbh->do( q{
22354             INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
22355             VALUES ('ILLHiddenRequestStatuses',NULL,NULL,'ILL statuses that are considered finished and should not be displayed in the ILL module','multiple')
22356     });
22357
22358     NewVersion( $DBversion, 23391, "Hide finished ILL requests" );
22359 }
22360
22361 $DBversion = '20.06.00.010';
22362 if( CheckVersion( $DBversion ) ) {
22363     $dbh->do(q{
22364         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22365         ('NoRefundOnLostReturnedItemsAge','','','Do not refund lost item fees if item is lost for more than this number of days','Integer')
22366     });
22367
22368     NewVersion( $DBversion, 20815, "Add NoRefundOnLostReturnedItemsAge system preference" );
22369 }
22370
22371 $DBversion = '20.06.00.011';
22372 if( CheckVersion( $DBversion ) ) {
22373     unless( column_exists( 'export_format', 'staff_only' ) ) {
22374         $dbh->do(q|
22375             ALTER TABLE export_format
22376                 ADD staff_only TINYINT(1) NOT NULL DEFAULT 0 AFTER used_for,
22377                 ADD KEY `staff_only_idx` (`staff_only`);
22378         |);
22379     }
22380
22381     unless ( index_exists( 'export_format', 'used_for_idx' ) ) {
22382         $dbh->do(q|
22383             ALTER TABLE export_format
22384                 ADD KEY `used_for_idx` (`used_for` (191));
22385         |);
22386     }
22387
22388     NewVersion( $DBversion, 5087, "Add export_format.staff_only" );
22389 }
22390
22391 $DBversion = '20.06.00.012';
22392 if( CheckVersion( $DBversion ) ) {
22393
22394     # get list of installed translations
22395     require C4::Languages;
22396     my @langs;
22397     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22398
22399     foreach my $language ( @$tlangs ) {
22400         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22401             push @langs, $sublanguage->{'rfc4646_subtag'};
22402         }
22403     }
22404
22405     # Get any existing value from the opaccredits system preference
22406     my ($opaccredits) = $dbh->selectrow_array( q|
22407         SELECT value FROM systempreferences WHERE variable='opaccredits';
22408     |);
22409     if( $opaccredits ){
22410         foreach my $lang ( @langs ) {
22411             # If there is a value in the opaccredits preference, insert it into opac_news
22412             $dbh->do("INSERT IGNORE INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "opaccredits_$lang", $opaccredits);
22413         }
22414     }
22415     # Remove the opaccredits system preference
22416     $dbh->do("DELETE FROM systempreferences WHERE variable='opaccredits'");
22417
22418     NewVersion( $DBversion, 23795, "Convert OpacCredits system preference to news block" );
22419 }
22420
22421 $DBversion = '20.06.00.013';
22422 if( CheckVersion( $DBversion ) ) {
22423
22424     # get list of installed translations
22425     require C4::Languages;
22426     my @langs;
22427     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22428
22429     foreach my $language ( @$tlangs ) {
22430         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22431             push @langs, $sublanguage->{'rfc4646_subtag'};
22432         }
22433     }
22434
22435     # Get any existing value from the OpacCustomSearch system preference
22436     my ($OpacCustomSearch) = $dbh->selectrow_array( q|
22437         SELECT value FROM systempreferences WHERE variable='OpacCustomSearch';
22438     |);
22439     if( $OpacCustomSearch ){
22440         foreach my $lang ( @langs ) {
22441             # If there is a value in the OpacCustomSearch preference, insert it into opac_news
22442             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacCustomSearch_$lang", $OpacCustomSearch);
22443         }
22444     }
22445     # Remove the OpacCustomSearch system preference
22446     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacCustomSearch'");
22447
22448     NewVersion( $DBversion, 23795, "Convert OpacCustomSearch system preference to news block" );
22449 }
22450
22451 $DBversion = '20.06.00.014';
22452 if( CheckVersion( $DBversion ) ) {
22453
22454     $dbh->do( "ALTER TABLE opac_news CHANGE lang lang VARCHAR(50) NOT NULL DEFAULT ''" );
22455
22456     NewVersion( $DBversion, 23797, "Extend the opac_news lang column to accommodate longer values" );
22457 }
22458
22459 $DBversion = '20.06.00.015';
22460 if( CheckVersion( $DBversion ) ) {
22461
22462     # get list of installed translations
22463     require C4::Languages;
22464     my @langs;
22465     my $tlangs = C4::Languages::getTranslatedLanguages('opac','bootstrap');
22466
22467     foreach my $language ( @$tlangs ) {
22468         foreach my $sublanguage ( @{$language->{'sublanguages_loop'}} ) {
22469             push @langs, $sublanguage->{'rfc4646_subtag'};
22470         }
22471     }
22472
22473     # Get any existing value from the OpacLoginInstructions system preference
22474     my ($opaclogininstructions) = $dbh->selectrow_array( q|
22475         SELECT value FROM systempreferences WHERE variable='OpacLoginInstructions';
22476     |);
22477     if( $opaclogininstructions ){
22478         foreach my $lang ( @langs ) {
22479             # If there is a value in the OpacLoginInstructions preference, insert it into opac_news
22480             $dbh->do("INSERT INTO opac_news (branchcode, lang, title, content ) VALUES (NULL, ?, '', ?)", undef, "OpacLoginInstructions_$lang", $opaclogininstructions);
22481         }
22482     }
22483     # Remove the OpacLoginInstructions system preference
22484     $dbh->do("DELETE FROM systempreferences WHERE variable='OpacLoginInstructions'");
22485
22486     NewVersion( $DBversion, 23797, "Convert OpacLoginInstructions system preference to news block" );
22487 }
22488
22489 $DBversion = '20.06.00.016';
22490 if( CheckVersion( $DBversion ) ) {
22491
22492     unless ( column_exists('branchtransfers', 'daterequested') ) {
22493         $dbh->do(
22494             qq{
22495                 ALTER TABLE branchtransfers
22496                 ADD
22497                   `daterequested` timestamp NOT NULL default CURRENT_TIMESTAMP
22498                 AFTER
22499                   `itemnumber`
22500               }
22501         );
22502     }
22503
22504     NewVersion( $DBversion, 23092, "Add 'daterequested' field to transfers table" );
22505 }
22506
22507 $DBversion = '20.06.00.017';
22508 if( CheckVersion( $DBversion ) ) {
22509     $dbh->do( "UPDATE systempreferences SET variable='NotesToHide' WHERE variable = 'NotesBlacklist'" );
22510     NewVersion( $DBversion, 25709, "Rename systempreference to NotesToHide");
22511 }
22512
22513 $DBversion = '20.06.00.018';
22514 if( CheckVersion( $DBversion ) ) {
22515     $dbh->do(q|
22516         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22517         (11, 'reopen_closed_invoices', 'Reopen closed invoices')
22518     |);
22519
22520     $dbh->do(q|
22521         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22522         (11, 'edit_invoices', 'Edit invoices')
22523     |);
22524
22525     $dbh->do(q|
22526         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22527         (11, 'delete_baskets', 'Delete baskets')
22528     |);
22529
22530     $dbh->do(q|
22531         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22532         (11, 'delete_invoices', 'Delete invoices')
22533     |);
22534
22535     $dbh->do(q|
22536         INSERT IGNORE INTO permissions (module_bit, code, description) VALUES
22537         (11, 'merge_invoices', 'Merge invoices')
22538     |);
22539
22540     NewVersion( $DBversion, 24157, "Add new permissions reopen_closed_invoices, edit_invoices, delete_invoices, merge_invoices, delete_basket");
22541 }
22542
22543 $DBversion = '20.06.00.019';
22544 if( CheckVersion( $DBversion ) ) {
22545     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('NewsToolEditor','tinymce', 'Choose tool for editing News','tinymce|codemirror','Choice')" );
22546
22547     NewVersion( $DBversion, 22660, "Adds NewsToolEditor system preference");
22548 }
22549
22550 $DBversion = '20.06.00.020';
22551 if( CheckVersion( $DBversion ) ) {
22552     # Remove from the systempreferences table
22553     $dbh->do("DELETE FROM systempreferences WHERE variable = 'GoogleIndicTransliteration'");
22554
22555     NewVersion( $DBversion, 26070, "Remove references to deprecated Google Transliterate API");
22556 }
22557
22558 $DBversion = '20.06.00.021';
22559 if( CheckVersion( $DBversion ) ) {
22560     $dbh->do(q{
22561         UPDATE systempreferences SET options = "callnum|ccode|location|library"
22562         WHERE variable = "OpacItemLocation"
22563     });
22564     NewVersion( $DBversion, 25871, "Add library option to OpacItemLocation");
22565 }
22566
22567 $DBversion = '20.06.00.022';
22568 if( CheckVersion( $DBversion ) ) {
22569     unless ( column_exists('itemtypes', 'parent_type') ) {
22570         $dbh->do(q{
22571             ALTER TABLE itemtypes
22572                 ADD COLUMN parent_type VARCHAR(10) NULL DEFAULT NULL
22573                 AFTER itemtype;
22574
22575         });
22576     }
22577     unless ( foreign_key_exists( 'itemtypes', 'itemtypes_ibfk_1') ){
22578         $dbh->do(q{
22579             ALTER TABLE itemtypes
22580             ADD CONSTRAINT itemtypes_ibfk_1
22581             FOREIGN KEY (parent_type) REFERENCES itemtypes (itemtype)
22582         });
22583     }
22584
22585     NewVersion( $DBversion, 21946, "Add parent type to itemtypes" );
22586 }
22587
22588 $DBversion = '20.06.00.023';
22589 if( CheckVersion( $DBversion ) ) {
22590
22591     my ( $QuoteOfTheDay ) = $dbh->selectrow_array(q|
22592         SELECT value FROM systempreferences WHERE variable='QuoteOfTheDay'
22593     |);
22594     my $options = $QuoteOfTheDay ? 'opac' : '';
22595     $dbh->do( q|
22596         UPDATE systempreferences
22597         SET value = ?,
22598             options = 'intranet,opac',
22599             explanation = 'Enable or disable display of Quote of the Day on the OPAC and staff interface home page',
22600             type = 'multiple'
22601         WHERE variable = 'QuoteOfTheDay'
22602     |, undef, $options );
22603
22604     NewVersion( $DBversion, 16371, "Quote of the Day (QOTD) for the staff interface " );
22605 }
22606
22607 $DBversion = '20.06.00.024';
22608 if( CheckVersion( $DBversion ) ) {
22609
22610     $dbh->do( "UPDATE marc_subfield_structure SET liblibrarian = 'Home library' WHERE liblibrarian = 'Permanent location'
22611         AND tagfield = 952 and tagsubfield = 'a'" );
22612     $dbh->do( "UPDATE marc_subfield_structure SET libopac = 'Home library' WHERE libopac = 'Permanent location'
22613         AND tagfield = 952 and tagsubfield = 'a'" );
22614     $dbh->do( "UPDATE marc_subfield_structure SET liblibrarian = 'Current library' WHERE liblibrarian = 'Current location'
22615         AND tagfield = 952 and tagsubfield = 'b'" );
22616     $dbh->do( "UPDATE marc_subfield_structure SET libopac = 'Current library' WHERE libopac = 'Current location'
22617         AND tagfield = 952 and tagsubfield = 'b'" );
22618
22619     NewVersion( $DBversion, 25867, "Update subfield descriptions for 952\$a and 952\$b");
22620 }
22621
22622 $DBversion = '20.06.00.025';
22623 if( CheckVersion( $DBversion ) ) {
22624
22625     $dbh->do( q{
22626         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES
22627         ('PatronDuplicateMatchingAddFields','surname|firstname|dateofbirth', NULL,'A list of fields separated by "|" to deduplicate patrons when created','Free')
22628     });
22629
22630     NewVersion( $DBversion, 6725, "Adds PatronDuplicateMatchingAddFields system preference");
22631 }
22632
22633 $DBversion = '20.06.00.026';
22634 if (CheckVersion($DBversion)) {
22635     unless (column_exists('accountlines', 'credit_number')) {
22636         $dbh->do('ALTER TABLE accountlines ADD COLUMN credit_number VARCHAR(20) NULL DEFAULT NULL COMMENT "autogenerated number for credits" AFTER debit_type_code');
22637     }
22638
22639     unless (column_exists('account_credit_types', 'credit_number_enabled')) {
22640         $dbh->do(q{
22641             ALTER TABLE account_credit_types
22642             ADD COLUMN credit_number_enabled TINYINT(1) NOT NULL DEFAULT 0
22643                 COMMENT "Is autogeneration of credit number enabled for this credit type"
22644                 AFTER can_be_added_manually
22645         });
22646     }
22647
22648     $dbh->do('INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES(?, ?, ?, ?, ?)', undef, 'AutoCreditNumber', '', '', 'Automatically generate a number for account credits', 'Choice');
22649
22650     NewVersion( $DBversion, 19036, "Add accountlines.credit_number, account_credit_types.credit_number_enabled and syspref AutoCreditNumber" );
22651 }
22652
22653 $DBversion = '20.06.00.027';
22654 if( CheckVersion( $DBversion ) ) {
22655     $dbh->do( "INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type) VALUES('BiblioItemtypeInfo', '0','Control whether biblio level itemtype image displays','0','YesNo')" );
22656
22657     NewVersion( $DBversion, 8732, 'Add new BiblioItemtypeInfo to system preferences' );
22658 }
22659
22660 $DBversion = '20.06.00.028';
22661 if( CheckVersion( $DBversion ) ) {
22662     $dbh->do(q{
22663         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22664         ('DefaultLongOverdueSkipLostStatuses', '', NULL, 'Skip these lost statuses by default in longoverdue.pl', 'Free')
22665     });
22666
22667     NewVersion( $DBversion, 25958, "Allow LongOverdue cron to exclude specified lost values");
22668 }
22669
22670 $DBversion = '20.06.00.029';
22671 if ( CheckVersion( $DBversion ) ) {
22672     $dbh->do(q{
22673         INSERT IGNORE INTO authorised_value_categories( category_name, is_system ) VALUES ('HOLD_CANCELLATION', 0);
22674     });
22675
22676     if ( !column_exists( 'reserves', 'cancellation_reason' ) ) {
22677         $dbh->do(q{
22678             ALTER TABLE reserves ADD COLUMN `cancellation_reason` varchar(80) default NULL AFTER cancellationdate;
22679         });
22680     }
22681
22682     if ( !column_exists( 'old_reserves', 'cancellation_reason' ) ) {
22683         $dbh->do(q{
22684             ALTER TABLE old_reserves ADD COLUMN `cancellation_reason` varchar(80) default NULL AFTER cancellationdate;
22685         });
22686     }
22687
22688     NewVersion( $DBversion, 25534, "Add ability to send an email specifying a reason when canceling a hold");
22689 }
22690
22691 $DBversion = '20.06.00.030';
22692 if ( CheckVersion( $DBversion ) ) {
22693
22694     $dbh->do(q{
22695         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type`) VALUES
22696         ('AutoApprovePatronProfileSettings', '0', '', 'Automatically approve patron profile changes from the OPAC.', 'YesNo');
22697     });
22698
22699     NewVersion( $DBversion, 20057, "Add new system preference 'AutoApprovePatronProfileSettings'");
22700 }
22701
22702 $DBversion = '20.06.00.031';
22703 if( CheckVersion( $DBversion ) ) {
22704
22705     if( !column_exists( 'reserves', 'non_priority' ) ) {
22706         $dbh->do("ALTER TABLE reserves ADD COLUMN `non_priority` tinyint(1) NOT NULL DEFAULT 0 AFTER `item_level_hold`");
22707     }
22708
22709     if( !column_exists( 'old_reserves', 'non_priority' ) ) {
22710         $dbh->do("ALTER TABLE old_reserves ADD COLUMN `non_priority` tinyint(1) NOT NULL DEFAULT 0 AFTER `item_level_hold`");
22711     }
22712
22713     NewVersion( $DBversion, 22789, "Add non_priority column on reserves and old_reserves tables");
22714 }
22715
22716 $DBversion = '20.06.00.032';
22717 if( CheckVersion( $DBversion ) ) {
22718     if( !column_exists( 'items', 'exclude_from_local_holds_priority' ) ) {
22719         $dbh->do(q{
22720             ALTER TABLE `items` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `new_status`
22721         });
22722     }
22723
22724     if( !column_exists( 'deleteditems', 'exclude_from_local_holds_priority' ) ) {
22725         $dbh->do(q{
22726             ALTER TABLE `deleteditems` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `new_status`
22727         });
22728     }
22729
22730     if( !column_exists( 'categories', 'exclude_from_local_holds_priority' ) ) {
22731         $dbh->do(q{
22732             ALTER TABLE `categories` ADD COLUMN `exclude_from_local_holds_priority` tinyint(1) default NULL AFTER `change_password`
22733         });
22734     }
22735     NewVersion( $DBversion, 19889, "Add exclude_from_local_holds_priority column to items, deleteditems and categories tables");
22736 }
22737
22738 $DBversion = '20.06.00.033';
22739 if( CheckVersion( $DBversion ) ) {
22740     if( column_exists( 'opac_news', 'timestamp' ) ) {
22741         $dbh->do(q|
22742             ALTER TABLE opac_news
22743             CHANGE COLUMN timestamp published_on date DEFAULT NULL
22744         |);
22745     }
22746     if( !column_exists( 'opac_news', 'updated_on' ) ) {
22747         $dbh->do(q|
22748             ALTER TABLE opac_news
22749             ADD COLUMN updated_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER published_on
22750         |);
22751     }
22752
22753     $dbh->do(q|
22754         UPDATE letter
22755         SET content = REPLACE(content,?,?)
22756         WHERE content LIKE ?
22757     |, undef, 'opac_news.timestamp', 'opac_news.published_on', '%opac_news.timestamp%' );
22758
22759     NewVersion( $DBversion, 21066, ["Rename column opac_news.timestamp with published_on", "Add new column opac_news.updated_on", "Replace timestamp references in letters table"] );
22760 }
22761
22762 $DBversion = '20.06.00.034';
22763 if( CheckVersion( $DBversion ) ) {
22764     $dbh->do(q|
22765         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
22766         VALUES ('AddressForFailedOverdueNotices', '', NULL, 'Destination email for failed overdue notices. If left empty then it will fallback to the first defined address in the following list: Library ReplyTo, Library Email, ReplytoDefault and KohaAdminEmailAddress', 'free')
22767     |);
22768
22769     NewVersion( $DBversion, 24197, "Add new system preference 'AddressForFailedOverdueNotices'" );
22770 }
22771
22772 $DBversion = '20.06.00.035';
22773 if ( CheckVersion( $DBversion ) ) {
22774     $dbh->do(q{
22775         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
22776         ('EdifactInvoiceImport', 'automatic', 'automatic|manual', "If on, don't auto-import EDI invoices, just keep them in the database with the status 'new'", 'Choice')
22777     });
22778
22779     NewVersion( $DBversion, 23682, "Add new system preference 'EdifactInvoiceImport'" );
22780 }
22781
22782 $DBversion = '20.06.00.036';
22783 if( CheckVersion( $DBversion ) ) {
22784     # Fix the markup in the OPACSearchForTitleIn system preference
22785     $dbh->do("UPDATE systempreferences SET VALUE = replace( value, '</li>', ''), value = REPLACE( value, '<li>', '') WHERE VARIABLE = 'OPACSearchForTitleIn';");
22786
22787     NewVersion( $DBversion, 20168, "Update OPACSearchForTitleIn to work with Bootstrap 4");
22788 }
22789
22790 $DBversion = '20.06.00.037';
22791 if( CheckVersion( $DBversion ) ) {
22792     if( !column_exists( 'categories', 'min_password_length' ) ) {
22793         $dbh->do("ALTER TABLE categories ADD COLUMN `min_password_length` smallint(6) NULL DEFAULT NULL AFTER `change_password` -- set minimum password length for patrons in this category");
22794     }
22795     if( !column_exists( 'categories', 'require_strong_password' ) ) {
22796         $dbh->do("ALTER TABLE categories ADD COLUMN `require_strong_password` TINYINT(1) NULL DEFAULT NULL AFTER `min_password_length` -- set required password strength for patrons in this category");
22797     }
22798
22799     NewVersion( $DBversion, 23816, "Add min_password_length and require_strong_password columns in categories table");
22800 }
22801
22802 $DBversion = '20.06.00.038';
22803 if( CheckVersion( $DBversion ) ) {
22804     $dbh->do( "ALTER TABLE `search_field` MODIFY COLUMN `type` enum('','string','date','number','boolean','sum','isbn','stdno','year') NOT NULL" );
22805     $dbh->do( "UPDATE `search_field` SET type = 'year' WHERE name = 'date-of-publication'" );
22806
22807     NewVersion( $DBversion, 24807, "Add 'year' type to improve sorting behaviour" );
22808 }
22809
22810 $DBversion = '20.06.00.039';
22811 if( CheckVersion( $DBversion ) ) {
22812
22813     if( !column_exists( 'hold_fill_targets', 'reserve_id' ) ) {
22814         $dbh->do( "ALTER TABLE hold_fill_targets ADD COLUMN reserve_id int(11) DEFAULT NULL AFTER item_level_request" );
22815     }
22816
22817     NewVersion( $DBversion, 18958, "Add reserve_id to hold_fill_targets");
22818 }
22819
22820 $DBversion = '20.06.00.040';
22821 if( CheckVersion( $DBversion ) ) {
22822     $dbh->do( "INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('OpacMetaDescription','','','This description will show in search engine results (160 characters).','Textarea');" );
22823
22824     NewVersion( $DBversion, 26454, "Add system preference to set meta description for the OPAC");
22825 }
22826
22827 $DBversion = '20.06.00.041';
22828 if ( CheckVersion($DBversion) ) {
22829
22830     if ( column_exists( 'items', 'paidfor' ) ) {
22831         my ($count) = $dbh->selectrow_array(
22832             q|
22833                 SELECT COUNT(*)
22834                 FROM items
22835                 WHERE paidfor IS NOT NULL AND paidfor <> ""
22836             |
22837         );
22838         if ($count) {
22839             warn "Warning - Cannot remove column items.paidfor. At least one value exists";
22840         }
22841         else {
22842             $dbh->do(q|ALTER TABLE items DROP COLUMN paidfor|);
22843             $dbh->do(q|UPDATE marc_subfield_structure SET kohafield = '' WHERE kohafield = 'items.paidfor'|);
22844         }
22845     }
22846
22847     if ( column_exists( 'deleteditems', 'paidfor' ) ) {
22848         my ($count) = $dbh->selectrow_array(
22849             q|
22850                 SELECT COUNT(*)
22851                 FROM deleteditems
22852                 WHERE paidfor IS NOT NULL AND paidfor <> ""
22853             |
22854         );
22855         if ($count) {
22856             warn "Warning - Cannot remove column deleteditems.paidfor. At least one value exists";
22857         }
22858         else {
22859             $dbh->do(q|ALTER TABLE deleteditems DROP COLUMN paidfor|);
22860         }
22861     }
22862
22863     NewVersion( $DBversion, 26268, "Remove items.paidfor field" );
22864 }
22865
22866 $DBversion = '20.06.00.042';
22867 if( CheckVersion( $DBversion ) ) {
22868     unless ( column_exists('letter', 'updated_on') ) {
22869         $dbh->do(q|
22870             ALTER TABLE letter ADD COLUMN updated_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER lang
22871         |);
22872     }
22873
22874     NewVersion( $DBversion, 25776, "Add letter.updated_on");
22875 }
22876
22877 $DBversion = '20.06.00.043';
22878 if( CheckVersion( $DBversion ) ) {
22879     $dbh->do(q{
22880         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('CircConfirmItemParts', '0', NULL, 'Require staff to confirm that all parts of an item are present at checkin/checkout.', 'YesNo')
22881     });
22882
22883     NewVersion( $DBversion, 25261, "Add CircConfirmItemParts syspref");
22884 }
22885
22886 $DBversion = '20.06.00.044';
22887 if( CheckVersion( $DBversion ) ) {
22888
22889     unless (TableExists('smtp_servers')) {
22890
22891         # Create the table
22892         $dbh->do(q{
22893             CREATE TABLE `smtp_servers` (
22894                 `id` INT(11) NOT NULL AUTO_INCREMENT,
22895                 `name` VARCHAR(80) NOT NULL,
22896                 `host` VARCHAR(80) NOT NULL DEFAULT 'localhost',
22897                 `port` INT(11) NOT NULL DEFAULT 25,
22898                 `timeout` INT(11) NOT NULL DEFAULT 120,
22899                 `ssl_mode` ENUM('disabled', 'ssl', 'starttls') NOT NULL,
22900                 `user_name` VARCHAR(80) NULL DEFAULT NULL,
22901                 `password` VARCHAR(80) NULL DEFAULT NULL,
22902                 `debug` TINYINT(1) NOT NULL DEFAULT 0,
22903                 PRIMARY KEY (`id`),
22904                 KEY `host_idx` (`host`)
22905             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22906         });
22907     }
22908
22909     unless (TableExists('library_smtp_servers')) {
22910         $dbh->do(q{
22911             CREATE TABLE `library_smtp_servers` (
22912                 `id` INT(11) NOT NULL AUTO_INCREMENT,
22913                 `library_id` VARCHAR(10) NOT NULL,
22914                 `smtp_server_id` INT(11) NOT NULL,
22915                 PRIMARY KEY (`id`),
22916                 UNIQUE KEY `library_id_idx` (`library_id`),
22917                 KEY `smtp_server_id_idx` (`smtp_server_id`),
22918                 CONSTRAINT `library_smtp_servers_library_fk` FOREIGN KEY (`library_id`) REFERENCES `branches` (`branchcode`) ON DELETE CASCADE ON UPDATE CASCADE,
22919                 CONSTRAINT `library_smtp_servers_smtp_servers_fk` FOREIGN KEY (`smtp_server_id`) REFERENCES `smtp_servers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
22920             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22921         });
22922     }
22923
22924     $dbh->do(q{
22925         INSERT IGNORE INTO permissions
22926             (module_bit, code, description)
22927         VALUES ( 3, 'manage_smtp_servers', 'Manage SMTP servers configuration');
22928     });
22929
22930     NewVersion( $DBversion, 22343, "Add SMTP configuration options");
22931 }
22932
22933 $DBversion = '20.06.00.045';
22934 if( CheckVersion( $DBversion ) ) {
22935
22936     unless ( TableExists('background_jobs') ) {
22937         $dbh->do(q|
22938             CREATE TABLE background_jobs (
22939                 id INT(11) NOT NULL AUTO_INCREMENT,
22940                 status VARCHAR(32),
22941                 progress INT(11),
22942                 size INT(11),
22943                 borrowernumber INT(11),
22944                 type VARCHAR(64),
22945                 data TEXT,
22946                 enqueued_on DATETIME DEFAULT NULL,
22947                 started_on DATETIME DEFAULT NULL,
22948                 ended_on DATETIME DEFAULT NULL,
22949                 PRIMARY KEY (id)
22950             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
22951         |);
22952     }
22953
22954     $dbh->do(qq{
22955         INSERT IGNORE permissions (module_bit, code, description)
22956         VALUES
22957         (3, 'manage_background_jobs', 'Manage background jobs')
22958     });
22959
22960     NewVersion( $DBversion, 22417, "Add new table background_jobs");
22961 }
22962
22963 $DBversion = '20.06.00.046';
22964 if( CheckVersion( $DBversion ) ) {
22965     unless ( foreign_key_exists( 'alert', 'alert_ibfk_1' ) ) {
22966         $dbh->do(q|
22967             DELETE a FROM alert a
22968             LEFT JOIN borrowers b ON a.borrowernumber=b.borrowernumber
22969             WHERE b.borrowernumber IS NULL
22970         |);
22971         $dbh->do(q|
22972             ALTER TABLE alert
22973             ADD CONSTRAINT alert_ibfk_1 FOREIGN KEY (borrowernumber) REFERENCES borrowers (borrowernumber) ON UPDATE CASCADE ON DELETE CASCADE
22974         |);
22975     }
22976     NewVersion( $DBversion, 13535, "Add FK constraint on borrowernumber to alert table" );
22977 }
22978
22979 $DBversion = '20.06.00.047';
22980 if ( CheckVersion($DBversion) ) {
22981
22982     #Get value from AllowPurchaseSuggestionBranchChoice system preference
22983     my ($allowpurchasesuggestionbranchchoice) =
22984       C4::Context->preference('AllowPurchaseSuggestionBranchChoice');
22985     if ($allowpurchasesuggestionbranchchoice) {
22986         $dbh->do(q{
22987             INSERT IGNORE INTO systempreferences
22988             (`variable`, `value`, `options`, `explanation`, `type`)
22989             VALUES
22990             ('OPACSuggestionUnwantedFields','branch', NULL,'Define the hidden fields for a patron purchase suggestions made via OPAC.','multiple');
22991         });
22992     }
22993     else {
22994         $dbh->do(q{
22995             INSERT IGNORE INTO systempreferences
22996             (`variable`, `value`, `options`, `explanation`, `type`)
22997             VALUES
22998             ('OPACSuggestionUnwantedFields','', NULL,'Define the hidden fields for a patron purchase suggestions made via OPAC.','multiple');
22999         });
23000     }
23001
23002     #Remove the  AllowPurchaseSuggestionBranchChoice system preference
23003     $dbh->do(
23004         "DELETE FROM systempreferences WHERE variable='AllowPurchaseSuggestionBranchChoice'"
23005     );
23006     NewVersion( $DBversion, 23420, "Allow configuration of hidden fields on the suggestion form in OPAC" );
23007 }
23008
23009 $DBversion = '20.06.00.048';
23010 if( CheckVersion( $DBversion ) ) {
23011     $dbh->do(q{
23012         DELETE FROM circulation_rules WHERE
23013         rule_name IN ('holdallowed','hold_fulfillment_policy','returnbranch') AND
23014         rule_value = ''
23015     });
23016     NewVersion( $DBversion, 26529, "Remove blank default branch rules");
23017 }
23018
23019 $DBversion = '20.06.00.049';
23020 if( CheckVersion( $DBversion ) ) {
23021
23022     if( TableExists('biblioimages') && !column_exists( 'biblioimages', 'itemnumber' ) ) {
23023         $dbh->do(q|
23024             ALTER TABLE biblioimages
23025             ADD COLUMN itemnumber INT(11) DEFAULT NULL
23026             AFTER biblionumber;
23027         |);
23028         $dbh->do(q|
23029             ALTER TABLE biblioimages
23030             ADD FOREIGN KEY bibliocoverimage_fk2 (`itemnumber`) REFERENCES `items` (`itemnumber`) ON DELETE CASCADE ON UPDATE CASCADE
23031         |);
23032         $dbh->do(q|
23033             ALTER TABLE biblioimages MODIFY biblionumber INT(11) DEFAULT NULL
23034         |)
23035     }
23036
23037     if( !TableExists('cover_images') ) {
23038         $dbh->do(q|
23039             ALTER TABLE biblioimages RENAME cover_images
23040         |);
23041     }
23042
23043     NewVersion( $DBversion, '26145', ["Add the biblioimages.itemnumber column", "Rename table biblioimages with cover_images"] );
23044 }
23045
23046 $DBversion = '20.06.00.050';
23047 if ( CheckVersion($DBversion) ) {
23048     $dbh->do(q{
23049         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23050         ('NoIssuesChargeGuarantorsWithGuarantees','','','Define maximum amount withstanding before checkouts are blocked including guarantors and their other guarantees','Integer');
23051     });
23052
23053     NewVersion( $DBversion, 19382, "Add ability to block guarantees based on fees owed by guarantor and other guarantee - new system preference 'NoIssuesChargeGuarantorsWithGuarantees'");
23054 }
23055
23056 $DBversion = '20.06.00.051';
23057 if( CheckVersion( $DBversion ) ) {
23058     $dbh->do(q{
23059         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23060         ('HoldsNeedProcessingSIP', '0', NULL, 'Require staff to check-in before hold is set to waiting state', 'YesNo' )
23061     });
23062
23063     NewVersion( $DBversion, 12556, "Add new syspref HoldsNeedProcessingSIP");
23064 }
23065
23066 $DBversion = '20.06.00.052';
23067 if ( CheckVersion($DBversion) ) {
23068     $dbh->do(q{
23069         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('OAI-PMH:AutoUpdateSetEmbedItemData', '0', '', 'Embed item information when automatically updating OAI sets. Requires OAI-PMH:AutoUpdateSets syspref to be enabled', 'YesNo')
23070     });
23071
23072     $dbh->do(q{
23073         UPDATE systempreferences SET explanation = 'Automatically update OAI sets when a bibliographic or item record is created or updated' WHERE variable = 'OAI-PMH:AutoUpdateSets'
23074     });
23075
23076     NewVersion( $DBversion, 25460, "Update OAI set when adding/editing/deleting item records" );
23077 }
23078
23079 $DBversion = '20.06.00.053';
23080 if( CheckVersion( $DBversion ) ) {
23081     $dbh->do( "UPDATE systempreferences SET explanation='Define which baskets a user is allowed to view: their own only, any within their branch, or all' WHERE variable='AcqViewBaskets'" );
23082     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set checkouts to be visible to their guarantor' WHERE variable='AllowPatronToSetCheckoutsVisibilityForGuarantor'" );
23083     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, the patron can set fines to be visible to their guarantor' WHERE variable='AllowPatronToSetFinesVisibilityForGuarantor'" );
23084     $dbh->do( "UPDATE systempreferences SET explanation='If on, and a patron is logged into the OPAC, items from their home library will be emphasized and shown first in search results and item details.' WHERE variable='HighlightOwnItemsOnOPAC'" );
23085     $dbh->do( "UPDATE systempreferences SET explanation='If ON, the next user will automatically get the last searches in their history' WHERE variable='LoadSearchHistoryToTheFirstLoggedUser'" );
23086     $dbh->do( "UPDATE systempreferences SET explanation='If enabled, any patron attempting to register themselves via the OPAC will be required to verify themselves via email to activate their account.' WHERE variable='PatronSelfRegistrationVerifyByEmail'" );
23087
23088     NewVersion( $DBversion, 26569, "Use gender neutral pronouns in system preference explanations" );
23089 }
23090
23091 $DBversion = '20.06.00.054';
23092 if ( CheckVersion($DBversion) ) {
23093
23094     $dbh->do(
23095         qq{
23096             INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
23097             VALUES
23098               ('OVERPAYMENT', 'Overpayment refund', 0, 1)
23099         }
23100     );
23101
23102     $dbh->do(
23103         qq{
23104             INSERT IGNORE INTO account_offset_types ( type ) VALUES ('Overpayment');
23105         }
23106     );
23107
23108     $dbh->do(
23109         qq{
23110             UPDATE accountlines SET credit_type_code = 'OVERPAYMENT' WHERE credit_type_code = 'CREDIT' AND description = 'Overpayment refund'
23111         }
23112     );
23113
23114     NewVersion( $DBversion, 25596, "Add OVERPAYMENT credit type" );
23115 }
23116
23117 $DBversion = '20.06.00.055';
23118 if( CheckVersion( $DBversion ) ) {
23119     my $count_missing_budget = $dbh->selectrow_arrayref(q|
23120         SELECT COUNT(*) FROM aqbudgets ab WHERE NOT EXISTS
23121             (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23122             AND budget_period_id IS NOT NULL;
23123
23124     |);
23125
23126     my $message = "";
23127     if($count_missing_budget->[0] > 0) {
23128         $dbh->do(q|
23129             CREATE TABLE _bug_18050_aqbudgets AS
23130             SELECT * FROM aqbudgets ab WHERE NOT EXISTS
23131                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23132         |);
23133
23134         $dbh->do(q|
23135             UPDATE aqbudgets ab SET budget_period_id = NULL
23136             WHERE NOT EXISTS
23137                 (SELECT * FROM aqbudgetperiods abp WHERE abp.budget_period_id = ab.budget_period_id)
23138         |);
23139         $message = ". There are $count_missing_budget->[0] funds in your database that are not linked
23140         to a valid budget. Setting invalid budget id (budget_period_id) to null. The table _bug_18050_aqbudgets
23141         was created with original data. Please check that table and place valid ids in aqbudget table as soon as possible."
23142
23143     }
23144
23145     if ( !foreign_key_exists( 'aqbudgets', 'aqbudgetperiods_ibfk_1' ) ) {
23146         $dbh->do(q|
23147             ALTER TABLE aqbudgets ADD CONSTRAINT `aqbudgetperiods_ibfk_1` FOREIGN KEY (`budget_period_id`) REFERENCES `aqbudgetperiods` (`budget_period_id`) ON UPDATE CASCADE ON DELETE CASCADE
23148         |);
23149         NewVersion( $DBversion, 18050, "Add FK constraint on aqbudgets.budget_period_id$message");
23150     } else {
23151         NewVersion( $DBversion, 18050, "FK constraint on aqbudgets.budget already exists");
23152     }
23153
23154 }
23155
23156 $DBversion = '20.06.00.056';
23157 if( CheckVersion( $DBversion ) ) {
23158
23159     $dbh->do("DROP INDEX title ON import_biblios");
23160     $dbh->do("DROP INDEX isbn ON import_biblios");
23161     $dbh->do("ALTER TABLE import_biblios MODIFY title LONGTEXT");
23162     $dbh->do("ALTER TABLE import_biblios MODIFY author LONGTEXT");
23163     $dbh->do("ALTER TABLE import_biblios MODIFY isbn LONGTEXT");
23164     $dbh->do("ALTER TABLE import_biblios MODIFY issn LONGTEXT");
23165     $dbh->do("CREATE INDEX title ON import_biblios (title(191));");
23166     $dbh->do("CREATE INDEX isbn ON import_biblios (isbn(191));");
23167
23168     NewVersion( $DBversion, 26853, "Update import_biblios columns and indexes" );
23169 }
23170
23171 $DBversion = '20.06.00.057';
23172 if( CheckVersion( $DBversion ) ) {
23173     $dbh->do(q{
23174         INSERT IGNORE INTO `systempreferences` (`variable`, `value`, `options`, `explanation`, `type`) VALUES
23175             ('ArticleRequestsMandatoryFieldsItemOnly', '', NULL, 'Comma delimited list of required fields for bibs where article requests rule = ''item_only''', 'multiple')
23176     });
23177     $dbh->do(q{
23178         DELETE FROM systempreferences WHERE variable = "ArticleRequestsMandatoryFieldsItemsOnly"
23179     });
23180
23181     NewVersion( $DBversion, 26638, "Add missing system preference ArticleRequestsMandatoryFieldsItemOnly");
23182 }
23183
23184 $DBversion = '20.06.00.058';
23185 if( CheckVersion( $DBversion ) ) {
23186
23187     # Adding the ON DELETE CASCASE ON UPDATE CASCADE, in case it's missing (from 9016 - 3.15.00.039)
23188     $dbh->do( q{
23189         ALTER TABLE letter DROP FOREIGN KEY message_transport_type_fk
23190     } );
23191
23192     $dbh->do( q{
23193         ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
23194     } );
23195
23196     $dbh->do(q{
23197         UPDATE message_transport_types SET message_transport_type = "itiva" WHERE message_transport_type = "phone"
23198     });
23199
23200     NewVersion( $DBversion, 25333, q{Change message transport type for Talking Tech from "phone" to "itiva"});
23201 }
23202
23203 $DBversion = '20.06.00.059';
23204 if( CheckVersion( $DBversion ) ) {
23205
23206     if( !column_exists( 'search_field', 'mandatory' ) ) {
23207         $dbh->do( "ALTER TABLE search_field ADD COLUMN mandatory tinyint(1) NULL DEFAULT NULL AFTER opac" );
23208     }
23209
23210     NewVersion( $DBversion, 19482, "Add mandatory column to search_field for ES mapping" );
23211 }
23212
23213 $DBversion = '20.06.00.060';
23214 if( CheckVersion( $DBversion ) ) {
23215     $dbh->do(q{
23216         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23217         ('PhoneNotification','0',NULL,'If ON, enables generation of phone notifications to be sent by plugins','YesNo')
23218     });
23219
23220     $dbh->do(q{
23221         INSERT IGNORE INTO message_transport_types (message_transport_type) VALUES ('phone')
23222     });
23223
23224     $dbh->do(q{
23225         INSERT IGNORE INTO `message_transports`
23226         (`message_attribute_id`, `message_transport_type`, `is_digest`, `letter_module`, `letter_code`)
23227         VALUES
23228         (1, 'phone',       0, 'circulation', 'DUE'),
23229         (1, 'phone',       1, 'circulation', 'DUEDGST'),
23230         (2, 'phone',       0, 'circulation', 'PREDUE'),
23231         (2, 'phone',       1, 'circulation', 'PREDUEDGST'),
23232         (4, 'phone',       0, 'reserves',    'HOLD'),
23233         (5, 'phone',       0, 'circulation', 'CHECKIN'),
23234         (6, 'phone',       0, 'circulation', 'CHECKOUT');
23235     });
23236
23237     NewVersion( $DBversion, 25334, "Add generic 'phone' message transport type");
23238 }
23239
23240 $DBversion = '20.06.00.061';
23241 if( CheckVersion( $DBversion ) ) {
23242     if ( !column_exists( 'reserves', 'desk_id' ) ) {
23243         $dbh->do(q{
23244              ALTER TABLE reserves ADD COLUMN desk_id INT(11) DEFAULT NULL AFTER branchcode,
23245              ADD KEY desk_id (`desk_id`),
23246              ADD CONSTRAINT `reserves_ibfk_6` FOREIGN KEY (`desk_id`) REFERENCES `desks` (`desk_id`) ON DELETE SET NULL ON UPDATE CASCADE ;
23247         });
23248         $dbh->do(q{
23249              ALTER TABLE old_reserves ADD COLUMN desk_id INT(11) DEFAULT NULL AFTER branchcode,
23250              ADD KEY `old_desk_id` (`desk_id`);
23251         });
23252     }
23253
23254     NewVersion( $DBversion, 24412, "Attach waiting reserve to desk" );
23255 }
23256
23257 $DBversion = '20.06.00.062';
23258 if( CheckVersion( $DBversion ) ) {
23259     $dbh->do( "UPDATE circulation_rules SET rule_name = 'lostreturn' WHERE rule_name = 'refund'" );
23260     $dbh->do( "UPDATE circulation_rules SET rule_value = 'refund' WHERE rule_name = 'lostreturn' AND rule_value = 1" );
23261
23262     NewVersion( $DBversion, 23091, "Update refund rules");
23263 }
23264
23265 $DBversion = '20.06.00.063';
23266 if( CheckVersion( $DBversion ) ) {
23267     $dbh->do(q{INSERT IGNORE INTO circulation_rules (branchcode, categorycode, itemtype, rule_name, rule_value) VALUES (NULL, NULL, NULL, 'decreaseloanholds', NULL) });
23268
23269     NewVersion( $DBversion, 14866, "Add decreaseloanholds circulation rule" );
23270 }
23271
23272 $DBversion = '20.06.00.064';
23273 if ( CheckVersion($DBversion) ) {
23274
23275     $dbh->do(q{
23276         INSERT IGNORE INTO account_credit_types (code, description, can_be_added_manually, is_system)
23277         VALUES ('CANCELLATION', 'Cancelled charge', 0, 1)
23278     });
23279
23280     $dbh->do(q{
23281         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('CANCELLATION');
23282     });
23283
23284     NewVersion( $DBversion, 24603, "Add CANCELLATION credit_type_code" );
23285 }
23286
23287 $DBversion = '20.06.00.065';
23288 if( CheckVersion( $DBversion ) ) {
23289     if( !column_exists( 'issues', 'issuer_id' ) ) {
23290         $dbh->do( q| ALTER TABLE issues ADD issuer_id INT(11) DEFAULT NULL AFTER borrowernumber | );
23291     }
23292     if (!foreign_key_exists( 'issues', 'issues_ibfk_borrowers_borrowernumber' )) {
23293         $dbh->do( q| ALTER TABLE issues ADD CONSTRAINT `issues_ibfk_borrowers_borrowernumber` FOREIGN KEY (`issuer_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE | );
23294     }
23295     if( !column_exists( 'old_issues', 'issuer_id' ) ) {
23296         $dbh->do( q| ALTER TABLE old_issues ADD issuer_id INT(11) DEFAULT NULL AFTER borrowernumber | );
23297     }
23298     if (!foreign_key_exists( 'old_issues', 'old_issues_ibfk_borrowers_borrowernumber' )) {
23299         $dbh->do( q| ALTER TABLE old_issues ADD CONSTRAINT `old_issues_ibfk_borrowers_borrowernumber` FOREIGN KEY (`issuer_id`) REFERENCES `borrowers` (`borrowernumber`) ON DELETE SET NULL ON UPDATE CASCADE | );
23300     }
23301
23302     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('RecordStaffUserOnCheckout', '0', 'If enabled, when an item is checked out, the user who checked out the item is recorded', '', 'YesNo'); | );
23303
23304     NewVersion( $DBversion, 23916, [ "Add new [old_]issues.issuer DB fields", "Add new syspref RecordStaffUserOnCheckout" ] );
23305 }
23306
23307 $DBversion = '20.06.00.066';
23308 if( CheckVersion( $DBversion ) ) {
23309     if( !column_exists( 'branches', 'branchillemail' ) ) {
23310         $dbh->do( q| ALTER TABLE branches ADD branchillemail LONGTEXT AFTER branchemail | );
23311     }
23312     # Add new sysprefs
23313     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('ILLDefaultStaffEmail', '', 'Fallback email address for staff ILL notices to be sent to in the absence of a branch address', NULL, 'Free'); | );
23314     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('ILLSendStaffNotices', NULL, 'Send these ILL notices to staff', NULL, 'multiple'); | );
23315     # Add new notices
23316     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_PICKUP_READY', '', 'ILL request ready for pickup', 0, "Interlibrary loan request ready for pickup", "Dear [% borrower.firstname %] [% borrower.surname %],\n\nThe Interlibrary loans request number [% illrequest.illrequest_id %] you placed for:\n\n- [% ill_bib_title %] - [% ill_bib_author %]\n\nis ready for pick up from [% branch.branchname %].\n\nKind Regards\n\n[% branch.branchname %]\n[% branch.branchaddress1 %]\n[% branch.branchaddress2 %]\n[% branch.branchaddress3 %]\n[% branch.branchcity %]\n[% branch.branchstate %]\n[% branch.branchzip %]\n[% branch.branchphone %]\n[% branch.branchillemail %]\n[% branch.branchemail %]", 'email', 'default'); | );
23317     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_REQUEST_UNAVAIL', '', 'ILL request unavailable', 0, "Interlibrary loan request unavailable", "Dear [% borrower.firstname %] [% borrower.surname %],\n\nThe Interlibrary loans request number [% illrequest.illrequest_id %] you placed for\n\n- [% ill_bib_title %] - [% ill_bib_author %]\n\nis unfortunately unavailable.\n\nKind Regards\n\n[% branch.branchname %]\n[% branch.branchaddress1 %]\n[% branch.branchaddress2 %]\n[% branch.branchaddress3 %]\n[% branch.branchcity %]\n[% branch.branchstate %]\n[% branch.branchzip %]\n[% branch.branchphone %]\n[% branch.branchillemail %]\n[% branch.branchemail %]", 'email', 'default'); | );
23318     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_REQUEST_CANCEL', '', 'ILL request cancelled', 0, "Interlibrary loan request cancelled", "The patron for interlibrary loans request [% illrequest.illrequest_id %], with the following details, has requested cancellation of this ILL request:\n\n[% ill_full_metadata %]", 'email', 'default'); | );
23319     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_REQUEST_MODIFIED', '', 'ILL request modified', 0, "Interlibrary loan request modified", "The patron for interlibrary loans request [% illrequest.illrequest_id %], with the following details, has modified this ILL request:\n\n[% ill_full_metadata %]", 'email', 'default'); | );
23320     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_PARTNER_REQ', '', 'ILL request to partners', 0, "Interlibrary loan request to partners", "Dear Sir/Madam,\n\nWe would like to request an interlibrary loan for a title matching the following description:\n\n[% ill_full_metadata %]\n\nPlease let us know if you are able to supply this to us.\n\nKind Regards\n\n[% branch.branchname %]\n[% branch.branchaddress1 %]\n[% branch.branchaddress2 %]\n[% branch.branchaddress3 %]\n[% branch.branchcity %]\n[% branch.branchstate %]\n[% branch.branchzip %]\n[% branch.branchphone %]\n[% branch.branchillemail %]\n[% branch.branchemail %]", 'email', 'default'); | );
23321     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_PICKUP_READY', '', 'ILL request ready for pickup', 0, "Interlibrary loan request ready for pickup", "Dear [% borrower.firstname %] [% borrower.surname %],\n\nThe Interlibrary loans request number [% illrequest.illrequest_id %] you placed for:\n\n- [% ill_bib_title %] - [% ill_bib_author %]\n\nis ready for pick up from [% branch.branchname %].\n\nKind Regards\n\n[% branch.branchname %]\n[% branch.branchaddress1 %]\n[% branch.branchaddress2 %]\n[% branch.branchaddress3 %]\n[% branch.branchcity %]\n[% branch.branchstate %]\n[% branch.branchzip %]\n[% branch.branchphone %]\n[% branch.branchillemail %]\n[% branch.branchemail %]", 'sms', 'default'); | );
23322     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_REQUEST_UNAVAIL', '', 'ILL request unavailable', 0, "Interlibrary loan request unavailable", "Dear [% borrower.firstname %] [% borrower.surname %],\n\nThe Interlibrary loans request number [% illrequest.illrequest_id %] you placed for\n\n- [% ill_bib_title %] - [% ill_bib_author %]\n\nis unfortunately unavailable.\n\nKind Regards\n\n[% branch.branchname %]\n[% branch.branchaddress1 %]\n[% branch.branchaddress2 %]\n[% branch.branchaddress3 %]\n[% branch.branchcity %]\n[% branch.branchstate %]\n[% branch.branchzip %]\n[% branch.branchphone %]\n[% branch.branchillemail %]\n[% branch.branchemail %]", 'sms', 'default'); | );
23323     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_REQUEST_CANCEL', '', 'ILL request cancelled', 0, "Interlibrary loan request cancelled", "The patron for interlibrary loans request [% illrequest.illrequest_id %], with the following details, has requested cancellation of this ILL request:\n\n[% ill_full_metadata %]", 'sms', 'default'); | );
23324     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_REQUEST_MODIFIED', '', 'ILL request modified', 0, "Interlibrary loan request modified", "The patron for interlibrary loans request [% illrequest.illrequest_id %], with the following details, has modified this ILL request:\n\n[% ill_full_metadata %]", 'sms', 'default'); | );
23325     $dbh->do( q| INSERT IGNORE INTO letter(module, code, branchcode, name, is_html, title, content, message_transport_type, lang) VALUES ('ill', 'ILL_PARTNER_REQ', '', 'ILL request to partners', 0, "Interlibrary loan request to partners", "Dear Sir/Madam,\n\nWe would like to request an interlibrary loan for a title matching the following description:\n\n[% ill_full_metadata %]\n\nPlease let us know if you are able to supply this to us.\n\nKind Regards\n\n[% branch.branchname %]\n[% branch.branchaddress1 %]\n[% branch.branchaddress2 %]\n[% branch.branchaddress3 %]\n[% branch.branchcity %]\n[% branch.branchstate %]\n[% branch.branchzip %]\n[% branch.branchphone %]\n[% branch.branchillemail %]\n[% branch.branchemail %]", 'sms', 'default'); | );
23326     # Add patron messaging preferences
23327     $dbh->do( q| INSERT IGNORE INTO message_attributes (message_name, takes_days) VALUES ('Ill_ready', 0); | );
23328     my $ready_id = $dbh->last_insert_id(undef, undef, 'message_attributes', undef);
23329     if (defined $ready_id) {
23330         $dbh->do( qq(INSERT IGNORE INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES ($ready_id, 'email', 0, 'ill', 'ILL_PICKUP_READY');) );
23331         $dbh->do( qq(INSERT IGNORE INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES ($ready_id, 'sms', 0, 'ill', 'ILL_PICKUP_READY');) );
23332         $dbh->do( qq(INSERT IGNORE INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES ($ready_id, 'phone', 0, 'ill', 'ILL_PICKUP_READY');) );
23333     }
23334     $dbh->do( q| INSERT IGNORE INTO message_attributes (message_name, takes_days) VALUES ('Ill_unavailable', 0); | );
23335     my $unavail_id = $dbh->last_insert_id(undef, undef, 'message_attributes', undef);
23336     if (defined $unavail_id) {
23337         $dbh->do( qq(INSERT IGNORE INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES ($unavail_id, 'email', 0, 'ill', 'ILL_REQUEST_UNAVAIL');) );
23338         $dbh->do( qq(INSERT IGNORE INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES ($unavail_id, 'sms', 0, 'ill', 'ILL_REQUEST_UNAVAIL');) );
23339         $dbh->do( qq(INSERT IGNORE INTO message_transports (message_attribute_id, message_transport_type, is_digest, letter_module, letter_code) VALUES ($unavail_id, 'phone', 0, 'ill', 'ILL_REQUEST_UNAVAIL');) );
23340     }
23341
23342     NewVersion( $DBversion, 22818, "Add ILL notices" );
23343 }
23344
23345 $DBversion = '20.06.00.067';
23346 if( CheckVersion( $DBversion ) ) {
23347     $dbh->do(q{
23348         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23349         ('OPACHoldsHistory','0','','If ON, enables display of Patron Holds History in OPAC','YesNo')
23350     });
23351
23352     NewVersion( $DBversion, 20936, "Add new system preference OPACHoldsHistory");
23353 }
23354
23355 $DBversion = '20.06.00.068';
23356 if( CheckVersion( $DBversion ) ) {
23357   if( !TableExists( 'import_batch_profiles' ) ) {
23358     $dbh->do(q{
23359       CREATE TABLE `import_batch_profiles` ( -- profile for batches of marc records to be imported
23360         `id` int(11) NOT NULL auto_increment, -- unique identifier and primary key
23361         `name` varchar(100) NOT NULL, -- name of this profile
23362         `matcher_id` int(11) default NULL, -- the id of the match rule used (matchpoints.matcher_id)
23363         `template_id` int(11) default NULL, -- the id of the marc modification template
23364         `overlay_action` varchar(50) default NULL, -- how to handle duplicate records
23365         `nomatch_action` varchar(50) default NULL, -- how to handle records where no match is found
23366         `item_action` varchar(50) default NULL, -- what to do with item records
23367         `parse_items` tinyint(1) default NULL, -- should items be parsed
23368         `record_type` varchar(50) default NULL, -- type of record in the batch
23369         `encoding` varchar(50) default NULL, -- file encoding
23370         `format` varchar(50) default NULL, -- marc format
23371         `comments` LONGTEXT, -- any comments added when the file was uploaded
23372         PRIMARY KEY (`id`),
23373         UNIQUE KEY `u_import_batch_profiles__name` (`name`)
23374       ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
23375     });
23376   }
23377
23378   if(!column_exists('import_batches', 'profile_id')) {
23379     $dbh->do(q{
23380       ALTER TABLE import_batches ADD COLUMN `profile_id` int(11) default NULL AFTER comments
23381     });
23382
23383     $dbh->do(q{
23384       ALTER TABLE import_batches ADD CONSTRAINT `import_batches_ibfk_1` FOREIGN KEY (`profile_id`) REFERENCES `import_batch_profiles` (`id`) ON DELETE SET NULL ON UPDATE SET NULL
23385     });
23386   }
23387
23388   NewVersion( $DBversion, 23019, "Add import_batch_profiles table and profile_id column in import_batches" );
23389 }
23390
23391 $DBversion = '20.06.00.069';
23392 if( CheckVersion( $DBversion ) ) {
23393     my ($count) = $dbh->selectrow_array(
23394         q|
23395             SELECT COUNT(*)
23396             FROM circulation_rules
23397             WHERE rule_name = 'unseen_renewals_allowed'
23398         |
23399     );
23400     if ($count == 0) {
23401         $dbh->do( q|
23402             INSERT INTO circulation_rules (rule_name, rule_value)
23403             VALUES ('unseen_renewals_allowed', '')
23404         | );
23405     }
23406
23407     if( !column_exists( 'issues', 'unseen_renewals' ) ) {
23408         $dbh->do( q| ALTER TABLE issues ADD unseen_renewals TINYINT(4) DEFAULT 0 NOT NULL AFTER renewals | );
23409     }
23410     if( !column_exists( 'old_issues', 'unseen_renewals' ) ) {
23411         $dbh->do( q| ALTER TABLE old_issues ADD unseen_renewals TINYINT(4) DEFAULT 0 NOT NULL AFTER renewals | );
23412     }
23413
23414     $dbh->do( q| INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type) VALUES ('UnseenRenewals', '0', 'If enabled, a renewal can be recorded as "unseen" by the library and count against the borrowers unseen renewals limit', '', 'YesNo'); | );
23415
23416     NewVersion( $DBversion, 24083, ["Add circulation_rules 'unseen_renewals_allowed'", "Add issues.unseen_renewals & old_issues.unseen_renewals)", "Add new system preference UnseenRenewals"] );
23417 }
23418
23419 $DBversion = '20.11.00.000';
23420 if( CheckVersion( $DBversion ) ) {
23421     NewVersion( $DBversion, "", "Koha 20.11.00 release" );
23422 }
23423
23424 $DBversion = '20.12.00.000';
23425 if( CheckVersion( $DBversion ) ) {
23426     NewVersion( $DBversion, "", "Sorry, this is my first life, I am still learning!" );
23427 }
23428
23429 $DBversion = '20.12.00.001';
23430 if( CheckVersion( $DBversion ) ) {
23431     $dbh->do(q{
23432         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` ) VALUES
23433        ('ElasticsearchCrossFields', '1', '', 'Enable "cross_fields" option for searches using Elastic search.', 'YesNo')
23434     });
23435     NewVersion( $DBversion, 27252, "Add ElasticsearchCrossFields system preference");
23436 }
23437
23438 $DBversion = '20.12.00.002';
23439 if( CheckVersion( $DBversion ) ) {
23440     $dbh->do(q{UPDATE systempreferences SET `type` = 'Choice' WHERE `variable` = 'UsageStatsCountry'});
23441     NewVersion( $DBversion, 27351, "Set type for UsageStatsCountry to Choice");
23442 }
23443
23444 $DBversion = '20.12.00.003';
23445 if( CheckVersion( $DBversion ) ) {
23446     $dbh->do(q{UPDATE systempreferences SET `type` = 'Choice' WHERE `variable` = 'Mana'});
23447     NewVersion( $DBversion, 27349, "Update type for Mana system preference to Choice");
23448 }
23449
23450 $DBversion = '20.12.00.004';
23451 if( CheckVersion( $DBversion ) ) {
23452     $dbh->do(q{UPDATE systempreferences set variable="TaxRates" WHERE variable="gist"});
23453     NewVersion( $DBversion, 27485, "Rename system preference 'gist' to 'TaxRates'");
23454 }
23455
23456 $DBversion = '20.12.00.005';
23457 if( CheckVersion( $DBversion ) ) {
23458     $dbh->do(q{UPDATE systempreferences set variable="OPACLanguages" WHERE variable="opaclanguages"});
23459     NewVersion( $DBversion, 27491, "Rename system preference 'opaclanguages' to 'OPACLanguages'");
23460 }
23461
23462 $DBversion = '20.12.00.006';
23463 if( CheckVersion( $DBversion ) ) {
23464     $dbh->do(q{UPDATE systempreferences SET variable="OPACComments" WHERE variable="reviewson" });
23465     NewVersion( $DBversion, 27487, "Rename system preference 'reviewson' to 'OPACComments");
23466 }
23467
23468 $DBversion = '20.12.00.007';
23469 if( CheckVersion( $DBversion ) ) {
23470     $dbh->do(q{UPDATE systempreferences set variable="CSVDelimiter" WHERE variable="delimiter"});
23471     NewVersion( $DBversion, 27486, "Renaming system preference 'delimiter' to 'CSVDelimiter'");
23472 }
23473
23474 $DBversion = '20.12.00.008';
23475 if( CheckVersion( $DBversion ) ) {
23476     $dbh->do(q{
23477         UPDATE systempreferences
23478         SET options = "claim_returned|batchmod|moredetail|cronjob|additem|pendingreserves|onpayment"
23479         WHERE variable = "MarkLostItemsAsReturned";
23480     });
23481     NewVersion( $DBversion, 25552, "Add missing Claims Returned option to MarkLostItemsAsReturned");
23482 }
23483
23484 $DBversion = '20.12.00.009';
23485 if( CheckVersion( $DBversion ) ) {
23486     $dbh->do( "UPDATE systempreferences SET variable = 'UseICUStyleQUotes' WHERE variable = 'UseICU'" );
23487     NewVersion( $DBversion, 27581, "Rename system preference 'UseICU' to 'UseICUStyleQuotes'");
23488 }
23489
23490 $DBversion = '20.12.00.010';
23491 if( CheckVersion( $DBversion ) ) {
23492     $dbh->do( q{
23493         DELETE FROM systempreferences WHERE variable="OpacGroupResults"
23494     });
23495
23496     NewVersion( $DBversion, 20410, "Remove OpacGroupResults");
23497 }
23498
23499 $DBversion = '20.12.00.011';
23500 if ( CheckVersion($DBversion) ) {
23501     $dbh->do( q{
23502         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23503         VALUES
23504         ('OPACShibOnly','0','If ON enables shibboleth only authentication for the opac','','YesNo'),
23505         ('staffShibOnly','0','If ON enables shibboleth only authentication for the staff client','','YesNo')
23506     } );
23507     NewVersion( $DBversion, 18506, "Add OPACShibOnly and staffShibOnly system preferences" );
23508 }
23509
23510 $DBversion = '20.12.00.012';
23511 if( CheckVersion( $DBversion ) ) {
23512     my $category_exists = $dbh->selectrow_array("SELECT count(category_name) FROM authorised_value_categories WHERE category_name='UPLOAD'");
23513     my $description;
23514     if( $category_exists ){
23515         $description = "The UPLOAD authorized value category exists. Update the 'is_system' value to 1.";
23516         $dbh->do( "UPDATE authorised_value_categories SET is_system = 1 WHERE category_name = 'UPLOAD'" );
23517     } else {
23518         $description = "The UPLOAD authorized value category does not exist. Create it.";
23519         $dbh->do( "INSERT IGNORE INTO authorised_value_categories (category_name, is_system) VALUES ('UPLOAD', 1)" );
23520     }
23521
23522     NewVersion( $DBversion, 27598, ["Add UPLOAD as a built-in system authorized value category", $description] );
23523 }
23524
23525 $DBversion = '20.12.00.013';
23526 if( CheckVersion( $DBversion ) ) {
23527     $dbh->do(q{
23528          INSERT IGNORE INTO systempreferences
23529          (variable, value, explanation, options, type) VALUES
23530          ('DefaultSaveRecordFileID', 'biblionumber', 'Defines whether the advanced cataloging editor will use the bibliographic record number or control number field to populate the name of the save file.', 'biblionumber|controlnumber', 'Choice')
23531     });
23532     NewVersion( $DBversion, 24108, "Add system preference DefaultSaveRecordFileID");
23533 }
23534
23535 $DBversion = '20.12.00.014';
23536 if( CheckVersion( $DBversion ) ) {
23537
23538     sanitize_zero_date('aqorders', 'datecancellationprinted');
23539     sanitize_zero_date('old_issues', 'returndate');
23540
23541     NewVersion( $DBversion, 7806, "Remove remaining possible 0000-00-00 values");
23542 }
23543
23544 $DBversion = '20.12.00.015';
23545 if( CheckVersion( $DBversion ) ) {
23546     $dbh->do( "UPDATE search_marc_to_field SET sort = 1 WHERE sort IS NULL" );
23547     $dbh->do( "ALTER TABLE search_marc_to_field MODIFY COLUMN sort tinyint(1) DEFAULT 1 NOT NULL COMMENT 'Sort defaults to 1 (Yes) and creates sort fields in the index, 0 (no) will prevent this'" );
23548     NewVersion( $DBversion, 27316, "In Elastisearch mappings convert NULL (Undef) for sort to 1 (Yes)");
23549 }
23550
23551 $DBversion = '20.12.00.016';
23552 if( CheckVersion( $DBversion ) ) {
23553
23554     unless ( column_exists( 'marc_subfield_structure', 'display_order' ) ) {
23555         $dbh->do(q{
23556             ALTER TABLE marc_subfield_structure
23557             ADD COLUMN display_order INT(2) NOT NULL DEFAULT 0 AFTER maxlength
23558         });
23559     }
23560
23561     unless ( column_exists( 'auth_subfield_structure', 'display_order' ) ) {
23562         $dbh->do(q{
23563             ALTER TABLE auth_subfield_structure
23564             ADD COLUMN display_order INT(2) NOT NULL DEFAULT 0 AFTER defaultvalue
23565         });
23566     }
23567
23568     NewVersion( $DBversion, 8976, "Allow setting a default sequence of subfields in cataloguing editor" );
23569 }
23570
23571 $DBversion = '20.12.00.017';
23572 if( CheckVersion( $DBversion ) ) {
23573     $dbh->do(q|
23574         INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23575         VALUES ('CheckPrevCheckoutDelay','0', 'Maximum number of days that will trigger a warning if the patron has borrowed that item in the past when CheckPrevCheckout is enabled. Disabled if 0 or empty.', NULL, 'free')
23576     |);
23577
23578     NewVersion( $DBversion, 26937, "Add CheckPrevCheckoutDelay system preference)" );
23579 }
23580
23581 $DBversion = '20.12.00.018';
23582 if( CheckVersion( $DBversion ) ) {
23583
23584     $dbh->do(q|
23585         UPDATE items
23586         LEFT JOIN issues ON issues.itemnumber=items.itemnumber
23587         SET items.onloan=CAST(issues.date_due AS DATE)
23588         WHERE items.onloan IS NULL AND issues.issue_id IS NOT NULL
23589     |);
23590
23591     NewVersion( $DBversion, 27808, "Adjust items.onloan if needed" );
23592 }
23593
23594 $DBversion = '20.12.00.019';
23595 if( CheckVersion( $DBversion ) ) {
23596
23597     if( !column_exists( 'branchtransfers', 'datecancelled' ) ) {
23598         $dbh->do(q|
23599             ALTER TABLE `branchtransfers`
23600             ADD COLUMN `datecancelled` datetime default NULL AFTER `datearrived`
23601         |);
23602     }
23603
23604     if( !column_exists( 'branchtransfers', 'cancellation_reason' ) ) {
23605         $dbh->do(q|
23606             ALTER TABLE `branchtransfers`
23607             ADD COLUMN `cancellation_reason` ENUM('Manual', 'StockrotationAdvance', 'StockrotationRepatriation', 'ReturnToHome', 'ReturnToHolding', 'RotatingCollection', 'Reserve', 'LostReserve', 'CancelReserve') DEFAULT NULL AFTER `reason`
23608         |);
23609     }
23610
23611     NewVersion( $DBversion, 26057, "Add datecancelled field to branchtransfers");
23612 }
23613
23614 $DBversion = '20.12.00.020';
23615 if ( CheckVersion($DBversion) ) {
23616
23617     # Update daterequested from datesent for stockrotation
23618     $dbh->do(q|
23619             UPDATE `branchtransfers`
23620             SET
23621               `daterequested` = `datesent`,
23622               `datesent` = NULL
23623             WHERE `reason` LIKE 'Stockrotation%'
23624             AND   `datearrived` IS NULL
23625     |);
23626
23627     NewVersion( $DBversion, 24446, "Update stockrotation 'daterequested' field in transfers table" );
23628 }
23629
23630 $DBversion = '20.12.00.021';
23631 if( CheckVersion( $DBversion ) ) {
23632     $dbh->do(q{
23633         UPDATE systempreferences SET type="Free" WHERE variable="OverDriveClientSecret" OR variable="RecordedBooksClientSecret"
23634     });
23635     $dbh->do(q{
23636         UPDATE systempreferences SET type="integer" WHERE variable="UsageStats"
23637     });
23638     $dbh->do(q{
23639         UPDATE systempreferences
23640         SET value="0"
23641         WHERE ( ( type = "YesNo" AND ( value NOT IN ( "1", "0" ) OR value IS NULL ) ) )
23642     });
23643
23644     NewVersion( $DBversion, 22824, "Update syspref values for YesNo");
23645 }
23646
23647 $DBversion = '20.12.00.022';
23648 if( CheckVersion( $DBversion ) ) {
23649     $dbh->do(q{ INSERT IGNORE INTO letter (module, code, branchcode, name, is_html, title, content, message_transport_type) VALUES
23650         ('circulation','CHECKINSLIP','','Checkin slip',1,'Checkin slip',
23651 "<h3>[% branch.branchname %]</h3>
23652 Checked in items for [% borrower.title %] [% borrower.firstname %] [% borrower.initials %] [% borrower.surname %] <br />
23653 ([% borrower.cardnumber %]) <br />
23654
23655 [% today | $KohaDates %]<br />
23656
23657 <h4>Checked in today</h4>
23658 [% FOREACH checkin IN old_checkouts %]
23659 [% SET item = checkin.item %]
23660 <p>
23661 [% item.biblio.title %] <br />
23662 Barcode: [% item.barcode %] <br />
23663 </p>
23664 [% END %]",
23665         'print')
23666     });
23667
23668     NewVersion( $DBversion, 12224, "Add CHECKINSLIP notice" );
23669 }
23670
23671 $DBversion = '20.12.00.023';
23672 if( CheckVersion( $DBversion ) ) {
23673
23674     $dbh->do(q{
23675         UPDATE systempreferences
23676         SET value=REPLACE(value, '|', ',')
23677         WHERE variable="OPACHoldsIfAvailableAtPickupExceptions"
23678            OR variable="BatchCheckoutsValidCategories"
23679     });
23680     NewVersion( $DBversion, 27652, "Separate values for OPACHoldsIfAvailableAtPickupExceptions and BatchCheckoutsValidCategories with comma");
23681 }
23682
23683 $DBversion = '20.12.00.024';
23684 if( CheckVersion( $DBversion ) ) {
23685
23686     $dbh->do( q{
23687         INSERT IGNORE INTO letter (module, code, name, title, content, message_transport_type) VALUES ('circulation', 'AUTO_RENEWALS_DGST', 'Notification on auto renewals', 'Auto renewals (Digest)',
23688         "Dear [% borrower.firstname %] [% borrower.surname %],
23689         [% IF error %]
23690             There were [% error %] items that were not renewed.
23691         [% END %]
23692         [% IF success %]
23693             There were [% success %] items that were renewed.
23694         [% END %]
23695         [% FOREACH checkout IN checkouts %]
23696             [% checkout.item.biblio.title %] : [% checkout.item.barcode %]
23697             [% IF !checkout.auto_renew_error %]
23698                 was renewed until [% checkout.date_due | $KohaDates as_due_date => 1%]
23699             [% ELSIF checkout.auto_renew_error == 'too_many' %]
23700                 You have reached the maximum number of checkouts possible.
23701             [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
23702                 This item is on hold for another patron.
23703             [% ELSIF checkout.auto_renew_error == 'restriction' %]
23704                 You are currently restricted.
23705             [% ELSIF checkout.auto_renew_error == 'overdue' %]
23706                 You have overdue items.
23707             [% ELSIF checkout.auto_renew_error == 'auto_too_late' %]
23708                 It's too late to renew this item.
23709             [% ELSIF checkout.auto_renew_error == 'auto_too_much_oweing' %]
23710                 Your total unpaid fines are too high.
23711             [% ELSIF checkout.auto_renew_error == 'too_unseen' %]
23712                 This item must be renewed at the library.
23713             [% END %]
23714         [% END %]
23715         ", 'email');
23716     });
23717
23718     $dbh->do( q{
23719         INSERT IGNORE INTO `message_attributes`
23720             (`message_attribute_id`, message_name, `takes_days`)
23721         VALUES (9, 'Auto_Renewals', 0)
23722     });
23723
23724     $dbh->do( q{
23725         INSERT IGNORE INTO `message_transports`
23726             (`message_attribute_id`, `message_transport_type`, `is_digest`, `letter_module`, `letter_code`)
23727         VALUES  (9, 'email', 0, 'circulation', 'AUTO_RENEWALS'),
23728                 (9, 'sms', 0, 'circulation', 'AUTO_RENEWALS'),
23729                 (9, 'email', 1, 'circulation', 'AUTO_RENEWALS_DGST'),
23730                 (9, 'sms', 1, 'circulation', 'AUTO_RENEWALS_DGST')
23731     });
23732
23733      $dbh->do(q{
23734          INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
23735          VALUES ('AutoRenewalNotices','cron','cron|preferences|never','How should Koha determine whether to end autorenewal notices','Choice')
23736      });
23737
23738     NewVersion( $DBversion, 18532, 'Messaging preferences for auto renewals' );
23739 }
23740
23741 $DBversion = '20.12.00.025';
23742 if( CheckVersion( $DBversion ) ) {
23743
23744     $dbh->do(q|
23745         INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type)
23746         VALUES ('ChargeFinesOnClosedDays', '0', NULL, 'Charge fines on days the library is closed.', 'YesNo')
23747     |);
23748
23749     NewVersion( $DBversion, 27835, "Add new system preference ChargeFinesOnClosedDays");
23750 }
23751
23752 $DBversion = '20.12.00.026';
23753 if( CheckVersion( $DBversion ) ) {
23754
23755     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('DefaultHoldExpirationdate','0','','Automatically set default expiration date for holds','YesNo') });
23756     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('DefaultHoldExpirationdatePeriod','0','','How long into the future default expiration date is set to be.','integer') });
23757     $dbh->do(q{INSERT IGNORE INTO systempreferences (variable,value,options,explanation,type) VALUES ('DefaultHoldExpirationdateUnitOfTime','days','days|months|years','Which unit of time is used when setting the default expiration date. ','choice') });
23758
23759     NewVersion( $DBversion, 26498, "Bug 26498 - Add option to set a default expire date for holds at reservation time");
23760 }
23761
23762 $DBversion = '20.12.00.027';
23763 if( CheckVersion( $DBversion ) ) {
23764
23765     $dbh->do(q{
23766         UPDATE circulation_rules
23767         SET
23768             rule_value = CASE
23769                 WHEN rule_value='0' THEN 'not_allowed'
23770                 WHEN rule_value='1' THEN 'from_home_library'
23771                 WHEN rule_value='2' THEN 'from_any_library'
23772                 WHEN rule_value='3' THEN 'from_local_hold_group'
23773             END
23774         WHERE rule_name='holdallowed' AND rule_value >= 0 AND rule_value <= 3;
23775     });
23776
23777     NewVersion( $DBversion, 27069, "Change holdallowed values from numbers to strings");
23778 }
23779
23780 $DBversion = '20.12.00.028';
23781 if ( CheckVersion($DBversion) ) {
23782
23783     if ( !column_exists( 'letter', 'id' ) ) {
23784         $dbh->do(q{
23785             ALTER TABLE letter DROP PRIMARY KEY
23786         });
23787         $dbh->do(q{
23788             ALTER TABLE letter ADD COLUMN `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
23789         });
23790         $dbh->do(q{
23791             ALTER TABLE letter ADD UNIQUE KEY letter_uniq_1 (`module`,`code`,`branchcode`,`message_transport_type`,`lang`)
23792         });
23793     }
23794
23795     $dbh->do(q{
23796         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23797         VALUES ('NoticesLog','0',NULL,'If enabled, log changes to notice templates','YesNo')
23798     });
23799
23800     NewVersion( $DBversion, 14233, "Add id field to letter table" );
23801 }
23802
23803 $DBversion = '20.12.00.029';
23804 if( CheckVersion( $DBversion ) ) {
23805     $dbh->do("ALTER TABLE problem_reports MODIFY content TEXT NOT NULL");
23806
23807     NewVersion( $DBversion, 27726, "Increase field size for problem_reports.content");
23808 }
23809
23810 $DBversion = '20.12.00.030';
23811 if( CheckVersion( $DBversion ) ) {
23812     $dbh->do(q|
23813         INSERT IGNORE INTO systempreferences ( `variable`, `value`, `options`, `explanation`, `type` )
23814         VALUES ('LockExpiredDelay','','','Delay for locking expired patrons (empty means no locking)','Integer')
23815     |);
23816
23817     NewVersion( $DBversion, 21549, "Add new system preference LockExpiredDelay");
23818 }
23819
23820 $DBversion = '20.12.00.031';
23821 if( CheckVersion( $DBversion ) ) {
23822     $dbh->do(q{
23823         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23824         VALUES ('Reference_NFL_Statuses','1|2',NULL,'Contains not for loan statuses considered as available for reference','Free')
23825     });
23826
23827     NewVersion( $DBversion, 21260, "Add new system preference Reference_NFL_Statuses");
23828 }
23829
23830 $DBversion = '20.12.00.032';
23831 if( CheckVersion( $DBversion ) ) {
23832     $dbh->do(q{
23833         INSERT IGNORE INTO letter
23834         (module,code,branchcode,name,is_html,title,content,message_transport_type,lang)
23835         VALUES ('reserves','HOLD_REMINDER','','Waiting hold reminder',0,'You have waiting holds.','Dear [% borrower.firstname %] [% borrower.surname %],\r\n\r\nThe following holds are waiting at [% branch.branchname %]:\r\n\\r\n[% FOREACH hold IN holds %]\r\n    [% hold.biblio.title %] : waiting since [% hold.waitingdate | $KohaDates %]\r\n[% END %]','email','default')
23836     });
23837
23838     NewVersion( $DBversion, 15986, "Add sample HOLD_REMINDER notice");
23839 }
23840
23841 $DBversion = '20.12.00.033';
23842 if( CheckVersion( $DBversion ) ) {
23843     my $debar = $dbh->selectall_arrayref(q|
23844         SELECT d.borrowernumber, GROUP_CONCAT(comment SEPARATOR '\n') AS comment
23845         FROM borrower_debarments d
23846         LEFT JOIN borrowers b ON b.borrowernumber=d.borrowernumber
23847         WHERE ( b.debarredcomment IS NULL OR b.debarredcomment = "" ) AND ( expiration > CURRENT_DATE() OR expiration IS NULL )
23848         GROUP BY d.borrowernumber
23849     |, { Slice => {} });
23850
23851
23852     my $update_sth = $dbh->prepare(q|
23853         UPDATE borrowers
23854         SET debarredcomment=?
23855         WHERE borrowernumber=?
23856     |);
23857     for my $d ( @$debar ) {
23858         $update_sth->execute($d->{comment}, $d->{borrowernumber});
23859     }
23860
23861     NewVersion( $DBversion, 26940, "Put in sync borrowers.debarredcomment with comments from borrower_debarments");
23862 }
23863
23864 $DBversion = '20.12.00.034';
23865 if( CheckVersion( $DBversion ) ) {
23866
23867     $dbh->do(q{
23868         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type)
23869         VALUES ('casServerVersion', '2', '2|3', 'Version of the CAS server Koha will connect to.', 'Choice');
23870     });
23871
23872     NewVersion( $DBversion, 20854, "Add new system preference casServerVersion");
23873 }
23874
23875 $DBversion = '20.12.00.035';
23876 if( CheckVersion( $DBversion ) ) {
23877     if( !column_exists( 'itemtypes', 'automatic_checkin' ) ) {
23878         $dbh->do(q{
23879             ALTER TABLE itemtypes
23880                 ADD COLUMN `automatic_checkin` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'If automatic checkin is enabled for items of this type' AFTER `searchcategory`
23881         });
23882     }
23883
23884     NewVersion( $DBversion, 23207, "Add automatic_checkin to itemtypes table");
23885 }
23886
23887 $DBversion = '20.12.00.036';
23888 if( CheckVersion( $DBversion ) ) {
23889     $dbh->do(q{
23890         ALTER TABLE club_holds_to_patron_holds
23891         MODIFY COLUMN error_code
23892         ENUM ( 'damaged', 'ageRestricted', 'itemAlreadyOnHold',
23893             'tooManyHoldsForThisRecord', 'tooManyReservesToday',
23894             'tooManyReserves', 'notReservable', 'cannotReserveFromOtherBranches',
23895             'libraryNotFound', 'libraryNotPickupLocation', 'cannotBeTransferred',
23896             'noReservesAllowed'
23897         )
23898     });
23899
23900     NewVersion( $DBversion, 16787, "Add noReservesAllowed to club holds error codes");
23901 }
23902
23903 $DBversion = '20.12.00.037';
23904 if( CheckVersion( $DBversion ) ) {
23905     $dbh->do( q{
23906         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
23907         VALUES ('AcquisitionLog', '0', 'If enabled, log acquisition activity', '', 'YesNo');
23908     });
23909
23910     NewVersion( $DBversion, 23971, "Add new system preference AcquisitionLog");
23911 }
23912
23913 $DBversion = '20.12.00.038';
23914 if( CheckVersion( $DBversion ) ) {
23915
23916     # Add 'ItemLost' to reserves cancellation_reason enum
23917     $dbh->do(
23918         q{
23919             ALTER TABLE
23920                 `branchtransfers`
23921             MODIFY COLUMN
23922                 `cancellation_reason` enum(
23923                     'Manual',
23924                     'StockrotationAdvance',
23925                     'StockrotationRepatriation',
23926                     'ReturnToHome',
23927                     'ReturnToHolding',
23928                     'RotatingCollection',
23929                     'Reserve',
23930                     'LostReserve',
23931                     'CancelReserve',
23932                     'ItemLost'
23933                 )
23934             AFTER `comments`
23935           }
23936     );
23937
23938     NewVersion( $DBversion, 27281, "Add 'ItemLost' to branchtransfers.cancellation_reason enum");
23939 }
23940
23941 $DBversion = '20.12.00.039';
23942 if( CheckVersion( $DBversion ) ) {
23943
23944     $dbh->do(
23945         q{
23946             ALTER TABLE
23947                 `branchtransfers`
23948             MODIFY COLUMN
23949                 `reason` enum(
23950                     'Manual',
23951                     'StockrotationAdvance',
23952                     'StockrotationRepatriation',
23953                     'ReturnToHome',
23954                     'ReturnToHolding',
23955                     'RotatingCollection',
23956                     'Reserve',
23957                     'LostReserve',
23958                     'CancelReserve',
23959                     'TransferCancellation'
23960                 )
23961             AFTER `comments`
23962           }
23963     );
23964
23965     NewVersion( $DBversion, 12362, "Add 'TransferCancellation' to branchtransfers.reason enum");
23966 }
23967
23968 $DBversion = '20.12.00.040';
23969 if( CheckVersion( $DBversion ) ) {
23970     $dbh->do(
23971         q{
23972             INSERT IGNORE INTO account_debit_types (
23973               code,
23974               description,
23975               can_be_invoiced,
23976               can_be_sold,
23977               default_amount,
23978               is_system
23979             )
23980             VALUES
23981               ('VOID', 'Credit has been voided', 0, 0, NULL, 1)
23982         }
23983     );
23984
23985     $dbh->do(q{
23986         INSERT IGNORE INTO account_offset_types ( type ) VALUES ('VOID');
23987     });
23988
23989     NewVersion( $DBversion, 27971, "Add VOID debit type code");
23990 }
23991
23992 $DBversion = '20.12.00.041';
23993 if ( CheckVersion($DBversion) ) {
23994
23995     # ACCOUNT_CREDIT UPDATES
23996     # backup existing notice to action_logs
23997     my $credit_arr = $dbh->selectall_arrayref(q{SELECT lang FROM letter WHERE code = 'ACCOUNT_CREDIT'}, { Slice => {} });
23998     my $c_sth = $dbh->prepare(q{
23999       INSERT INTO action_logs ( timestamp, module, action, object, info, interface )
24000       SELECT NOW(), 'NOTICES', 'UPGRADE', id, content, 'cli'
24001       FROM letter
24002       WHERE lang = ? AND code = 'ACCOUNT_CREDIT'
24003     });
24004
24005     for my $c ( @{$credit_arr} ) {
24006         $c_sth->execute( $c->{lang} );
24007     }
24008
24009     # replace notice with default
24010     my $c_notice = q{
24011 [% USE Price %]
24012 [% PROCESS 'accounts.inc' %]
24013 <table>
24014 [% IF ( LibraryName ) %]
24015  <tr>
24016     <th colspan="4" class="centerednames">
24017         <h3>[% LibraryName | html %]</h3>
24018     </th>
24019  </tr>
24020 [% END %]
24021  <tr>
24022     <th colspan="4" class="centerednames">
24023         <h2><u>Fee receipt</u></h2>
24024     </th>
24025  </tr>
24026  <tr>
24027     <th colspan="4" class="centerednames">
24028         <h2>[% Branches.GetName( credit.patron.branchcode ) | html %]</h2>
24029     </th>
24030  </tr>
24031  <tr>
24032     <th colspan="4">
24033         Received with thanks from  [% credit.patron.firstname | html %] [% credit.patron.surname | html %] <br />
24034         Card number: [% credit.patron.cardnumber | html %]<br />
24035     </th>
24036  </tr>
24037   <tr>
24038     <th>Date</th>
24039     <th>Description of charges</th>
24040     <th>Note</th>
24041     <th>Amount</th>
24042  </tr>
24043
24044  <tr class="highlight">
24045     <td>[% credit.date | $KohaDates %]</td>
24046     <td>
24047       [% PROCESS account_type_description account=credit %]
24048       [%- IF credit.description %], [% credit.description | html %][% END %]
24049     </td>
24050     <td>[% credit.note | html %]</td>
24051     <td class="credit">[% credit.amount | $Price %]</td>
24052  </tr>
24053
24054 <tfoot>
24055   <tr>
24056     <td colspan="3">Total outstanding dues as on date: </td>
24057     [% IF ( credit.patron.account.balance >= 0 ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% credit.patron.account.balance | $Price %]</td>
24058   </tr>
24059 </tfoot>
24060 </table>
24061     };
24062
24063     $dbh->do(q{UPDATE letter SET content = ?, is_html = 1 WHERE code = 'ACCOUNT_CREDIT'}, undef, $c_notice);
24064
24065     # ACCOUNT_DEBIT UPDATES
24066     # backup existing notice to action_logs
24067     my $debit_arr = $dbh->selectall_arrayref(
24068         "SELECT lang FROM letter WHERE code = 'ACCOUNT_DEBIT'", { Slice => {} });
24069     my $d_sth = $dbh->prepare(q{
24070       INSERT INTO action_logs ( timestamp, module, action, object, info, interface )
24071       SELECT NOW(), 'NOTICES', 'UPGRADE', id, content, 'cli'
24072       FROM letter
24073       WHERE lang = ? AND code = 'ACCOUNT_DEBIT'
24074     });
24075
24076     for my $d ( @{$debit_arr} ) {
24077         $d_sth->execute( $d->{lang} );
24078     }
24079
24080     # replace notice with default
24081     my $d_notice = q{
24082 [% USE Price %]
24083 [% PROCESS 'accounts.inc' %]
24084 <table>
24085   [% IF ( LibraryName ) %]
24086     <tr>
24087       <th colspan="5" class="centerednames">
24088         <h3>[% LibraryName | html %]</h3>
24089       </th>
24090     </tr>
24091   [% END %]
24092
24093   <tr>
24094     <th colspan="5" class="centerednames">
24095       <h2><u>INVOICE</u></h2>
24096     </th>
24097   </tr>
24098   <tr>
24099     <th colspan="5" class="centerednames">
24100       <h2>[% Branches.GetName( debit.patron.branchcode ) | html %]</h2>
24101     </th>
24102   </tr>
24103   <tr>
24104     <th colspan="5" >
24105       Bill to: [% debit.patron.firstname | html %] [% debit.patron.surname | html %] <br />
24106       Card number: [% debit.patron.cardnumber | html %]<br />
24107     </th>
24108   </tr>
24109   <tr>
24110     <th>Date</th>
24111     <th>Description of charges</th>
24112     <th>Note</th>
24113     <th style="text-align:right;">Amount</th>
24114     <th style="text-align:right;">Amount outstanding</th>
24115   </tr>
24116
24117   <tr class="highlight">
24118     <td>[% debit.date | $KohaDates%]</td>
24119     <td>
24120       [% PROCESS account_type_description account=debit %]
24121       [%- IF debit.description %], [% debit.description | html %][% END %]
24122     </td>
24123     <td>[% debit.note | html %]</td>
24124     <td class="debit">[% debit.amount | $Price %]</td>
24125     <td class="debit">[% debit.amountoutstanding | $Price %]</td>
24126   </tr>
24127
24128   [% IF ( tendered ) %]
24129     <tr>
24130       <td colspan="3">Amount tendered: </td>
24131       <td>[% tendered | $Price %]</td>
24132     </tr>
24133     <tr>
24134       <td colspan="3">Change given: </td>
24135       <td>[% change | $Price %]</td>
24136     </tr>
24137   [% END %]
24138
24139   <tfoot>
24140     <tr>
24141       <td colspan="4">Total outstanding dues as on date: </td>
24142       [% IF ( debit.patron.account.balance <= 0 ) %]<td class="credit">[% ELSE %]<td class="debit">[% END %][% debit.patron.account.balance | $Price %]</td>
24143     </tr>
24144   </tfoot>
24145 </table>
24146     };
24147     $dbh->do(q{UPDATE letter SET content = ?, is_html = 1 WHERE code = 'ACCOUNT_DEBIT'}, undef, $d_notice);
24148
24149     NewVersion( $DBversion, 26734, ["Update notices to use defaults", "WARNING - ACCOUNT_DEBIT and ACCOUNT_CREDIT slip templates have been replaced. Backups have been made to the action logs for your reference."] );
24150 }
24151
24152 $DBversion = '20.12.00.042';
24153 if( CheckVersion( $DBversion ) ) {
24154     unless( foreign_key_exists( 'collections_tracking', 'collectionst_ibfk_1' ) ) {
24155         $dbh->do(q{
24156             DELETE FROM collections_tracking WHERE colId NOT IN ( SELECT colId FROM collections )
24157         });
24158         $dbh->do(q{
24159             ALTER TABLE collections_tracking
24160             ADD CONSTRAINT `collectionst_ibfk_1` FOREIGN KEY (`colId`) REFERENCES `collections` (`colId`) ON DELETE CASCADE ON UPDATE CASCADE
24161         });
24162     }
24163
24164     NewVersion( $DBversion, 17202, "Add FK constraint for collection to collections_tracking");
24165 }
24166
24167 $DBversion = '20.12.00.043';
24168 if( CheckVersion( $DBversion ) ) {
24169     $dbh->do(q{
24170         UPDATE letter SET
24171         content = REPLACE(content, "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due as_due_date => 1 %]" , "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]")
24172         WHERE code = 'AUTO_RENEWALS';
24173     });
24174
24175     NewVersion( $DBversion, 28258, "Update AUTO_RENEWAL content");
24176 }
24177
24178 $DBversion = '20.12.00.044';
24179 if( CheckVersion( $DBversion ) ) {
24180     $dbh->do(q{
24181         UPDATE language_subtag_registry SET description = 'Ukrainian' WHERE subtag='uk' and type='language' and description='Ukranian'
24182     });
24183     $dbh->do(q{
24184         UPDATE language_descriptions SET description = 'Ukrainian' WHERE subtag='uk' and type='language' and lang='en' and description='Ukranian'
24185     });
24186
24187     NewVersion( $DBversion, 28244, "Fix Ukrainian typo in English");
24188 }
24189
24190 $DBversion = '20.12.00.045';
24191 if( CheckVersion( $DBversion ) ) {
24192     $dbh->do(q{
24193         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('SearchLimitLibrary', 'both', 'homebranch|holdingbranch|both', "When limiting search results with a library or library group, use the item's home library, or holding library, or both.", 'Choice')
24194     });
24195
24196     NewVersion( $DBversion, 21249, "Adding new system preference SearchLimitLibrary" );
24197 }
24198
24199 $DBversion = '20.12.00.046';
24200 if( CheckVersion( $DBversion ) ) {
24201     unless ( column_exists('message_queue', 'delivery_note') ) {
24202         $dbh->do(q{
24203             ALTER TABLE message_queue ADD delivery_note mediumtext AFTER content_type
24204         });
24205     }
24206
24207     NewVersion( $DBversion, 14723, "Additional delivery notes to messages" );
24208 }
24209
24210 $DBversion = '20.12.00.047';
24211 if( CheckVersion( $DBversion ) ) {
24212
24213     $dbh->do(q{
24214         DELETE FROM systempreferences
24215         WHERE variable IN
24216             ('EnablePayPalOpacPayments',
24217              'PayPalChargeDescription',
24218              'PayPalPwd',
24219              'PayPalReturnURL',
24220              'PayPalSandboxMode',
24221              'PayPalSignature',
24222              'PayPalUser');
24223     });
24224
24225     NewVersion( $DBversion, 23215, "Remove core PayPal support in favor of the use of plugins" );
24226 }
24227
24228 $DBversion = '20.12.00.048';
24229 if( CheckVersion( $DBversion ) ) {
24230
24231     # This DB upgrade has been commented out because it removes
24232     # actively used data, the relationship columns will be added back
24233
24234     # if ( column_exists( 'borrowers', 'relationship' ) ) {
24235     #     $dbh->do(q{
24236     #         ALTER TABLE borrowers DROP COLUMN relationship
24237     #     });
24238     # }
24239
24240     # if ( column_exists( 'deletedborrowers', 'relationship' ) ) {
24241     #     $dbh->do(q{
24242     #         ALTER TABLE deletedborrowers DROP COLUMN relationship
24243     #     });
24244     # }
24245
24246     # if ( column_exists( 'borrower_modifications', 'relationship' ) ) {
24247     #     $dbh->do(q{
24248     #         ALTER TABLE borrower_modifications DROP COLUMN relationship
24249     #     });
24250     # }
24251
24252     NewVersion( $DBversion, 26995, "[SKIP] Drop column relationship from borrower tables [not executed]");
24253 }
24254
24255 $DBversion = '20.12.00.049';
24256 if ( CheckVersion($DBversion) ) {
24257     $dbh->do(q{
24258         UPDATE action_logs SET module = 'CLAIMS'
24259         WHERE module = 'ACQUISITIONS' AND ( action = 'SERIAL CLAIM' OR action = 'ACQUISITION CLAIM')
24260     });
24261
24262     $dbh->do(q{
24263         UPDATE systempreferences SET variable = 'ClaimsLog' WHERE variable = 'LetterLog';
24264     });
24265
24266     NewVersion( $DBversion, 28108, "Move action logs 'SERIAL CLAIM' and 'ACQUISITION CLAIM' to a new 'CLAIMS' module" );
24267 }
24268
24269 $DBversion = '20.12.00.050';
24270 if ( CheckVersion($DBversion) ) {
24271     $dbh->do(q{
24272         INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
24273         ('OpacHiddenItemsHidesRecord','1','','Hide bibliographic record when all its items are hidden because of OpacHiddenItems','YesNo')
24274     });
24275
24276     NewVersion( $DBversion, 28108, "Add new systempreference OpacHiddenItemsHidesRecord" );
24277 }
24278
24279 $DBversion = '21.05.00.000';
24280 if( CheckVersion( $DBversion ) ) {
24281     NewVersion( $DBversion, "", "Koha 21.05.00 release" );
24282 }
24283
24284 $DBversion = '21.06.00.000';
24285 if( CheckVersion( $DBversion ) ) {
24286     NewVersion( $DBversion, "", ["🎵 Run, rabbit run. 🎶", "Dig that hole, forget the sun,", "And when at last the work is done", "Don't sit down it's time to dig another one."] );
24287 }
24288
24289 $DBversion = '21.06.00.001';
24290 if ( CheckVersion($DBversion) ) {
24291     $dbh->do('DELETE FROM sessions');
24292     $dbh->do('ALTER TABLE sessions MODIFY a_session LONGBLOB NOT NULL');
24293
24294     NewVersion( $DBversion, '28489', 'Modify sessions.a_session from longtext to longblob' );
24295 }
24296
24297 $DBversion = '21.06.00.002';
24298 if( CheckVersion( $DBversion ) ) {
24299     if( !column_exists( 'borrower_modifications', 'relationship' ) ) {
24300       $dbh->do(q{
24301           ALTER TABLE borrower_modifications ADD COLUMN `relationship` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL AFTER `borrowernotes`
24302       });
24303     }
24304
24305     if( !column_exists( 'borrowers', 'relationship' ) ) {
24306       $dbh->do(q{
24307           ALTER TABLE borrowers ADD COLUMN `relationship` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'used for children to include the relationship to their guarantor' AFTER `borrowernotes`
24308       });
24309     }
24310
24311     if( !column_exists( 'deletedborrowers', 'relationship' ) ) {
24312       $dbh->do(q{
24313           ALTER TABLE deletedborrowers ADD COLUMN `relationship` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'used for children to include the relationship to their guarantor' AFTER `borrowernotes`
24314       });
24315     }
24316
24317     NewVersion( $DBversion, 28490, "Bring back accidentally deleted relationship columns");
24318 }
24319
24320 $DBversion = '21.06.00.003';
24321 if( CheckVersion( $DBversion ) ) {
24322
24323     # Add 'WrongTransfer' to branchtransfers cancellation_reason enum
24324     $dbh->do(
24325         q{
24326             ALTER TABLE
24327                 `branchtransfers`
24328             MODIFY COLUMN
24329                 `cancellation_reason` enum(
24330                     'Manual',
24331                     'StockrotationAdvance',
24332                     'StockrotationRepatriation',
24333                     'ReturnToHome',
24334                     'ReturnToHolding',
24335                     'RotatingCollection',
24336                     'Reserve',
24337                     'LostReserve',
24338                     'CancelReserve',
24339                     'ItemLost',
24340                     'WrongTransfer'
24341                 )
24342             AFTER `comments`
24343           }
24344     );
24345
24346     NewVersion( $DBversion, 24434, "Add 'WrongTransfer' to branchtransfers.cancellation_reason enum");
24347 }
24348
24349 $DBversion = '21.06.00.004';
24350 if ( CheckVersion($DBversion) ) {
24351
24352     $dbh->do(q{
24353         INSERT IGNORE permissions (module_bit, code, description)
24354         VALUES
24355         (4, 'delete_borrowers', 'Delete borrowers')
24356     });
24357
24358     $dbh->do(q{
24359         INSERT IGNORE INTO user_permissions (borrowernumber, module_bit, code)
24360         SELECT borrowernumber, 4, 'delete_borrowers' FROM user_permissions WHERE code = 'edit_borrowers'
24361     });
24362
24363     NewVersion( $DBversion, 15788, "Split edit_borrowers permission" );
24364 }
24365
24366 $DBversion = '21.06.00.005';
24367 if( CheckVersion( $DBversion ) ) {
24368     $dbh->do( q{
24369         INSERT IGNORE INTO systempreferences (variable, value, explanation, options, type)
24370         VALUES ('NewsLog', '0', 'If enabled, log OPAC News changes', '', 'YesNo')
24371     });
24372
24373     NewVersion( $DBversion, 26205, "Add new system preference NewsLog to log news changes");
24374 }
24375
24376 $DBversion = '21.06.00.006';
24377 if( CheckVersion( $DBversion ) ){
24378     unless( column_exists( 'course_items', 'biblionumber') ) {
24379         $dbh->do(q{ ALTER TABLE course_items ADD `biblionumber` int(11) AFTER `itemnumber` });
24380
24381         $dbh->do(q{
24382             UPDATE course_items
24383             LEFT JOIN items ON items.itemnumber=course_items.itemnumber
24384             SET course_items.biblionumber=items.biblionumber
24385             WHERE items.itemnumber IS NOT NULL
24386         });
24387
24388         $dbh->do(q{ ALTER TABLE course_items MODIFY COLUMN `biblionumber` INT(11) NOT NULL });
24389
24390         $dbh->do(q{ ALTER TABLE course_items ADD CONSTRAINT `fk_course_items_biblionumber` FOREIGN KEY (`biblionumber`) REFERENCES `biblio` (`biblionumber`) ON DELETE CASCADE ON UPDATE CASCADE });
24391         $dbh->do(q{ ALTER TABLE course_items CHANGE `itemnumber` `itemnumber` int(11) DEFAULT NULL });
24392     }
24393
24394     NewVersion( $DBversion, 14237, ["Add course_items.biblionumber column", "Add fk_course_items_biblionumber constraint", "Change course_items.itemnumber to allow NULL values"] );
24395 }
24396
24397 $DBversion = '21.06.00.007';
24398 if( CheckVersion( $DBversion ) ) {
24399     if( !column_exists( 'borrowers', 'primary_contact_method' ) ) {
24400         $dbh->do( "ALTER TABLE `borrowers` ADD COLUMN `primary_contact_method` VARCHAR(45) DEFAULT NULL AFTER `autorenew_checkouts`" );
24401     }
24402
24403     if( !column_exists( 'deletedborrowers', 'primary_contact_method' ) ) {
24404         $dbh->do( "ALTER TABLE `deletedborrowers` ADD COLUMN `primary_contact_method` VARCHAR(45) DEFAULT NULL AFTER `autorenew_checkouts`" );
24405     }
24406
24407     if( !column_exists( 'borrower_modifications', 'primary_contact_method' ) ) {
24408         $dbh->do( "ALTER TABLE `borrower_modifications` ADD COLUMN `primary_contact_method` VARCHAR(45) DEFAULT NULL AFTER `gdpr_proc_consent`" );
24409     }
24410
24411     NewVersion( $DBversion, 11879, "Add a new field to patron record: main contact method");
24412 }
24413
24414 # SEE bug 13068
24415 # if there is anything in the atomicupdate, read and execute it.
24416 my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
24417 opendir( my $dirh, $update_dir );
24418 foreach my $file ( sort readdir $dirh ) {
24419     next if $file !~ /\.(sql|perl)$/;  #skip other files
24420     next if $file eq 'skeleton.perl'; # skip the skeleton file
24421     print "DEV atomic update: $file\n";
24422     if ( $file =~ /\.sql$/ ) {
24423         my $installer = C4::Installer->new();
24424         my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
24425     } elsif ( $file =~ /\.perl$/ ) {
24426         my $code = read_file( $update_dir . $file );
24427         eval $code; ## no critic (StringyEval)
24428         say "Atomic update generated errors: $@" if $@;
24429     }
24430 }
24431
24432 =head1 FUNCTIONS
24433
24434 =head2 DropAllForeignKeys($table)
24435
24436 Drop all foreign keys of the table $table
24437
24438 =cut
24439
24440 sub DropAllForeignKeys {
24441     my ($table) = @_;
24442     # get the table description
24443     my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
24444     $sth->execute;
24445     my $vsc_structure = $sth->fetchrow;
24446     # split on CONSTRAINT keyword
24447     my @fks = split /CONSTRAINT /,$vsc_structure;
24448     # parse each entry
24449     foreach (@fks) {
24450         # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
24451         $_ = /(.*) FOREIGN KEY.*/;
24452         my $id = $1;
24453         if ($id) {
24454             # we have found 1 foreign, drop it
24455             $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
24456             $id="";
24457         }
24458     }
24459 }
24460
24461
24462 =head2 TransformToNum
24463
24464 Transform the Koha version from a 4 parts string
24465 to a number, with just 1 .
24466
24467 =cut
24468
24469 sub TransformToNum {
24470     my $version = shift;
24471     # remove the 3 last . to have a Perl number
24472     $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
24473     # three X's at the end indicate that you are testing patch with dbrev
24474     # change it into 999
24475     # prevents error on a < comparison between strings (should be: lt)
24476     $version =~ s/XXX$/999/;
24477     return $version;
24478 }
24479
24480 =head2 SetVersion
24481
24482 set the DBversion in the systempreferences
24483
24484 =cut
24485
24486 sub SetVersion {
24487     return if $_[0]=~ /XXX$/;
24488       #you are testing a patch with a db revision; do not change version
24489     my $kohaversion = TransformToNum($_[0]);
24490     if (C4::Context->preference('Version')) {
24491       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
24492       $finish->execute($kohaversion);
24493     } else {
24494       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')");
24495       $finish->execute($kohaversion);
24496     }
24497     C4::Context::clear_syspref_cache(); # invalidate cached preferences
24498 }
24499
24500 sub NewVersion {
24501     my ( $DBversion, $bug_number, $descriptions ) = @_;
24502
24503     SetVersion($DBversion);
24504
24505     unless ( ref($descriptions) ) {
24506         $descriptions = [ $descriptions ];
24507     }
24508     my $first = 1;
24509     my $time = POSIX::strftime("%H:%M:%S",localtime);
24510     for my $description ( @$descriptions ) {
24511         if ( @$descriptions > 1 ) {
24512             if ( $first ) {
24513                 unless ( $bug_number ) {
24514                     say sprintf "Upgrade to %s done [%s]: %s", $DBversion, $time, $description;
24515                 } else {
24516                     say sprintf "Upgrade to %s done [%s]: Bug %5s - %s", $DBversion, $time, $bug_number, $description;
24517                 }
24518             } else {
24519                 say sprintf "\t\t\t\t\t\t   - %s", $description;
24520             }
24521         } else {
24522             unless ( $bug_number ) {
24523                 say sprintf "Upgrade to %s done [%s]: %s", $DBversion, $time, $description;
24524             } else {
24525                 say sprintf "Upgrade to %s done [%s]: Bug %5s - %s", $DBversion, $time, $bug_number, $description;
24526             }
24527         }
24528         $first = 0;
24529     }
24530 }
24531
24532 =head2 CheckVersion
24533
24534 Check whether a given update should be run when passed the proposed version
24535 number. The update will always be run if the proposed version is greater
24536 than the current database version and less than or equal to the version in
24537 kohaversion.pl. The update is also run if the version contains XXX, though
24538 this behavior will be changed following the adoption of non-linear updates
24539 as implemented in bug 7167.
24540
24541 =cut
24542
24543 sub CheckVersion {
24544     my ($proposed_version) = @_;
24545     my $version_number = TransformToNum($proposed_version);
24546
24547     # The following line should be deleted when bug 7167 is pushed
24548     return 1 if ( $proposed_version =~ m/XXX/ );
24549
24550     if ( C4::Context->preference("Version") < $version_number
24551         && $version_number <= TransformToNum( $Koha::VERSION ) )
24552     {
24553         return 1;
24554     }
24555     else {
24556         return 0;
24557     }
24558 }
24559
24560 sub sanitize_zero_date {
24561     my ( $table_name, $column_name ) = @_;
24562
24563     my (undef, $datatype) = $dbh->selectrow_array(qq|
24564         SHOW COLUMNS FROM $table_name WHERE Field = ?|, undef, $column_name);
24565
24566     if ( $datatype eq 'date' ) {
24567         $dbh->do(qq|
24568             UPDATE $table_name
24569             SET $column_name = NULL
24570             WHERE CAST($column_name AS CHAR(10)) = '0000-00-00';
24571         |);
24572     } else {
24573         $dbh->do(qq|
24574             UPDATE $table_name
24575             SET $column_name = NULL
24576             WHERE CAST($column_name AS CHAR(19)) = '0000-00-00 00:00:00';
24577         |);
24578     }
24579 }
24580
24581 exit;